content stringlengths 5 1.05M |
|---|
--[[
module: CompositeEntity
author: DylanYang
time: 2021-02-24 21:35:14
idea: Compared to 'CoarseGrainedObject', it is only one more level and can contain other content.
advance:
]]
local CoarseGrainedObject = require("patterns.j2ee.compositeEntity.CoarseGrainedObject")
local _M = Class("CompositeEntity")
local public = _M.public
_M.cgo = nil
function _M:ctor()
self.cgo = CoarseGrainedObject.new()
end
function public:SetData(data1, data2)
self.cgo:SetData(data1, data2)
end
function public:GetData()
return self.cgo:GetData()
end
return _M |
local washopen = {
[1] = {ID=1,Level=0,equipPart=2,number=0},
[2] = {ID=2,Level=0,equipPart=3,number=0},
[3] = {ID=3,Level=0,equipPart=4,number=0},
[4] = {ID=4,Level=0,equipPart=5,number=0},
[5] = {ID=5,Level=0,equipPart=6,number=0},
[6] = {ID=6,Level=5,equipPart=2,number=0},
[7] = {ID=7,Level=5,equipPart=3,number=0},
[8] = {ID=8,Level=5,equipPart=4,number=0},
[9] = {ID=9,Level=5,equipPart=5,number=0},
[10] = {ID=10,Level=5,equipPart=6,number=0},
[11] = {ID=11,Level=10,equipPart=2,number=0},
[12] = {ID=12,Level=10,equipPart=3,number=0},
[13] = {ID=13,Level=10,equipPart=4,number=0},
[14] = {ID=14,Level=10,equipPart=5,number=0},
[15] = {ID=15,Level=10,equipPart=6,number=0},
[16] = {ID=16,Level=15,equipPart=2,number=0},
[17] = {ID=17,Level=15,equipPart=3,number=0},
[18] = {ID=18,Level=15,equipPart=4,number=0},
[19] = {ID=19,Level=15,equipPart=5,number=0},
[20] = {ID=20,Level=15,equipPart=6,number=0},
[21] = {ID=21,Level=20,equipPart=2,number=0},
[22] = {ID=22,Level=20,equipPart=3,number=0},
[23] = {ID=23,Level=20,equipPart=4,number=0},
[24] = {ID=24,Level=20,equipPart=5,number=0},
[25] = {ID=25,Level=20,equipPart=6,number=0},
[26] = {ID=26,Level=25,equipPart=2,number=0},
[27] = {ID=27,Level=25,equipPart=3,number=0},
[28] = {ID=28,Level=25,equipPart=4,number=0},
[29] = {ID=29,Level=25,equipPart=5,number=0},
[30] = {ID=30,Level=25,equipPart=6,number=0},
[31] = {ID=31,Level=30,equipPart=2,number=4},
[32] = {ID=32,Level=30,equipPart=3,number=4},
[33] = {ID=33,Level=30,equipPart=4,number=4},
[34] = {ID=34,Level=30,equipPart=5,number=4},
[35] = {ID=35,Level=30,equipPart=6,number=4},
[36] = {ID=36,Level=35,equipPart=2,number=4},
[37] = {ID=37,Level=35,equipPart=3,number=4},
[38] = {ID=38,Level=35,equipPart=4,number=4},
[39] = {ID=39,Level=35,equipPart=5,number=4},
[40] = {ID=40,Level=35,equipPart=6,number=4},
[41] = {ID=41,Level=40,equipPart=2,number=4},
[42] = {ID=42,Level=40,equipPart=3,number=4},
[43] = {ID=43,Level=40,equipPart=4,number=4},
[44] = {ID=44,Level=40,equipPart=5,number=4},
[45] = {ID=45,Level=40,equipPart=6,number=4},
[46] = {ID=46,Level=45,equipPart=2,number=4},
[47] = {ID=47,Level=45,equipPart=3,number=4},
[48] = {ID=48,Level=45,equipPart=4,number=4},
[49] = {ID=49,Level=45,equipPart=5,number=4},
[50] = {ID=50,Level=45,equipPart=6,number=4},
[51] = {ID=51,Level=50,equipPart=2,number=4},
[52] = {ID=52,Level=50,equipPart=3,number=4},
[53] = {ID=53,Level=50,equipPart=4,number=4},
[54] = {ID=54,Level=50,equipPart=5,number=4},
[55] = {ID=55,Level=50,equipPart=6,number=4},
[56] = {ID=56,Level=55,equipPart=2,number=4},
[57] = {ID=57,Level=55,equipPart=3,number=4},
[58] = {ID=58,Level=55,equipPart=4,number=4},
[59] = {ID=59,Level=55,equipPart=5,number=4},
[60] = {ID=60,Level=55,equipPart=6,number=4},
[61] = {ID=61,Level=60,equipPart=2,number=4},
[62] = {ID=62,Level=60,equipPart=3,number=4},
[63] = {ID=63,Level=60,equipPart=4,number=4},
[64] = {ID=64,Level=60,equipPart=5,number=4},
[65] = {ID=65,Level=60,equipPart=6,number=4},
[66] = {ID=66,Level=65,equipPart=2,number=4},
[67] = {ID=67,Level=65,equipPart=3,number=4},
[68] = {ID=68,Level=65,equipPart=4,number=4},
[69] = {ID=69,Level=65,equipPart=5,number=4},
[70] = {ID=70,Level=65,equipPart=6,number=4},
[71] = {ID=71,Level=70,equipPart=2,number=4},
[72] = {ID=72,Level=70,equipPart=3,number=4},
[73] = {ID=73,Level=70,equipPart=4,number=4},
[74] = {ID=74,Level=70,equipPart=5,number=4},
[75] = {ID=75,Level=70,equipPart=6,number=4},
[76] = {ID=76,Level=75,equipPart=2,number=4},
[77] = {ID=77,Level=75,equipPart=3,number=4},
[78] = {ID=78,Level=75,equipPart=4,number=4},
[79] = {ID=79,Level=75,equipPart=5,number=4},
[80] = {ID=80,Level=75,equipPart=6,number=4},
[81] = {ID=81,Level=80,equipPart=2,number=4},
[82] = {ID=82,Level=80,equipPart=3,number=4},
[83] = {ID=83,Level=80,equipPart=4,number=4},
[84] = {ID=84,Level=80,equipPart=5,number=4},
[85] = {ID=85,Level=80,equipPart=6,number=4},
[86] = {ID=86,Level=85,equipPart=2,number=4},
[87] = {ID=87,Level=85,equipPart=3,number=4},
[88] = {ID=88,Level=85,equipPart=4,number=4},
[89] = {ID=89,Level=85,equipPart=5,number=4},
[90] = {ID=90,Level=85,equipPart=6,number=4},
[91] = {ID=91,Level=90,equipPart=2,number=4},
[92] = {ID=92,Level=90,equipPart=3,number=4},
[93] = {ID=93,Level=90,equipPart=4,number=4},
[94] = {ID=94,Level=90,equipPart=5,number=4},
[95] = {ID=95,Level=90,equipPart=6,number=4},
[96] = {ID=96,Level=95,equipPart=2,number=4},
[97] = {ID=97,Level=95,equipPart=3,number=4},
[98] = {ID=98,Level=95,equipPart=4,number=4},
[99] = {ID=99,Level=95,equipPart=5,number=4},
[100] = {ID=100,Level=95,equipPart=6,number=4},
[101] = {ID=101,Level=100,equipPart=2,number=4},
[102] = {ID=102,Level=100,equipPart=3,number=4},
[103] = {ID=103,Level=100,equipPart=4,number=4},
[104] = {ID=104,Level=100,equipPart=5,number=4},
[105] = {ID=105,Level=100,equipPart=6,number=4},
}
return washopen
|
function onCreate()
makeLuaSprite('BG', 'gold_spookyhouse', -300, -0)
addLuaSprite('BG', false)
end
|
-- copy all globals into locals, some locals are prefixed with a G to reduce name clashes
local coroutine,package,string,table,math,io,os,debug,assert,dofile,error,_G,getfenv,getmetatable,ipairs,Gload,loadfile,loadstring,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,_VERSION,xpcall,module,require=coroutine,package,string,table,math,io,os,debug,assert,dofile,error,_G,getfenv,getmetatable,ipairs,load,loadfile,loadstring,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,_VERSION,xpcall,module,require
--[[#lua.wetgenes
local wetgenes=require("wetgenes")
Simple generic functions that are intended to be useful for all
wetgenes.* modules.
]]
local M={ modname=(...) } ; package.loaded[M.modname]=M
-----------------------------------------------------------------------------
--[[#lua.wetgenes.safecall
... = wetgenes.safecall(func,...)
Call a function func(...) wrapped in an xpcall to catch and ignore
errors, the errors are printed to stderr with a traceback and the
function returns nil on an error.
So provided the function returns not nil on success then you can still
tell if the function completed OK. Best to use for things that are OK
to fail and the rest of the code will work around it.
]]
-----------------------------------------------------------------------------
M.safecall=function(f,...)
local a={...}
local r={ xpcall(function() return f(unpack(a)) end,function(err) return "safecall ignoring error: "..debug.traceback(err).."\n" end) }
if not r[1] then io.stderr:write(r[2]) return end -- print error and return nil on error
return select(2,unpack(r))
end
-----------------------------------------------------------------------------
--[[#lua.wetgenes.safewrap
savefunc = wetgenes.safecall(func)
Wrap a funciton in safecall, so it will never generate errors but can
be called as normal.
]]
-----------------------------------------------------------------------------
M.safewrap=function(f)
return function(...)
return M.safecall(f,...)
end
end
-----------------------------------------------------------------------------
--[[#lua.wetgenes.export
... = wetgenes.export(table,...)
Export multiple names from this table as multiple returns, can be
used to pull functions out of this module and into locals like so
local export,lookup,set_env=require("wetgenes"):export("export","lookup","set_env")
Or copy it into other modules to provide them with the same functionality.
M.lookup=require("wetgenes").lookup
]]
-----------------------------------------------------------------------------
M.export=function(env,...)
local tab={}
for i,v in ipairs{...} do
tab[i]=env[v]
end
return unpack(tab)
end
-----------------------------------------------------------------------------
--[[#lua.wetgenes.lookup
value = wetgenes.lookup(table,...)
Safe recursive lookup within a table that returns nil if any part of
the lookup is nil so we never cause an error but just return nil.
This is intended to replace the following sort of code
a = b and b.c and b.c.d and b.c.d.e
To get e only if all of its parent bits exist and not to cause any
error if they do not. instead use
a = lookup(b,"c","d","e")
]]
-----------------------------------------------------------------------------
M.lookup=function(tab,...)
for i,v in ipairs{...} do
if type(tab)~="table" then return nil end
tab=tab[v]
end
return tab
end
-----------------------------------------------------------------------------
--[[#lua.wetgenes.set_env
local _ENV=set_env(new_environment)
Since setfenv is going away in lua 5.2 here is a plan to future
proof code that wants to control its own environment
Specifically this is for loading functions sabdboxed into a given
table, which we need to do from time to time.
we set the environment of the code that called us only if setfenv
exists and we always return the new environment
So the following incantation can be used to change the current environment and
it should work exactly the same in lua 5.1 or 5.2
local _ENV=set_env(new_environment)
]]
-----------------------------------------------------------------------------
M.set_env=function(env)
if setfenv then setfenv(2,env) end
return env
end
-----------------------------------------------------------------------------
--[[#lua.wetgenes.set_env
gamecake -e" require('wetgenes').savescripts('./') "
Run the above from the command line.
This will export all the gamecake internal strings into the file system
it is saved into the current directory so be careful where you run it.
Game Cake checks the files system first so, these files can be modified
and they will replace the built in versions.
gamecake -e" require('wetgenes').savescripts('./internal/') "
This is a safer version that will save the files to ./internal/lua/*
instead of just ./lua/*
]]
-----------------------------------------------------------------------------
M.savescripts=function(basedir)
assert(basedir, "missing destination path")
local wbake=require("wetgenes.bake")
local wgc=require("wetgenes.gamecake.core")
local names=wgc.list_cache_strings()
for n,v in pairs(names) do
local fname
if "lua/"==v:sub(1,4) then -- these are extra files, eg .glsl code
fname=v
else -- these are modules, so need to be turned into files
fname="lua/"..v:gsub("%.","/")..".lua"
end
local data=wgc.get_cache_string(v)
print( "saving" , #data , " bytes as ", basedir..fname )
wbake.create_dir_for_file( basedir..fname )
wbake.writefile( basedir..fname , data )
end
end
|
print("CalmAI Loaded. AI is now Relaxed! Coded by NickThe0ne") |
--translated by Nick#6127 from GFL Teams on Discord
return {
["CONGRATS_COMMAND"] = "Giver dig konfetti og festlige lyde; dog kun for dig.",
["CONGRATS_GLOBAL"] = "Tillyke, du slog rekorden for højeste runde på serveren!",
["CONGRATS_MAP"] = "Tillyke, du slog rekorden for højeste runde i denne bane! Prøv at se om du kan slå serverens globale rekord på %u.",
["GUI_BUTTON"] = "Åben Hæderstavlen",
["GUI_ENTRY"] = "%s - Runde %u",
["GUI_ENTRY_MAP"] = "%s\n\n%u drab",
["GUI_ENTRY_MAP_LEFT"] = "%s\nTilbage i runden %u\n%u drab",
["GUI_TITLE"] = "Hæderstavlen",
["GUI_TITLE_MAP"] = "Hæderstavlen - %s"
} |
print("Loading ReportScreen.lua from Better Report Screen version "..GlobalParameters.BRS_VERSION_MAJOR.."."..GlobalParameters.BRS_VERSION_MINOR);
-- ===========================================================================
-- ReportScreen
-- All the data
-- Copyright 2016-2018, Firaxis Games
-- ===========================================================================
include("CitySupport");
include("Civ6Common");
include("InstanceManager");
include("SupportFunctions");
include("TabSupport");
include("LeaderIcon");
-- exposing functions and variables
if not ExposedMembers.RMA then ExposedMembers.RMA = {} end;
local RMA = ExposedMembers.RMA;
-- Expansions check
local bIsRiseFall:boolean = Modding.IsModActive("1B28771A-C749-434B-9053-D1380C553DE9"); -- Rise & Fall
print("Rise & Fall :", (bIsRiseFall and "YES" or "no"));
local bIsGatheringStorm:boolean = Modding.IsModActive("4873eb62-8ccc-4574-b784-dda455e74e68"); -- Gathering Storm
print("Gathering Storm:", (bIsGatheringStorm and "YES" or "no"));
local bIsMonopolies:boolean = GameCapabilities.HasCapability("CAPABILITY_MONOPOLIES"); -- Monopoly and Corporations Mode
print("Monopolies :", (bIsMonopolies and "YES" or "no"));
-- configuration options
local bOptionModifiers:boolean = ( GlobalParameters.BRS_OPTION_MODIFIERS == 1 );
-- ===========================================================================
-- DEBUG
-- Toggle these for temporary debugging help.
-- ===========================================================================
local m_debugNumResourcesStrategic :number = 0; -- (0) number of extra strategics to show for screen testing.
local m_debugNumBonuses :number = 0; -- (0) number of extra bonuses to show for screen testing.
local m_debugNumResourcesLuxuries :number = 0; -- (0) number of extra luxuries to show for screen testing.
-- ===========================================================================
-- CONSTANTS
-- ===========================================================================
local LL = Locale.Lookup;
local ENDCOLOR :string = "[ENDCOLOR]";
local DARKEN_CITY_INCOME_AREA_ADDITIONAL_Y :number = 6;
local DATA_FIELD_SELECTION :string = "Selection";
local SIZE_HEIGHT_BOTTOM_YIELDS :number = 135;
local SIZE_HEIGHT_PADDING_BOTTOM_ADJUST :number = 87; -- (Total Y - (scroll area + THIS PADDING)) = bottom area
local INDENT_STRING :string = " ";
local TOOLTIP_SEP :string = "-------------------";
local TOOLTIP_SEP_NEWLINE :string = "[NEWLINE]"..TOOLTIP_SEP.."[NEWLINE]";
local GOSSIP_GROUP_TYPES :table = {
"ALL",
"BARBARIAN",
"DIPLOMACY",
"CITY",
"CULTURE",
"DISCOVER",
"ESPIONAGE",
"GREATPERSON",
"MILITARY",
"RELIGION",
"SCIENCE",
"SETTLEMENT",
"VICTORY"
};
-- Mapping of unit type to cost.
local UnitCostMap:table = {};
do
for row in GameInfo.Units() do
UnitCostMap[row.UnitType] = row.Maintenance;
end
end
--BRS !! Added function to sort out tables for units
-- Infixo: this is only used by Upgrade Callback; parent will be used a flag; must be set to nil when leaving report screen
local tUnitSort = { type = "", group = "", parent = nil };
-- Infixo: this is an iterator to replace pairs
-- it sorts t and returns its elements one by one
-- source: https://stackoverflow.com/questions/15706270/sort-a-table-in-lua
function spairs( t, order_function )
local keys:table = {}; -- actual table of keys that will bo sorted
for key,_ in pairs(t) do table.insert(keys, key); end
if order_function then
table.sort(keys, function(a,b) return order_function(t, a, b) end)
else
table.sort(keys)
end
-- iterator here
local i:number = 0;
return function()
i = i + 1;
if keys[i] then
return keys[i], t[keys[i]]
end
end
end
-- !! end of function
-- ===========================================================================
-- VARIABLES
-- ===========================================================================
m_simpleIM = InstanceManager:new("SimpleInstance", "Top", Controls.Stack); -- Non-Collapsable, simple
m_tabIM = InstanceManager:new("TabInstance", "Button", Controls.TabContainer);
m_strategicResourcesIM = InstanceManager:new("ResourceAmountInstance", "Info", Controls.StrategicResources);
m_bonusResourcesIM = InstanceManager:new("ResourceAmountInstance", "Info", Controls.BonusResources);
m_luxuryResourcesIM = InstanceManager:new("ResourceAmountInstance", "Info", Controls.LuxuryResources);
local m_groupIM :table = InstanceManager:new("GroupInstance", "Top", Controls.Stack); -- Collapsable
m_kCityData = nil;
m_tabs = nil;
m_kResourceData = nil;
local m_kCityTotalData :table = nil;
local m_kUnitData :table = nil; -- TODO: Show units by promotion class
local m_kDealData :table = nil;
local m_uiGroups :table = nil; -- Track the groups on-screen for collapse all action.
local m_isCollapsing :boolean = true;
--Gossip filtering
local m_kGossipInstances:table = {};
local m_groupFilter:number = 1; -- (1) Indicates Unfiltered by this criteria (Group Type Index)
local m_leaderFilter:number = -1; -- (-1) Indicates Unfilitered by this criteria (PlayerID)
--BRS !! new variables
local m_kCurrentDeals :table = nil;
local m_kUnitDataReport :table = nil;
local m_kPolicyData :table = nil;
local m_kMinorData :table = nil;
local m_kModifiers :table = nil; -- to calculate yield per pop and other modifier-ralated effects on the city level
local m_kModifiersUnits :table = nil; -- to show various abilities and effects
-- !!
-- Remember last tab variable: ARISTOS
m_kCurrentTab = 1;
-- !!
-- ===========================================================================
-- Time helpers and debug routines
-- ===========================================================================
local fStartTime1:number = 0.0
local fStartTime2:number = 0.0
function Timer1Start()
fStartTime1 = Automation.GetTime()
--print("Timer1 Start", fStartTime1)
end
function Timer2Start()
fStartTime2 = Automation.GetTime()
--print("Timer2 Start() (start)", fStartTime2)
end
function Timer1Tick(txt:string)
print("Timer1 Tick", txt, string.format("%5.3f", Automation.GetTime()-fStartTime1))
end
function Timer2Tick(txt:string)
print("Timer2 Tick", txt, string.format("%5.3f", Automation.GetTime()-fStartTime2))
end
-- debug routine - prints a table (no recursion)
function dshowtable(tTable:table)
if tTable == nil then print("dshowtable: table is nil"); return; end
for k,v in pairs(tTable) do
print(k, type(v), tostring(v));
end
end
-- debug routine - prints a table, and tables inside recursively (up to 5 levels)
function dshowrectable(tTable:table, iLevel:number)
local level:number = 0;
if iLevel ~= nil then level = iLevel; end
for k,v in pairs(tTable) do
print(string.rep("---:",level), k, type(v), tostring(v));
if type(v) == "table" and level < 5 then dshowrectable(v, level+1); end
end
end
-- ===========================================================================
-- Updated functions from Civ6Common, to include rounding to 1 decimal digit
-- ===========================================================================
function toPlusMinusString( value:number )
if value == 0 then return "0"; end
return Locale.ToNumber(math.floor((value*10)+0.5)/10, "+#,###.#;-#,###.#");
end
function toPlusMinusNoneString( value:number )
if value == 0 then return " "; end
return Locale.ToNumber(math.floor((value*10)+0.5)/10, "+#,###.#;-#,###.#");
end
-- ===========================================================================
-- Single exit point for display
-- ===========================================================================
function Close()
if not ContextPtr:IsHidden() then
UI.PlaySound("UI_Screen_Close");
end
UIManager:DequeuePopup(ContextPtr);
LuaEvents.ReportScreen_Closed();
--print("Closing... current tab is:", m_kCurrentTab);
tUnitSort.parent = nil; -- unit upgrades off the report screen should not call re-sort
end
-- ===========================================================================
-- UI Callback
-- ===========================================================================
function OnCloseButton()
Close();
end
-- ===========================================================================
-- Single entry point for display
-- ===========================================================================
function Open( tabToOpen:number )
--print("FUN Open()", tabToOpen);
UIManager:QueuePopup( ContextPtr, PopupPriority.Medium );
Controls.ScreenAnimIn:SetToBeginning();
Controls.ScreenAnimIn:Play();
UI.PlaySound("UI_Screen_Open");
--LuaEvents.ReportScreen_Opened();
-- BRS !! new line to add new variables
Timer2Start()
m_kCityData, m_kCityTotalData, m_kResourceData, m_kUnitData, m_kDealData, m_kCurrentDeals, m_kUnitDataReport = GetData();
UpdatePolicyData();
UpdateMinorData();
Timer2Tick("GetData")
-- To remember the last opened tab when the report is re-opened: ARISTOS
if tabToOpen ~= nil then m_kCurrentTab = tabToOpen; end
Resize();
m_tabs.SelectTab( m_kCurrentTab );
-- show number of cities in the title bar
local tTT:table = {};
local iWon:number, iDis:number, iBul:number, iPop:number = 0, 0, 0, 0;
for _,city in pairs(m_kCityData) do
iWon = iWon + #city.Wonders;
iDis = iDis + city.DistrictsNum;
iBul = iBul + city.BuildingsNum;
iPop = iPop + city.Population;
end
local iCiv:number, iMil:number = 0, 0;
local playerID:number = Game.GetLocalPlayer();
if playerID ~= PlayerTypes.NONE and playerID ~= PlayerTypes.OBSERVER then
for _,unit in Players[playerID]:GetUnits():Members() do
if GameInfo.Units[unit:GetUnitType()].FormationClass == "FORMATION_CLASS_CIVILIAN" then iCiv = iCiv + 1; else iMil = iMil + 1; end
end -- for
end -- if
Controls.TotalsLabel:SetText( Locale.Lookup("LOC_DIPLOMACY_DEAL_CITIES").." "..tostring(Players[Game.GetLocalPlayer()]:GetCities():GetCount()) );
table.insert(tTT, Locale.Lookup("LOC_RAZE_CITY_POPULATION_LABEL").." "..tostring(iPop));
table.insert(tTT, Locale.Lookup("LOC_TECH_FILTER_WONDERS")..": "..tostring(iWon));
table.insert(tTT, Locale.Lookup("LOC_DEAL_CITY_DISTRICTS_TOOLTIP").." "..tostring(iDis));
table.insert(tTT, Locale.Lookup("LOC_TOOLTIP_PLOT_BUILDINGS_TEXT").." "..tostring(iBul));
table.insert(tTT, Locale.Lookup("LOC_TECH_FILTER_UNITS")..": "..tostring(iCiv+iMil));
table.insert(tTT, Locale.Lookup("LOC_MILITARY")..": "..tostring(iMil));
table.insert(tTT, Locale.Lookup("LOC_FORMATION_CLASS_CIVILIAN_NAME")..": "..tostring(iCiv));
Controls.TotalsLabel:SetToolTipString( table.concat(tTT, "[NEWLINE]") );
end
-- ===========================================================================
-- UI Callback
-- Collapse all the things!
-- ===========================================================================
function OnCollapseAllButton()
if m_uiGroups == nil or table.count(m_uiGroups) == 0 then
return;
end
for i,instance in ipairs( m_uiGroups ) do
if instance["isCollapsed"] ~= m_isCollapsing then
instance["isCollapsed"] = m_isCollapsing;
instance.CollapseAnim:Reverse();
RealizeGroup( instance );
end
end
Controls.CollapseAll:LocalizeAndSetText(m_isCollapsing and "LOC_HUD_REPORTS_EXPAND_ALL" or "LOC_HUD_REPORTS_COLLAPSE_ALL");
m_isCollapsing = not m_isCollapsing;
end
-- ===========================================================================
-- Populate with all data required for any/all report tabs.
-- ===========================================================================
-- REAL HOUSING FROM IMPROVEMENTS
-- Get the real housing from improvements, not rounded-down
-- The idea taken from CQUI, however CQUI's code is wrong(tested for vanilla and R&F) - the farm doesn't need to be worked, only created within borders
-- GetHousingFromImprovements() returns math.floor(), i.e. +0.5 is rounded to 0, must have 2 farms to get +1 housing
--[[ OBSOLETE as of 2020-06-09
-- Some improvements provide more housing when a tech or civic is unlocked
-- this is done via modifiers, so we need to find them first (EFFECT_ADJUST_IMPROVEMENT_HOUSING)
-- STEPWELL_HOUSING_WITHTECH (REQUIREMENT_PLAYER_HAS_TECHNOLOGY) TechnologyType
-- GOLFCOURSE_HOUSING_WITHGLOBLIZATION (REQUIREMENT_PLAYER_HAS_CIVIC) CivicType
-- MEKEWAP_HOUSING_WITHCIVILSERVICE (REQUIREMENT_PLAYER_HAS_CIVIC)
-- All set via SubjectRequirementSetId
-- However, it is not clear if Amount=1 in modifier means +1 housing or +0.5 just as with base values
-- CQUI calculates as +1 in this case, seems that wiki also says that each of them gives +1
-- this table will hold Tech or Civic requirement for increased Housing
local tImprMoreHousingReqs:table = nil;
local iFarmHousingForMaya:number = 0; -- 2020-05-28 Special case for Maya civ
function PopulateImprMoreHousingReqs()
--print("PopulateImprMoreHousingReqs");
tImprMoreHousingReqs = {};
for mod in GameInfo.ImprovementModifiers() do
local tMod:table = RMA.FetchAndCacheData(mod.ModifierID); -- one of cases with upper case ID
--print(mod.ImprovementType, "fetched", tMod.ModifierId, tMod.EffectType, tMod.SubjectReqSetId);
if tMod and tMod.EffectType == "EFFECT_ADJUST_IMPROVEMENT_HOUSING" and tMod.SubjectReqSet then
--dshowrectable(tMod);
-- now extract requirement!
for _,req in ipairs(tMod.SubjectReqSet.Reqs) do
-- 2020-05-28 Special case for Maya civ
if req.ReqType == "REQUIREMENT_PLAYER_TYPE_MATCHES" and req.Arguments.CivilizationType == "CIVILIZATION_MAYA" then
iFarmHousingForMaya = tonumber(tMod.Arguments.Amount);
elseif req.ReqType == "REQUIREMENT_PLAYER_HAS_TECHNOLOGY" then
tImprMoreHousingReqs[ mod.ImprovementType ] = { IsTech = true, Prereq = req.Arguments.TechnologyType, Amount = tonumber(tMod.Arguments.Amount) };
elseif req.ReqType == "REQUIREMENT_PLAYER_HAS_CIVIC" then
tImprMoreHousingReqs[ mod.ImprovementType ] = { IsTech = false, Prereq = req.Arguments.CivicType, Amount = tonumber(tMod.Arguments.Amount) };
end
end
end
end
print("Found", table.count(tImprMoreHousingReqs), "improvements with additional Housing.");
for k,v in pairs(tImprMoreHousingReqs) do print(k, v.IsTech, v.Prereq, v.Amount); end
print("Maya housing for Farms is", iFarmHousingForMaya);
end
function GetRealHousingFromImprovements(pCity:table)
if tImprMoreHousingReqs == nil then PopulateImprMoreHousingReqs(); end -- do it once
local iNumHousing:number = 0; -- we'll add data from Housing field in Improvements divided by TilesRequired which is usually 2
-- 2020-05-28 Special case for Maya civ
local ePlayerID:number = pCity:GetOwner();
local bIsMaya:boolean = ( PlayerConfigurations[ePlayerID]:GetCivilizationTypeName() == "CIVILIZATION_MAYA" );
-- check all plots in the city
for _,plotIndex in ipairs(Map.GetCityPlots():GetPurchasedPlots(pCity)) do
local pPlot:table = Map.GetPlotByIndex(plotIndex);
if pPlot and pPlot:GetImprovementType() > -1 and not pPlot:IsImprovementPillaged() then
local imprInfo:table = GameInfo.Improvements[ pPlot:GetImprovementType() ];
iNumHousing = iNumHousing + imprInfo.Housing / imprInfo.TilesRequired; -- well, we can always add 0, right?
-- now check if there's more with techs/civics
-- this check is independent from base Housing: there could be an improvement that doesn't give housing as fresh but could later
if tImprMoreHousingReqs[ imprInfo.ImprovementType ] then
--print("ANALYZE WEIRD CASE", imprInfo.ImprovementType);
local reqs:table = tImprMoreHousingReqs[ imprInfo.ImprovementType ];
if reqs.IsTech then
if Players[ePlayerID]:GetTechs():HasTech( GameInfo.Technologies[reqs.Prereq].Index ) then iNumHousing = iNumHousing + reqs.Amount; end
else
if Players[ePlayerID]:GetCulture():HasCivic( GameInfo.Civics[reqs.Prereq].Index ) then iNumHousing = iNumHousing + reqs.Amount; end
end
end
-- 2020-05-28 Special case for Maya civ
if imprInfo.ImprovementType == "IMPROVEMENT_FARM" and bIsMaya then
iNumHousing = iNumHousing + iFarmHousingForMaya;
end
end
end
return iNumHousing;
end
--]]
-- 2020-06-09 new idea for calculations - calculate only a correction and apply to the game function
-- please note that another condition was added - a tile must be within workable distance - this is how the game's engine works
local iCityMaxBuyPlotRange:number = tonumber(GlobalParameters.CITY_MAX_BUY_PLOT_RANGE);
function GetRealHousingFromImprovements(pCity:table)
local cityX:number, cityY:number = pCity:GetX(), pCity:GetY();
--local centerIndex:number = Map.GetPlotIndex(pCity:GetLocation());
local iNumHousing:number = 0; -- we'll add data from Housing field in Improvements divided by TilesRequired which is usually 2
-- check all plots in the city
for _,plotIndex in ipairs(Map.GetCityPlots():GetPurchasedPlots(pCity)) do
local pPlot:table = Map.GetPlotByIndex(plotIndex);
--print(centerIndex, plotIndex, Map.GetPlotDistance(cityX,cityY, pPlot:GetX(), pPlot:GetY()));
if pPlot and pPlot:GetImprovementType() > -1 and not pPlot:IsImprovementPillaged() and Map.GetPlotDistance(cityX, cityY, pPlot:GetX(), pPlot:GetY()) <= iCityMaxBuyPlotRange then
local imprInfo:table = GameInfo.Improvements[ pPlot:GetImprovementType() ];
iNumHousing = iNumHousing + imprInfo.Housing / imprInfo.TilesRequired; -- well, we can always add 0, right?
end
end
return pCity:GetGrowth():GetHousingFromImprovements() + Round(iNumHousing-math.floor(iNumHousing),1);
end
function GetData()
--print("FUN GetData() - start");
local kResources :table = {};
local kCityData :table = {};
local kCityTotalData:table = {
Income = {},
Expenses= {},
Net = {},
Treasury= {}
};
local kUnitData :table = {};
kCityTotalData.Income[YieldTypes.CULTURE] = 0;
kCityTotalData.Income[YieldTypes.FAITH] = 0;
kCityTotalData.Income[YieldTypes.FOOD] = 0;
kCityTotalData.Income[YieldTypes.GOLD] = 0;
kCityTotalData.Income[YieldTypes.PRODUCTION]= 0;
kCityTotalData.Income[YieldTypes.SCIENCE] = 0;
kCityTotalData.Income["TOURISM"] = 0;
kCityTotalData.Expenses[YieldTypes.GOLD] = 0;
local playerID :number = Game.GetLocalPlayer();
if playerID == PlayerTypes.NONE then
UI.DataError("Unable to get valid playerID for report screen.");
return;
end
local player :table = Players[playerID];
local pCulture :table = player:GetCulture();
local pTreasury :table = player:GetTreasury();
local pReligion :table = player:GetReligion();
local pScience :table = player:GetTechs();
local pResources:table = player:GetResources();
local MaintenanceDiscountPerUnit:number = pTreasury:GetMaintDiscountPerUnit(); -- this will be used in 2 reports
-- ==========================
-- BRS !! this will use the m_kUnitDataReport to fill out player's unit info
-- ==========================
--print("FUN GetData() - unit data report");
local tSupportedFormationClasses:table = { FORMATION_CLASS_CIVILIAN = true, FORMATION_CLASS_LAND_COMBAT = true, FORMATION_CLASS_NAVAL = true, FORMATION_CLASS_SUPPORT = true, FORMATION_CLASS_AIR = true };
local kUnitDataReport:table = {};
local group_name:string;
local tUnitsDist:table = {}; -- temp table for calculating units' distance from cities
for _, unit in player:GetUnits():Members() do
local unitInfo:table = GameInfo.Units[unit:GetUnitType()];
local formationClass:string = unitInfo.FormationClass; -- FORMATION_CLASS_CIVILIAN, FORMATION_CLASS_LAND_COMBAT, FORMATION_CLASS_NAVAL, FORMATION_CLASS_SUPPORT, FORMATION_CLASS_AIR
-- categorize
group_name = string.gsub(formationClass, "FORMATION_CLASS_", "");
if formationClass == "FORMATION_CLASS_CIVILIAN" then
-- need to split into sub-classes
if unit:GetGreatPerson():IsGreatPerson() then group_name = "GREAT_PERSON";
elseif unitInfo.MakeTradeRoute then group_name = "TRADER";
elseif unitInfo.Spy then group_name = "SPY";
elseif unit:GetReligiousStrength() > 0 then group_name = "RELIGIOUS";
end
end
-- tweak to handle new, unknown formation classes
if not tSupportedFormationClasses[formationClass] then
print("WARNING: GetData Unknown formation class", formationClass, "for unit", unitInfo.UnitType);
group_name = "SUPPORT";
end
-- store for Units tab report
if kUnitDataReport[group_name] == nil then
if group_name == "LAND_COMBAT" then kUnitDataReport[group_name] = { ID= 1, func= group_military, Header= "UnitsMilitaryHeaderInstance", Entry= "UnitsMilitaryEntryInstance" };
elseif group_name == "NAVAL" then kUnitDataReport[group_name] = { ID= 2, func= group_military, Header= "UnitsMilitaryHeaderInstance", Entry= "UnitsMilitaryEntryInstance" };
elseif group_name == "AIR" then kUnitDataReport[group_name] = { ID= 3, func= group_military, Header= "UnitsMilitaryHeaderInstance", Entry= "UnitsMilitaryEntryInstance" };
elseif group_name == "SUPPORT" then kUnitDataReport[group_name] = { ID= 4, func= group_military, Header= "UnitsMilitaryHeaderInstance", Entry= "UnitsMilitaryEntryInstance" };
elseif group_name == "CIVILIAN" then kUnitDataReport[group_name] = { ID= 5, func= group_civilian, Header= "UnitsCivilianHeaderInstance", Entry= "UnitsCivilianEntryInstance" };
elseif group_name == "RELIGIOUS" then kUnitDataReport[group_name] = { ID= 6, func= group_religious,Header= "UnitsReligiousHeaderInstance", Entry= "UnitsReligiousEntryInstance" };
elseif group_name == "GREAT_PERSON" then kUnitDataReport[group_name] = { ID= 7, func= group_great, Header= "UnitsGreatPeopleHeaderInstance",Entry= "UnitsGreatPeopleEntryInstance" };
elseif group_name == "SPY" then kUnitDataReport[group_name] = { ID= 8, func= group_spy, Header= "UnitsSpyHeaderInstance", Entry= "UnitsSpyEntryInstance" };
elseif group_name == "TRADER" then kUnitDataReport[group_name] = { ID= 9, func= group_trader, Header= "UnitsTraderHeaderInstance", Entry= "UnitsTraderEntryInstance" };
end
--print("...creating a new unit group", formationClass, group_name);
kUnitDataReport[group_name].Name = "LOC_BRS_UNITS_GROUP_"..group_name;
kUnitDataReport[group_name].units = {};
end
table.insert( kUnitDataReport[group_name].units, unit );
-- add some unit specific data
unit.MaintenanceAfterDiscount = math.max(GetUnitMaintenance(unit) - MaintenanceDiscountPerUnit, 0); -- cannot go below 0
-- store data for distance calculations
unit.NearCityDistance = 9999;
unit.NearCityName = "";
unit.NearCityIsCapital = false;
unit.NearCityIsOurs = true;
-- Gathering Storm
if bIsGatheringStorm then
unit.ResMaint = "";
local unitInfoXP2:table = GameInfo.Units_XP2[ unitInfo.UnitType ];
if unitInfoXP2 ~= nil and unitInfoXP2.ResourceMaintenanceType ~= nil then
unit.ResMaint = "[ICON_"..unitInfoXP2.ResourceMaintenanceType.."]";
end
end
-- Rock Band
unit.IsRockBand = false;
unit.RockBandAlbums = 0;
unit.RockBandLevel = 0;
if bIsGatheringStorm and unitInfo.PromotionClass == "PROMOTION_CLASS_ROCK_BAND" then
unit.IsRockBand = true;
unit.RockBandAlbums = unit:GetRockBand():GetAlbumSales();
unit.RockBandLevel = unit:GetRockBand():GetRockBandLevel();
end
table.insert( tUnitsDist, unit );
end
-- calculate distance to the closest city for all units
-- must iterate through all living players and their cities
for _,player in ipairs(PlayerManager.GetAlive()) do
local bIsOurs:boolean = ( player:GetID() == playerID );
for _,city in player:GetCities():Members() do
local iCityX:number, iCityY:number = city:GetX(), city:GetY();
local sCityName:string = Locale.Lookup( city:GetName() );
local bIsCapital:boolean = city:IsCapital();
for _,unit in ipairs(tUnitsDist) do
local iDistance:number = Map.GetPlotDistance( unit:GetX(), unit:GetY(), iCityX, iCityY );
if iDistance < unit.NearCityDistance then
unit.NearCityDistance = iDistance;
unit.NearCityName = sCityName;
unit.NearCityIsCapital = bIsCapital;
unit.NearCityIsOurs = bIsOurs;
end
end
end
end
-- ==========================
-- !! end of edit
-- ==========================
-----------------------------------
-- MODIFIERS
-- scan only once, select those for a) player's cities b) with desired effects
-- store in a similar fashion as city data i.e. indexed by CityName
-- on a city level a simple table, each entry contains:
-- .ID - instance ID from GameEffects.GetModifiers
-- .Active - boolean, as returned by GameEffects.GetModifierActive
-- .Definition - table, as returned by GameEffects.GetModifierDefinition
-- .Arguments - table, reference to .Arguments from .Definition (easy access)
-- .OwnerType, .OwnerName - strings, as returned by GameEffects.GetObjectType and GetObjectName - for debug
-- .Modifier - static as returned by RMA.FetchAndCacheData
-----------------------------------
--print("FUN GetData() - modifiers");
m_kModifiers = {}; -- clear main table
m_kModifiersUnits ={}; -- clear main table
local sTrackedPlayer:string = PlayerConfigurations[playerID]:GetLeaderName(); -- LOC_LEADER_xxx_NAME
--print("Tracking player", sTrackedPlayer); -- debug
--[[ not used
local tTrackedEffects:table = {
EFFECT_ADJUST_CITY_YIELD_CHANGE = true, -- all listed as Modifiers in CityPanel
EFFECT_ADJUST_CITY_YIELD_MODIFIER = true, -- e.g. governor's +20%, Wonders use it, some beliefs
EFFECT_ADJUST_CITY_YIELD_PER_POPULATION = true, -- e.g. Theocracy and Communism
EFFECT_ADJUST_CITY_YIELD_PER_DISTRICT = true, -- e.g. Democtratic Legacy +2 Production per district
EFFECT_ADJUST_FOLLOWER_YIELD_MODIFIER = true, -- Work Ethic belief +1% Production; use the number of followers of the majority religion in the city
--EFFECT_ADJUST_CITY_YIELD_FROM_FOREIGN_TRADE_ROUTES_PASSING_THROUGH = true, -- unknown
};
--]]
--for k,v in pairs(tTrackedEffects) do print(k,v); end -- debug
local tTrackedOwners:table = {};
for _,city in player:GetCities():Members() do
tTrackedOwners[ city:GetName() ] = true;
m_kModifiers[ city:GetName() ] = {}; -- we need al least empty table for each city
end
local tTrackedUnits:table = {};
for _,unit in player:GetUnits():Members() do
tTrackedUnits[ unit:GetID() ] = true;
m_kModifiersUnits[ unit:GetID() ] = {};
end
--for k,v in pairs(tTrackedOwners) do print(k,v); end -- debug
-- main loop
for _,instID in ipairs(GameEffects.GetModifiers()) do
local iOwnerID:number = GameEffects.GetModifierOwner( instID );
local iPlayerID:number = GameEffects.GetObjectsPlayerId( iOwnerID );
local sOwnerType:string = GameEffects.GetObjectType( iOwnerID ); -- LOC_MODIFIER_OBJECT_CITY, LOC_MODIFIER_OBJECT_PLAYER, LOC_MODIFIER_OBJECT_GOVERNOR
local sOwnerName:string = GameEffects.GetObjectName( iOwnerID ); -- LOC_CITY_xxx_NAME, LOC_LEADER_xxx_NAME, etc.
local tSubjects:table = GameEffects.GetModifierSubjects( instID ); -- table of objectIDs or nil
--print("checking", instID, sOwnerName, sOwnerType, iOwnerID, iPlayerID); -- debug
local instdef:table = GameEffects.GetModifierDefinition(instID);
local data:table = {
ID = instID,
Active = GameEffects.GetModifierActive(instID), -- should always be true? but check to be safe
Definition = instdef, -- .Id has the static name
Arguments = instdef.Arguments, -- same structure as static, Name = Value
OwnerType = sOwnerType,
OwnerName = sOwnerName,
SubjectType = nil, -- will be filled for modifiers taken from Subjects
SubjectName = nil, -- will be filled for modifiers taken from Subjects
UnitID = nil, -- will be used only for units' modifiers
Modifier = RMA.FetchAndCacheData(instdef.Id),
};
local function RegisterModifierForCity(sSubjectType:string, sSubjectName:string)
--print("registering for city", data.ID, sSubjectType, sSubjectName);
-- fix for sudden changes in modifier system, like Veterancy changed in March 2018 patch
-- some modifiers might be removed, but still are attached to objects from old games
-- the game itself seems to be resistant to such situation
if data.Modifier == nil then print("WARNING! GetData/Modifiers: Ignoring non-existing modifier", data.ID, data.Definition.Id, sOwnerName, sSubjectName); return end
if sSubjectType == nil or sSubjectName == nil then
data.SubjectType = nil;
data.SubjectName = nil;
table.insert(m_kModifiers[sOwnerName], data);
else -- register as subject
data.SubjectType = sSubjectType;
data.SubjectName = sSubjectName;
table.insert(m_kModifiers[sSubjectName], data);
end
-- debug output
--print("--------- Tracking", data.ID, sOwnerType, sOwnerName, sSubjectName);
--for k,v in pairs(data) do print(k,v); end
--print("- Modifier:", data.Definition.Id);
--print("- Collection:", data.Modifier.CollectionType);
--print("- Effect:", data.Modifier.EffectType);
--print("- Arguments:");
--for k,v in pairs(data.Arguments) do print(k,v); end -- debug
end
local function RegisterModifierForUnit(iUnitID:number, sSubjectType:string, sSubjectName:string)
--print("registering for unit", iUnitID, data.ID, sSubjectType, sSubjectName);
-- fix for sudden changes in modifier system, like Veterancy changed in March 2018 patch
-- some modifiers might be removed, but still are attached to objects from old games
-- the game itself seems to be resistant to such situation
if data.Modifier == nil then print("WARNING! GetData/Modifiers: Ignoring non-existing modifier", data.ID, data.Definition.Id, sOwnerName, sSubjectName); return end
data.UnitID = iUnitID;
if sSubjectType == nil or sSubjectName == nil then
data.SubjectType = nil;
data.SubjectName = nil;
else -- register as subject
data.SubjectType = sSubjectType;
data.SubjectName = sSubjectName;
end
table.insert(m_kModifiersUnits[iUnitID], data);
-- debug output
--print("--------- Tracking", iUnitID, data.ID, sOwnerType, sOwnerName, sSubjectName);
--for k,v in pairs(data) do print(k,v); end
--print("- Modifier:", data.Definition.Id);
--print("- Collection:", data.Modifier.CollectionType);
--print("- Effect:", data.Modifier.EffectType);
--print("- Arguments:");
--for k,v in pairs(data.Arguments) do print(k,v); end -- debug
end
-- this part is for modifiers attached directly to the city (COLLECTION_OWNER)
if tTrackedOwners[ sOwnerName ] then
RegisterModifierForCity(); -- City is owner
end
-- this part is for modifiers attached to the player
-- we need to analyze Subjects (COLLECTION_PLAYER_CITIES, COLLECTION_PLAYER_CAPITAL_CITY)
-- GetModifierTrackedObjects gives all Subjects, but GetModifierSubjects gives only those with met requirements!
if sOwnerType == "LOC_MODIFIER_OBJECT_PLAYER" and sOwnerName == sTrackedPlayer and tSubjects then
for _,subjectID in ipairs(tSubjects) do
local sSubjectType:string = GameEffects.GetObjectType( subjectID ); -- LOC_MODIFIER_OBJECT_CITY, LOC_MODIFIER_OBJECT_PLAYER, LOC_MODIFIER_OBJECT_GOVERNOR
local sSubjectName:string = GameEffects.GetObjectName( subjectID ); -- LOC_CITY_xxx_NAME, LOC_LEADER_xxx_NAME, etc.
if sSubjectType == "LOC_MODIFIER_OBJECT_CITY" and tTrackedOwners[sSubjectName] then RegisterModifierForCity(sSubjectType, sSubjectName); end
end
end
-- this part is for modifiers attached to Districts
-- we process all districts, but sOwnerName contains DistrictName if necessary LOC_DISTRICT_xxx_NAME
-- for each there is always a set of Subjects, even if only 1 for a singular effect
-- those subjects can be LOC_MODIFIER_OBJECT_DISTRICT or LOC_MODIFIER_OBJECT_PLOT_YIELDS
-- then we need to find its City, which is stupidly hidden in a description string "District: districtID, Owner: playerID, City: cityID"
if iPlayerID == playerID and sOwnerType == "LOC_MODIFIER_OBJECT_DISTRICT" and tSubjects then
for _,subjectID in ipairs(tSubjects) do
local sSubjectType:string = GameEffects.GetObjectType( subjectID );
local sSubjectName:string = GameEffects.GetObjectName( subjectID );
if sSubjectType == "LOC_MODIFIER_OBJECT_DISTRICT" then
-- find a city
local sSubjectString:string = GameEffects.GetObjectString( subjectID );
local iCityID:number = tonumber( string.match(sSubjectString, "City: (%d+)") );
--print("city:", sSubjectString, "decode:", iCityID);
if iCityID ~= nil then
local pCity:table = player:GetCities():FindID(iCityID);
if pCity and tTrackedOwners[pCity:GetName()] then RegisterModifierForCity(sSubjectType, pCity:GetName()); end
end
end
end
end
-- this part is for units as owners, we need to decode the unit and see if it's ours
if sOwnerType == "LOC_MODIFIER_OBJECT_UNIT" then
-- find a unit
local sOwnerString:string = GameEffects.GetObjectString( iOwnerID );
local iUnitID:number = tonumber( string.match(sOwnerString, "Unit: (%d+)") );
local iUnitOwnerID:number = tonumber( string.match(sOwnerString, "Owner: (%d+)") );
--print("unit:", sOwnerString, "decode:", iUnitOwnerID, iUnitID);
if iUnitID and iUnitOwnerID and iUnitOwnerID == playerID and tTrackedUnits[iUnitID] then
RegisterModifierForUnit(iUnitID);
end
end
-- this part is for units as subjects; to make it more unified it will simply analyze all subjects' sets
if tSubjects then
for _,subjectID in ipairs(tSubjects) do
local sSubjectType:string = GameEffects.GetObjectType( subjectID );
local sSubjectName:string = GameEffects.GetObjectName( subjectID );
if sSubjectType == "LOC_MODIFIER_OBJECT_UNIT" then
-- find a unit
local sSubjectString:string = GameEffects.GetObjectString( subjectID );
local iUnitID:number = tonumber( string.match(sSubjectString, "Unit: (%d+)") );
local iUnitOwnerID:number = tonumber( string.match(sSubjectString, "Owner: (%d+)") );
--print("unit:", sSubjectString, "decode:", iUnitOwnerID, iUnitID);
if iUnitID and iUnitOwnerID and iUnitOwnerID == playerID and tTrackedUnits[iUnitID] then
RegisterModifierForUnit(iUnitID, sSubjectType, sSubjectName);
end
end -- unit
end -- subjects
end
end
--print("--------------"); print("FOUND MODIFIERS FOR CITIES"); for k,v in pairs(m_kModifiers) do print(k, #v); end
--print("--------------"); print("FOUND MODIFIERS FOR UNITS"); for k,v in pairs(m_kModifiersUnits) do print(k, #v); end
--print("FUN GetData() - cities");
local pCities = player:GetCities();
for i, pCity in pCities:Members() do
local cityName :string = pCity:GetName();
-- Big calls, obtain city data and add report specific fields to it.
local data :table = GetCityData( pCity );
data.Resources = GetCityResourceData( pCity ); -- Add more data (not in CitySupport)
data.WorkedTileYields, data.NumWorkedTiles, data.SpecialistYields, data.NumSpecialists = GetWorkedTileYieldData( pCity, pCulture ); -- Add more data (not in CitySupport)
-- Add to totals.
kCityTotalData.Income[YieldTypes.CULTURE] = kCityTotalData.Income[YieldTypes.CULTURE] + data.CulturePerTurn;
kCityTotalData.Income[YieldTypes.FAITH] = kCityTotalData.Income[YieldTypes.FAITH] + data.FaithPerTurn;
kCityTotalData.Income[YieldTypes.FOOD] = kCityTotalData.Income[YieldTypes.FOOD] + data.FoodPerTurn;
kCityTotalData.Income[YieldTypes.GOLD] = kCityTotalData.Income[YieldTypes.GOLD] + data.GoldPerTurn;
kCityTotalData.Income[YieldTypes.PRODUCTION]= kCityTotalData.Income[YieldTypes.PRODUCTION] + data.ProductionPerTurn;
kCityTotalData.Income[YieldTypes.SCIENCE] = kCityTotalData.Income[YieldTypes.SCIENCE] + data.SciencePerTurn;
kCityTotalData.Income["TOURISM"] = kCityTotalData.Income["TOURISM"] + data.WorkedTileYields["TOURISM"];
kCityData[cityName] = data;
-- Add outgoing route data
data.OutgoingRoutes = pCity:GetTrade():GetOutgoingRoutes();
data.IncomingRoutes = pCity:GetTrade():GetIncomingRoutes();
-- Add resources
if m_debugNumResourcesStrategic > 0 or m_debugNumResourcesLuxuries > 0 or m_debugNumBonuses > 0 then
for debugRes=1,m_debugNumResourcesStrategic,1 do
kResources[debugRes] = {
CityList = { CityName="Kangaroo", Amount=(10+debugRes) },
Icon = "[ICON_"..GameInfo.Resources[debugRes].ResourceType.."]",
IsStrategic = true,
IsLuxury = false,
IsBonus = false,
Total = 88
};
end
for debugRes=1,m_debugNumResourcesLuxuries,1 do
kResources[debugRes] = {
CityList = { CityName="Kangaroo", Amount=(10+debugRes) },
Icon = "[ICON_"..GameInfo.Resources[debugRes].ResourceType.."]",
IsStrategic = false,
IsLuxury = true,
IsBonus = false,
Total = 88
};
end
for debugRes=1,m_debugNumBonuses,1 do
kResources[debugRes] = {
CityList = { CityName="Kangaroo", Amount=(10+debugRes) },
Icon = "[ICON_"..GameInfo.Resources[debugRes].ResourceType.."]",
IsStrategic = false,
IsLuxury = false,
IsBonus = true,
Total = 88
};
end
end
for eResourceType,amount in pairs(data.Resources) do
AddResourceData(kResources, eResourceType, cityName, "LOC_HUD_REPORTS_TRADE_OWNED", amount);
end
-- ADDITIONAL DATA
-- Modifiers
data.Modifiers = m_kModifiers[ cityName ]; -- just a reference to the main table
-- real housing from improvements - this is a permanent fix for data.Housing field, so it is safe to use it later
data.RealHousingFromImprovements = GetRealHousingFromImprovements(pCity);
data.Housing = data.Housing - data.HousingFromImprovements + data.RealHousingFromImprovements;
data.HousingFromImprovements = data.RealHousingFromImprovements;
-- number of followers of the main religion
data.MajorityReligionFollowers = 0;
local eDominantReligion:number = pCity:GetReligion():GetMajorityReligion();
if eDominantReligion > 0 then -- WARNING! this rules out pantheons!
for _, religionData in pairs(pCity:GetReligion():GetReligionsInCity()) do
if religionData.Religion == eDominantReligion then data.MajorityReligionFollowers = religionData.Followers; end
end
end
--print("Majority religion followers for", cityName, data.MajorityReligionFollowers);
-- Garrison in a city
data.IsGarrisonUnit = false;
local pPlotCity:table = Map.GetPlot( pCity:GetX(), pCity:GetY() );
for _,unit in ipairs(Units.GetUnitsInPlot(pPlotCity)) do
if GameInfo.Units[ unit:GetUnitType() ].FormationClass == "FORMATION_CLASS_LAND_COMBAT" then
data.IsGarrisonUnit = true;
data.GarrisonUnitName = Locale.Lookup( unit:GetName() );
break;
end
end
-- count all districts and specialty ones
data.NumDistricts = 0;
data.NumSpecialtyDistricts = 0
for _,district in pCity:GetDistricts():Members() do
local districtInfo:table = GameInfo.Districts[ district:GetType() ];
if district:IsComplete() and not districtInfo.CityCenter and districtInfo.DistrictType ~= "DISTRICT_WONDER" then
data.NumDistricts = data.NumDistricts + 1;
end
if district:IsComplete() and not districtInfo.CityCenter and districtInfo.OnePerCity and districtInfo.DistrictType ~= "DISTRICT_WONDER" then
data.NumSpecialtyDistricts = data.NumSpecialtyDistricts + 1;
end
end
-- current production type
data.CurrentProductionType = "NONE";
local iCurrentProductionHash:number = pCity:GetBuildQueue():GetCurrentProductionTypeHash();
if iCurrentProductionHash ~= 0 then
if GameInfo.Buildings[iCurrentProductionHash] ~= nil then data.CurrentProductionType = "BUILDING";
elseif GameInfo.Districts[iCurrentProductionHash] ~= nil then data.CurrentProductionType = "DISTRICT";
elseif GameInfo.Units[iCurrentProductionHash] ~= nil then data.CurrentProductionType = "UNIT";
elseif GameInfo.Projects[iCurrentProductionHash] ~= nil then data.CurrentProductionType = "PROJECT";
end
end
-- Growth and related data
-- This part of code is from CityPanelOverview.lua, retrofitted to use here (it uses data as prepared by CitySupport.lua)
-- line 1, data.FoodPerTurn
data.FoodConsumption = -(data.FoodPerTurn - data.FoodSurplus); -- line 2, it will be always negative!
-- line 3, data.FoodSurplus
-- line 4, data.HappinessGrowthModifier
-- line 5, data.OccupationMultiplier
data.FoodPerTurnModified = 0; -- line 6, modified food per turn [=line3 * (1+line4+line5)
-- line 7, data.HousingMultiplier
-- line 8a vanilla, data.OccupationMultiplier
-- line 8b ris&fal, loyalty calculated
data.TotalFoodSurplus = 0; -- line 9, as displayed in City Details
-- line 10, data.TurnsUntilGrowth
-- growth changes related to Loyalty
if bIsRiseFall or bIsGatheringStorm then
data.LoyaltyGrowthModifier = Round( 100 * pCity:GetGrowth():GetLoyaltyGrowthModifier() - 100, 0 );
data.LoyaltyLevelName = GameInfo.LoyaltyLevels[ pCity:GetCulturalIdentity():GetLoyaltyLevel() ].Name;
end
local tGrowthTT:table = {}; -- growth tooltip
local function AddGrowthToolTip(sText:string, fValue:number, sSuffix:string)
if fValue then table.insert(tGrowthTT, Locale.Lookup(sText)..": "..toPlusMinusString(fValue)..(sSuffix and sSuffix or ""));
else table.insert(tGrowthTT, Locale.Lookup(sText)..": "..Locale.Lookup("LOC_HUD_CITY_NOT_APPLICABLE")); end
end
local function AddGrowthToolTipSeparator()
table.insert(tGrowthTT, "----------");
end
AddGrowthToolTip("LOC_HUD_CITY_FOOD_PER_TURN", data.FoodPerTurn); -- line 1: food per turn
AddGrowthToolTip("LOC_HUD_CITY_FOOD_CONSUMPTION", data.FoodConsumption); -- line 2: food consumption
AddGrowthToolTipSeparator();
AddGrowthToolTip("LOC_HUD_CITY_GROWTH_FOOD_PER_TURN", data.FoodSurplus); -- line 3: food growth per turn
if data.TurnsUntilGrowth > -1 then
-- GROWTH IN: Set bonuses and multipliers
AddGrowthToolTip("LOC_HUD_CITY_HAPPINESS_GROWTH_BONUS", Round(data.HappinessGrowthModifier, 0), "%"); -- line 4: amenities (happiness) growth bonus
AddGrowthToolTip("LOC_HUD_CITY_OTHER_GROWTH_BONUSES", Round(data.OtherGrowthModifiers * 100, 0), "%"); -- line 5: other growth bonuses
AddGrowthToolTipSeparator();
local growthModifier = math.max(1 + (data.HappinessGrowthModifier/100) + data.OtherGrowthModifiers, 0); -- This is unintuitive but it's in parity with the logic in City_Growth.cpp
data.FoodPerTurnModified = Round(data.FoodSurplus * growthModifier, 2); -- line 6
AddGrowthToolTip("LOC_HUD_CITY_MODIFIED_GROWTH_FOOD_PER_TURN", data.FoodPerTurnModified); -- line 6: modified food per turn
table.insert(tGrowthTT, Locale.Lookup("LOC_HUD_CITY_HOUSING_MULTIPLIER")..": "..data.HousingMultiplier); -- line 7: housing multiplier
data.TotalFoodSurplus = data.FoodPerTurnModified * data.HousingMultiplier;
-- occupied
if data.Occupied then data.TotalFoodSurplus = data.FoodPerTurnModified * data.OccupationMultiplier; end
AddGrowthToolTip("LOC_HUD_CITY_OCCUPATION_MULTIPLIER", (data.Occupied and data.OccupationMultiplier * 100) or nil, "%"); -- line 8a
if bIsRiseFall or bIsGatheringStorm then
if data.LoyaltyGrowthModifier ~= 0 then AddGrowthToolTip(data.LoyaltyLevelName, data.LoyaltyGrowthModifier, "%"); -- line 8b
else table.insert(tGrowthTT, Locale.Lookup(data.LoyaltyLevelName)..": "..Locale.Lookup("LOC_CULTURAL_IDENTITY_LOYALTY_NO_GROWTH_PENALTY")); end -- line 8b
end
AddGrowthToolTipSeparator();
-- final
AddGrowthToolTip("LOC_HUD_CITY_TOTAL_FOOD_SURPLUS", data.TotalFoodSurplus, (data.TotalFoodSurplus > 0 and "[ICON_FoodSurplus]") or "[ICON_FoodDeficit]"); -- line 9
if data.Occupied then AddGrowthToolTip("LOC_HUD_CITY_GROWTH_OCCUPIED"); -- line 10, occupied: no growth
else table.insert(tGrowthTT, Locale.Lookup("LOC_HUD_CITY_TURNS_UNTIL_CITIZEN_BORN", math.abs(data.TurnsUntilGrowth))); end -- line 10
else
-- CITIZEN LOST IN: In a deficit, no bonuses or multipliers apply
AddGrowthToolTip("LOC_HUD_CITY_HAPPINESS_GROWTH_BONUS"); -- line 4: amenities (happiness) growth bonus
AddGrowthToolTip("LOC_HUD_CITY_OTHER_GROWTH_BONUSES"); -- line 5: other growth bonuses
AddGrowthToolTipSeparator();
data.FoodPerTurnModified = data.FoodSurplus; -- line 6
AddGrowthToolTip("LOC_HUD_CITY_MODIFIED_GROWTH_FOOD_PER_TURN", data.FoodPerTurnModified); -- line 6: modified food per turn
AddGrowthToolTip("LOC_HUD_CITY_HOUSING_MULTIPLIER"); -- line 7: housing multiplier
AddGrowthToolTip("LOC_HUD_CITY_OCCUPATION_MULTIPLIER", (data.Occupied and data.OccupationMultiplier * 100) or nil, "%"); -- line 8a
if bIsRiseFall or bIsGatheringStorm then AddGrowthToolTip(data.LoyaltyLevelName); end -- line 8b
AddGrowthToolTipSeparator();
data.TotalFoodSurplus = data.FoodPerTurnModified; -- line 9
AddGrowthToolTip("LOC_HUD_CITY_TOTAL_FOOD_DEFICIT", data.TotalFoodSurplus, "[ICON_FoodDeficit]"); -- line 9
table.insert(tGrowthTT, "[Color:StatBadCS]"..string.upper(Locale.Lookup("LOC_HUD_CITY_STARVING")).."[ENDCOLOR]"); -- starving marker
table.insert(tGrowthTT, Locale.Lookup("LOC_HUD_CITY_TURNS_UNTIL_CITIZEN_LOST", math.abs(data.TurnsUntilGrowth))); -- line 10
end
data.TotalFoodSurplusToolTip = table.concat(tGrowthTT, "[NEWLINE]");
-- Gathering Storm
if bIsGatheringStorm then AppendXP2CityData(data); end
end -- for Cities:Members
kCityTotalData.Expenses[YieldTypes.GOLD] = pTreasury:GetTotalMaintenance();
-- NET = Income - Expense
kCityTotalData.Net[YieldTypes.GOLD] = kCityTotalData.Income[YieldTypes.GOLD] - kCityTotalData.Expenses[YieldTypes.GOLD];
kCityTotalData.Net[YieldTypes.FAITH] = kCityTotalData.Income[YieldTypes.FAITH];
-- Treasury
kCityTotalData.Treasury[YieldTypes.CULTURE] = Round( pCulture:GetCultureYield(), 0 );
kCityTotalData.Treasury[YieldTypes.FAITH] = Round( pReligion:GetFaithBalance(), 0 );
kCityTotalData.Treasury[YieldTypes.GOLD] = Round( pTreasury:GetGoldBalance(), 0 );
kCityTotalData.Treasury[YieldTypes.SCIENCE] = Round( pScience:GetScienceYield(), 0 );
kCityTotalData.Treasury["TOURISM"] = Round( kCityTotalData.Income["TOURISM"], 0 );
-- Units (TODO: Group units by promotion class and determine total maintenance cost)
--print("FUN GetData() - units");
--local MaintenanceDiscountPerUnit:number = pTreasury:GetMaintDiscountPerUnit(); -- used also for Units tab, so defined earlier
local pUnits :table = player:GetUnits();
for i, pUnit in pUnits:Members() do
local pUnitInfo:table = GameInfo.Units[pUnit:GetUnitType()];
-- get localized unit name with appropriate suffix
local unitName :string = Locale.Lookup(pUnitInfo.Name);
local unitMilitaryFormation = pUnit:GetMilitaryFormation();
if (unitMilitaryFormation == MilitaryFormationTypes.CORPS_FORMATION) then
--unitName = unitName.." "..Locale.Lookup( (pUnitInfo.Domain == "DOMAIN_SEA" and "LOC_HUD_UNIT_PANEL_FLEET_SUFFIX") or "LOC_HUD_UNIT_PANEL_CORPS_SUFFIX");
--unitName = unitName.." [ICON_Corps]";
elseif (unitMilitaryFormation == MilitaryFormationTypes.ARMY_FORMATION) then
--unitName = unitName.." "..Locale.Lookup( (pUnitInfo.Domain == "DOMAIN_SEA" and "LOC_HUD_UNIT_PANEL_ARMADA_SUFFIX") or "LOC_HUD_UNIT_PANEL_ARMY_SUFFIX");
--unitName = unitName.." [ICON_Army]";
else
--BRS Civilian units can be NO_FORMATION (-1) or STANDARD (0)
unitMilitaryFormation = MilitaryFormationTypes.STANDARD_FORMATION; -- 0
end
-- calculate unit maintenance with discount if active
local TotalMaintenanceAfterDiscount:number = math.max(GetUnitMaintenance(pUnit) - MaintenanceDiscountPerUnit, 0); -- cannot go below 0
local unitTypeKey = pUnitInfo.UnitType..unitMilitaryFormation;
if kUnitData[unitTypeKey] == nil then
kUnitData[unitTypeKey] = { Name = Locale.Lookup(pUnitInfo.Name), Formation = unitMilitaryFormation, Count = 1, Maintenance = TotalMaintenanceAfterDiscount };
if bIsGatheringStorm then kUnitData[unitTypeKey].ResCount = 0; end
else
kUnitData[unitTypeKey].Count = kUnitData[unitTypeKey].Count + 1;
kUnitData[unitTypeKey].Maintenance = kUnitData[unitTypeKey].Maintenance + TotalMaintenanceAfterDiscount;
end
-- Gathering Storm
if bIsGatheringStorm then
kUnitData[unitTypeKey].ResIcon = "";
local unitInfoXP2:table = GameInfo.Units_XP2[ pUnitInfo.UnitType ];
if unitInfoXP2 ~= nil and unitInfoXP2.ResourceMaintenanceType ~= nil then
kUnitData[unitTypeKey].ResIcon = "[ICON_"..unitInfoXP2.ResourceMaintenanceType.."]";
kUnitData[unitTypeKey].ResCount = kUnitData[unitTypeKey].ResCount + unitInfoXP2.ResourceMaintenanceAmount;
end
end
end
-- =================================================================
-- BRS Current Deals Info (didn't wanna mess with diplomatic deal data
-- below, maybe later
-- =================================================================
--print("FUN GetData() - deals");
local kCurrentDeals : table = {}
local kPlayers : table = PlayerManager.GetAliveMajors()
local iTotal = 0
for _, pOtherPlayer in ipairs( kPlayers ) do
local otherID:number = pOtherPlayer:GetID()
if otherID ~= playerID then
local pPlayerConfig :table = PlayerConfigurations[otherID]
local pDeals :table = DealManager.GetPlayerDeals( playerID, otherID )
if pDeals ~= nil then
for i, pDeal in ipairs( pDeals ) do
iTotal = iTotal + 1
local Receiving : table = { Agreements = {}, Gold = {}, Resources = {} }
local Sending : table = { Agreements = {}, Gold = {}, Resources = {} }
Receiving.Resources = pDeal:FindItemsByType( DealItemTypes.RESOURCES, DealItemSubTypes.NONE, otherID )
Receiving.Gold = pDeal:FindItemsByType( DealItemTypes.GOLD, DealItemSubTypes.NONE, otherID )
Receiving.Agreements = pDeal:FindItemsByType( DealItemTypes.AGREEMENTS, DealItemSubTypes.NONE, otherID )
Sending.Resources = pDeal:FindItemsByType( DealItemTypes.RESOURCES, DealItemSubTypes.NONE, playerID )
Sending.Gold = pDeal:FindItemsByType( DealItemTypes.GOLD, DealItemSubTypes.NONE, playerID )
Sending.Agreements = pDeal:FindItemsByType( DealItemTypes.AGREEMENTS, DealItemSubTypes.NONE, playerID )
kCurrentDeals[iTotal] =
{
WithCivilization = Locale.Lookup( pPlayerConfig:GetCivilizationDescription() ),
EndTurn = 0,
Receiving = {},
Sending = {}
}
local iDeal = 0
for pReceivingName, pReceivingGroup in pairs( Receiving ) do
for _, pDealItem in ipairs( pReceivingGroup ) do
iDeal = iDeal + 1
kCurrentDeals[iTotal].EndTurn = pDealItem:GetEndTurn()
kCurrentDeals[iTotal].Receiving[iDeal] = { Amount = pDealItem:GetAmount() }
local deal = kCurrentDeals[iTotal].Receiving[iDeal]
if pReceivingName == "Agreements" then
deal.Name = pDealItem:GetSubTypeNameID()
elseif pReceivingName == "Gold" then
deal.Name = deal.Amount.." "..Locale.Lookup("LOC_DIPLOMACY_DEAL_GOLD_PER_TURN");
deal.Icon = "[ICON_GOLD]"
else
if deal.Amount > 1 then
deal.Name = pDealItem:GetValueTypeNameID() .. "(" .. deal.Amount .. ")"
else
deal.Name = pDealItem:GetValueTypeNameID()
end
deal.Icon = "[ICON_" .. pDealItem:GetValueTypeID() .. "]"
end
deal.Name = Locale.Lookup( deal.Name )
end
end
iDeal = 0
for pSendingName, pSendingGroup in pairs( Sending ) do
for _, pDealItem in ipairs( pSendingGroup ) do
iDeal = iDeal + 1
kCurrentDeals[iTotal].EndTurn = pDealItem:GetEndTurn()
kCurrentDeals[iTotal].Sending[iDeal] = { Amount = pDealItem:GetAmount() }
local deal = kCurrentDeals[iTotal].Sending[iDeal]
if pSendingName == "Agreements" then
deal.Name = pDealItem:GetSubTypeNameID()
elseif pSendingName == "Gold" then
deal.Name = deal.Amount.." "..Locale.Lookup("LOC_DIPLOMACY_DEAL_GOLD_PER_TURN");
deal.Icon = "[ICON_GOLD]"
else
if deal.Amount > 1 then
deal.Name = pDealItem:GetValueTypeNameID() .. "(" .. deal.Amount .. ")"
else
deal.Name = pDealItem:GetValueTypeNameID()
end
deal.Icon = "[ICON_" .. pDealItem:GetValueTypeID() .. "]"
end
deal.Name = Locale.Lookup( deal.Name )
end
end
end
end
end
end
-- =================================================================
local kDealData :table = {};
local kPlayers :table = PlayerManager.GetAliveMajors();
for _, pOtherPlayer in ipairs(kPlayers) do
local otherID:number = pOtherPlayer:GetID();
local currentGameTurn = Game.GetCurrentGameTurn();
if otherID ~= playerID then
local pPlayerConfig :table = PlayerConfigurations[otherID];
local pDeals :table = DealManager.GetPlayerDeals(playerID, otherID);
if pDeals ~= nil then
for i,pDeal in ipairs(pDeals) do
if pDeal:IsValid() then -- BRS
-- Add outgoing gold deals
local pOutgoingDeal :table = pDeal:FindItemsByType(DealItemTypes.GOLD, DealItemSubTypes.NONE, playerID);
if pOutgoingDeal ~= nil then
for i,pDealItem in ipairs(pOutgoingDeal) do
local duration :number = pDealItem:GetDuration();
local remainingTurns:number = duration - (currentGameTurn - pDealItem:GetEnactedTurn());
if duration ~= 0 then
local gold :number = pDealItem:GetAmount();
table.insert( kDealData, {
Type = DealItemTypes.GOLD,
Amount = gold,
Duration = remainingTurns, -- Infixo was duration in BRS
IsOutgoing = true,
PlayerID = otherID,
Name = Locale.Lookup( pPlayerConfig:GetCivilizationDescription() )
});
end
end
end
-- Add outgoing resource deals
pOutgoingDeal = pDeal:FindItemsByType(DealItemTypes.RESOURCES, DealItemSubTypes.NONE, playerID);
if pOutgoingDeal ~= nil then
for i,pDealItem in ipairs(pOutgoingDeal) do
local duration :number = pDealItem:GetDuration();
local remainingTurns:number = duration - (currentGameTurn - pDealItem:GetEnactedTurn());
if duration ~= 0 then
local amount :number = pDealItem:GetAmount();
local resourceType :number = pDealItem:GetValueType();
table.insert( kDealData, {
Type = DealItemTypes.RESOURCES,
ResourceType = resourceType,
Amount = amount,
Duration = remainingTurns, -- Infixo was duration in BRS
IsOutgoing = true,
PlayerID = otherID,
Name = Locale.Lookup( pPlayerConfig:GetCivilizationDescription() )
});
local entryString:string = Locale.Lookup("LOC_HUD_REPORTS_ROW_DIPLOMATIC_DEALS") .. " (" .. Locale.Lookup(pPlayerConfig:GetPlayerName()) .. " " .. Locale.Lookup("LOC_REPORTS_NUMBER_OF_TURNS", remainingTurns) .. ")";
AddResourceData(kResources, resourceType, entryString, "LOC_HUD_REPORTS_TRADE_EXPORTED", -1 * amount);
end
end
end
-- Add incoming gold deals
local pIncomingDeal :table = pDeal:FindItemsByType(DealItemTypes.GOLD, DealItemSubTypes.NONE, otherID);
if pIncomingDeal ~= nil then
for i,pDealItem in ipairs(pIncomingDeal) do
local duration :number = pDealItem:GetDuration();
local remainingTurns:number = duration - (currentGameTurn - pDealItem:GetEnactedTurn());
if duration ~= 0 then
local gold :number = pDealItem:GetAmount()
table.insert( kDealData, {
Type = DealItemTypes.GOLD;
Amount = gold,
Duration = remainingTurns, -- Infixo was duration in BRS
IsOutgoing = false,
PlayerID = otherID,
Name = Locale.Lookup( pPlayerConfig:GetCivilizationDescription() )
});
end
end
end
-- Add incoming resource deals
pIncomingDeal = pDeal:FindItemsByType(DealItemTypes.RESOURCES, DealItemSubTypes.NONE, otherID);
if pIncomingDeal ~= nil then
for i,pDealItem in ipairs(pIncomingDeal) do
local duration :number = pDealItem:GetDuration();
if duration ~= 0 then
local amount :number = pDealItem:GetAmount();
local resourceType :number = pDealItem:GetValueType();
local remainingTurns:number = duration - (currentGameTurn - pDealItem:GetEnactedTurn());
table.insert( kDealData, {
Type = DealItemTypes.RESOURCES,
ResourceType = resourceType,
Amount = amount,
Duration = remainingTurns, -- Infixo was duration in BRS
IsOutgoing = false,
PlayerID = otherID,
Name = Locale.Lookup( pPlayerConfig:GetCivilizationDescription() )
});
local entryString:string = Locale.Lookup("LOC_HUD_REPORTS_ROW_DIPLOMATIC_DEALS") .. " (" .. Locale.Lookup(pPlayerConfig:GetPlayerName()) .. " " .. Locale.Lookup("LOC_REPORTS_NUMBER_OF_TURNS", remainingTurns) .. ")";
AddResourceData(kResources, resourceType, entryString, "LOC_HUD_REPORTS_TRADE_IMPORTED", amount);
end
end
end
end -- BRS end
end
end
end
end
-- Add resources provided by city states
for i, pMinorPlayer in ipairs(PlayerManager.GetAliveMinors()) do
local pMinorPlayerInfluence:table = pMinorPlayer:GetInfluence();
if pMinorPlayerInfluence ~= nil then
local suzerainID:number = pMinorPlayerInfluence:GetSuzerain();
if suzerainID == playerID then
for row in GameInfo.Resources() do
local resourceAmount:number = pMinorPlayer:GetResources():GetExportedResourceAmount(row.Index);
if resourceAmount > 0 then
local pMinorPlayerConfig:table = PlayerConfigurations[pMinorPlayer:GetID()];
local entryString:string = Locale.Lookup("LOC_HUD_REPORTS_CITY_STATE") .. " (" .. Locale.Lookup(pMinorPlayerConfig:GetPlayerName()) .. ")";
AddResourceData(kResources, row.Index, entryString, "LOC_CITY_STATES_SUZERAIN", resourceAmount);
end
end
end
end
end
kResources = AddMiscResourceData(pResources, kResources);
--BRS !! changed
return kCityData, kCityTotalData, kResources, kUnitData, kDealData, kCurrentDeals, kUnitDataReport;
end
function AddMiscResourceData(pResourceData:table, kResourceTable:table)
if bIsGatheringStorm then return AddMiscResourceDataXP2(pResourceData, kResourceTable); end
-- Resources not yet accounted for come from other gameplay bonuses
if pResourceData then
for row in GameInfo.Resources() do
local internalResourceAmount:number = pResourceData:GetResourceAmount(row.Index);
if (internalResourceAmount > 0) then
if (kResourceTable[row.Index] ~= nil) then
if (internalResourceAmount > kResourceTable[row.Index].Total) then
AddResourceData(kResourceTable, row.Index, "LOC_HUD_REPORTS_MISC_RESOURCE_SOURCE", "-", internalResourceAmount - kResourceTable[row.Index].Total);
end
else
AddResourceData(kResourceTable, row.Index, "LOC_HUD_REPORTS_MISC_RESOURCE_SOURCE", "-", internalResourceAmount);
end
end
end
end
return kResourceTable;
end
function AddMiscResourceDataXP2(pResourceData:table, kResourceTable:table)
--Append our resource entries before we continue
kResourceTable = AppendXP2ResourceData(kResourceTable);
-- Resources not yet accounted for come from other gameplay bonuses
if pResourceData then
for row in GameInfo.Resources() do
local internalResourceAmount:number = pResourceData:GetResourceAmount(row.Index);
local resourceUnitConsumptionPerTurn:number = -pResourceData:GetUnitResourceDemandPerTurn(row.ResourceType);
local resourcePowerConsumptionPerTurn:number = -pResourceData:GetPowerResourceDemandPerTurn(row.ResourceType);
local resourceAccumulationPerTurn:number = pResourceData:GetResourceAccumulationPerTurn(row.ResourceType);
local resourceDelta:number = resourceUnitConsumptionPerTurn + resourcePowerConsumptionPerTurn + resourceAccumulationPerTurn;
if (row.ResourceClassType == "RESOURCECLASS_STRATEGIC") then
internalResourceAmount = resourceDelta;
end
if (internalResourceAmount > 0 or internalResourceAmount < 0) then
if (kResourceTable[row.Index] ~= nil) then
if (internalResourceAmount > kResourceTable[row.Index].Total) then
AddResourceData(kResourceTable, row.Index, "LOC_HUD_REPORTS_MISC_RESOURCE_SOURCE", "-", internalResourceAmount - kResourceTable[row.Index].Total);
end
else
AddResourceData(kResourceTable, row.Index, "LOC_HUD_REPORTS_MISC_RESOURCE_SOURCE", "-", internalResourceAmount);
end
end
--Stockpile only?
if pResourceData:GetResourceAmount(row.ResourceType) > 0 then
AddResourceData(kResourceTable, row.Index, "", "", 0);
end
end
end
return kResourceTable;
end
-- ===========================================================================
function AppendXP2ResourceData(kResourceData:table)
local playerID:number = Game.GetLocalPlayer();
if playerID == PlayerTypes.NONE then
UI.DataError("Unable to get valid playerID for ReportScreen_Expansion2.");
return;
end
local player:table = Players[playerID];
local pResources:table = player:GetResources();
if pResources then
for row in GameInfo.Resources() do
local resourceHash:number = row.Hash;
local resourceUnitCostPerTurn:number = pResources:GetUnitResourceDemandPerTurn(resourceHash);
local resourcePowerCostPerTurn:number = pResources:GetPowerResourceDemandPerTurn(resourceHash);
local reservedCostForProduction:number = pResources:GetReservedResourceAmount(resourceHash);
local miscResourceTotal:number = pResources:GetResourceAmount(resourceHash);
local importResources:number = pResources:GetResourceImportPerTurn(resourceHash);
if resourceUnitCostPerTurn > 0 then
AddResourceData(kResourceData, row.Index, "LOC_PRODUCTION_PANEL_UNITS_TOOLTIP", "-", -resourceUnitCostPerTurn);
end
if resourcePowerCostPerTurn > 0 then
AddResourceData(kResourceData, row.Index, "LOC_UI_PEDIA_POWER_COST", "-", -resourcePowerCostPerTurn);
end
if reservedCostForProduction > 0 then
AddResourceData(kResourceData, row.Index, "LOC_RESOURCE_REPORTS_ITEM_IN_RESERVE", "-", -reservedCostForProduction);
end
if kResourceData[row.Index] == nil and miscResourceTotal > 0 then
local titleString:string = importResources > 0 and "LOC_RESOURCE_REPORTS_CITY_STATES" or "LOC_HUD_REPORTS_MISC_RESOURCE_SOURCE";
AddResourceData(kResourceData, row.Index, titleString, "-", miscResourceTotal);
elseif importResources > 0 then
AddResourceData(kResourceData, row.Index, "LOC_RESOURCE_REPORTS_CITY_STATES", "-", importResources);
end
end
end
return kResourceData;
end
function AddResourceData( kResources:table, eResourceType:number, EntryString:string, ControlString:string, InAmount:number)
local kResource :table = GameInfo.Resources[eResourceType];
--Artifacts need to be excluded because while TECHNICALLY a resource, they do nothing to contribute in a way that is relevant to any other resource
--or screen. So... exclusion.
if kResource.ResourceClassType == "RESOURCECLASS_ARTIFACT" then
return;
end
local localPlayerID = Game.GetLocalPlayer();
local localPlayer = Players[localPlayerID];
if localPlayer then
local pPlayerResources:table = localPlayer:GetResources();
if pPlayerResources then
if kResources[eResourceType] == nil then
kResources[eResourceType] = {
EntryList = {},
Icon = "[ICON_"..kResource.ResourceType.."]",
IsStrategic = kResource.ResourceClassType == "RESOURCECLASS_STRATEGIC",
IsLuxury = GameInfo.Resources[eResourceType].ResourceClassType == "RESOURCECLASS_LUXURY",
IsBonus = GameInfo.Resources[eResourceType].ResourceClassType == "RESOURCECLASS_BONUS",
Total = 0
};
if bIsGatheringStorm then
kResources[eResourceType].Maximum = pPlayerResources:GetResourceStockpileCap(eResourceType);
kResources[eResourceType].Stockpile = pPlayerResources:GetResourceAmount(eResourceType);
end
end
if EntryString ~= "" then
table.insert( kResources[eResourceType].EntryList,
{
EntryText = EntryString,
ControlText = ControlString,
Amount = InAmount,
});
end
kResources[eResourceType].Total = kResources[eResourceType].Total + InAmount;
end -- pPlayerResources
end -- localPlayer
end
-- ===========================================================================
-- Obtain the total resources for a given city.
-- ===========================================================================
function GetCityResourceData( pCity:table )
if bIsGatheringStorm then return GetCityResourceDataXP2(pCity); end
-- Loop through all the plots for a given city; tallying the resource amount.
local kResources : table = {};
local cityPlots : table = Map.GetCityPlots():GetPurchasedPlots(pCity)
for _, plotID in ipairs(cityPlots) do
local plot : table = Map.GetPlotByIndex(plotID)
local plotX : number = plot:GetX()
local plotY : number = plot:GetY()
local eResourceType : number = plot:GetResourceType();
-- TODO: Account for trade/diplomacy resources.
if eResourceType ~= -1 and Players[pCity:GetOwner()]:GetResources():IsResourceExtractableAt(plot) then
if kResources[eResourceType] == nil then
kResources[eResourceType] = 1;
else
kResources[eResourceType] = kResources[eResourceType] + 1;
end
end
end
return kResources;
end
-- a new function used: GetResourcesExtractedByCity
function GetCityResourceDataXP2( pCity:table )
-- Loop through all the plots for a given city; tallying the resource amount.
local kResources : table = {};
local localPlayerID = Game.GetLocalPlayer();
local localPlayer = Players[localPlayerID];
if localPlayer then
local pPlayerResources:table = localPlayer:GetResources();
if pPlayerResources then
local kExtractedResources = pPlayerResources:GetResourcesExtractedByCity( pCity:GetID(), ResultFormat.SUMMARY );
if kExtractedResources ~= nil and table.count(kExtractedResources) > 0 then
for i, entry in ipairs(kExtractedResources) do
if entry.Amount > 0 then
kResources[entry.ResourceType] = entry.Amount;
end
end
end
end
end
return kResources;
end
-- ===========================================================================
-- Obtain the yields from the worked plots
-- Infixo: again, original function is incomplete, the game uses a different algorithm
-- 1. Get info about all tiles and citizens from CityManager.GetCommandTargets
-- 2. If the plot is worked then
-- 2a. if it is a District then Yield = NumSpecs * District_CitizenYieldChanges.YieldChange
-- 2b. if it is NOT a District then Yield = plot:GetYield()
-- I will break it into 2 rows, "Worked Tiles" and "Specialists" to avoid confusion
-- ===========================================================================
function GetWorkedTileYieldData( pCity:table, pCulture:table )
-- return data
local kYields:table = { YIELD_PRODUCTION = 0, YIELD_FOOD = 0, YIELD_GOLD = 0, YIELD_FAITH = 0, YIELD_SCIENCE = 0, YIELD_CULTURE = 0, TOURISM = 0 };
local kSpecYields:table = { YIELD_PRODUCTION = 0, YIELD_FOOD = 0, YIELD_GOLD = 0, YIELD_FAITH = 0, YIELD_SCIENCE = 0, YIELD_CULTURE = 0 };
local iNumWorkedPlots:number = 0;
local iNumSpecialists:number = 0;
-- code partially taken from PlotInfo.lua
local tParameters:table = {};
tParameters[CityCommandTypes.PARAM_MANAGE_CITIZEN] = UI.GetInterfaceModeParameter(CityCommandTypes.PARAM_MANAGE_CITIZEN);
local tResults:table = CityManager.GetCommandTargets( pCity, CityCommandTypes.MANAGE, tParameters );
if tResults == nil then
print("ERROR: GetWorkedTileYieldData, GetCommandTargets returned nil")
return kYields, 0, kSpecYields, 0;
end
local tPlots:table = tResults[CityCommandResults.PLOTS];
local tUnits:table = tResults[CityCommandResults.CITIZENS];
--local tMaxUnits :table = tResults[CityCommandResults.MAX_CITIZENS]; -- not used
--local tLockedUnits :table = tResults[CityCommandResults.LOCKED_CITIZENS]; -- not used
if tPlots == nil or table.count(tPlots) == 0 then
print("ERROR: GetWorkedTileYieldData, GetCommandTargets returned 0 plots")
return kYields, 0, kSpecYields, 0;
end
--print("--- PLOTS OF", pCity:GetName(), table.count(tPlots)); -- debug
--print("--- CITIZENS OF", pCity:GetName(), table.count(tUnits)); -- debug
for i,plotId in pairs(tPlots) do
local kPlot :table = Map.GetPlotByIndex(plotId);
local index:number = kPlot:GetIndex();
local eDistrictType:number = kPlot:GetDistrictType();
local numUnits:number = tUnits[i];
--local maxUnits:number = tMaxUnits[i];
--print("..plot", index, kPlot:GetX(), kPlot:GetY(), eDistrictType, numUnits, "yields", kPlot:GetYield(0), kPlot:GetYield(1));
if numUnits > 0 then -- if worked at all
if eDistrictType > 0 then -- CITY_CENTER is treated as normal tile with yields, it is not a specialist
-- district
iNumSpecialists = iNumSpecialists + numUnits;
local sDistrictType:string = GameInfo.Districts[ eDistrictType ].DistrictType;
for row in GameInfo.District_CitizenYieldChanges() do
if row.DistrictType == sDistrictType then
kSpecYields[row.YieldType] = kSpecYields[row.YieldType] + numUnits * row.YieldChange;
end
end
else
-- normal tile or City Center
iNumWorkedPlots = iNumWorkedPlots + 1;
--for row in GameInfo.Yields() do
--kYields[row.YieldType] = kYields[row.YieldType] + kPlot:GetYield(row.Index);
--end
-- 2021-05-14 Support for mods that add new yield types e.g. DE:E
for yield,idx in pairs(YieldTypes) do -- WARNING! In this context there are no extra yields from RMT - but this is ok, because they don't exist in the game anyway
kYields["YIELD_"..yield] = kYields["YIELD_"..yield] + kPlot:GetYield(idx);
end
end
end
-- Support tourism.
-- Not a common yield, and only exposure from game core is based off
-- of the plot so the sum is easily shown, but it's not possible to
-- show how individual buildings contribute... yet.
--kYields.TOURISM = kYields.TOURISM + pCulture:GetTourismAt( index );
end
-- TOURISM
-- Tourism from tiles like Wonders and Districts is not counted because they cannot be worked!
local cityX:number, cityY:number = pCity:GetX(), pCity:GetY();
--local iInside, iOutside = 0, 0;
for _, plotID in ipairs(Map.GetCityPlots():GetPurchasedPlots(pCity)) do
pPlot = Map.GetPlotByIndex(plotID);
--print("...tourism at", plotID, pCulture:GetTourismAt( plotID )); -- debug
if Map.GetPlotDistance(cityX, cityY, pPlot:GetX(), pPlot:GetY()) <= 3 then
kYields.TOURISM = kYields.TOURISM + pCulture:GetTourismAt( plotID );
--iInside = iInside + pCulture:GetTourismAt( plotID );
--if pCulture:GetTourismAt( plotID ) > 0 then print("...inside tourism at", plotID, pCulture:GetTourismAt( plotID )); end -- debug
else
--iOutside = iOutside + pCulture:GetTourismAt( plotID );
end
--kYields.TOURISM = kYields.TOURISM + pCulture:GetTourismAt( plotID );
end
--print("tourism inside", iInside, "outside", iOutside);
--print("--- SUMMARY OF", pCity:GetName(), iNumWorkedPlots, iNumSpecialists, "tourism:", kYields.TOURISM); -- debug
return kYields, iNumWorkedPlots, kSpecYields, iNumSpecialists;
end
-- ===========================================================================
-- Obtain unit maintenance
-- This function will use GameInfo for vanilla game and UnitManager for R&F/GS
function GetUnitMaintenance(pUnit:table)
if bIsRiseFall or bIsGatheringStorm then
-- Rise & Fall version
local iUnitInfoHash:number = GameInfo.Units[ pUnit:GetUnitType() ].Hash;
local unitMilitaryFormation = pUnit:GetMilitaryFormation();
if unitMilitaryFormation == MilitaryFormationTypes.CORPS_FORMATION then return UnitManager.GetUnitCorpsMaintenance(iUnitInfoHash); end
if unitMilitaryFormation == MilitaryFormationTypes.ARMY_FORMATION then return UnitManager.GetUnitArmyMaintenance(iUnitInfoHash); end
return UnitManager.GetUnitMaintenance(iUnitInfoHash);
end
-- vanilla version
local iUnitMaintenance:number = GameInfo.Units[ pUnit:GetUnitType() ].Maintenance;
local unitMilitaryFormation = pUnit:GetMilitaryFormation();
if unitMilitaryFormation == MilitaryFormationTypes.CORPS_FORMATION then return math.ceil(iUnitMaintenance * 1.5); end -- it is 150% rounded UP
if unitMilitaryFormation == MilitaryFormationTypes.ARMY_FORMATION then return iUnitMaintenance * 2; end -- it is 200%
return iUnitMaintenance;
end
-- ===========================================================================
-- Gathering Storm City Data
local tPowerImprovements:table = {
IMPROVEMENT_GEOTHERMAL_PLANT = 4, -- GEOTHERMAL_GENERATE_POWER
IMPROVEMENT_SOLAR_FARM = 2, -- SOLAR_FARM_GENERATE_POWER
IMPROVEMENT_WIND_FARM = 2, -- WIND_FARM_GENERATE_POWER
IMPROVEMENT_OFFSHORE_WIND_FARM = 2, -- OFFSHORE_WIND_FARM_GENERATE_POWER
};
-- fill improvements from MODIFIER_SINGLE_CITY_ADJUST_FREE_POWER modifiers
function InitializePowerImprovements()
end
local tPowerBuildings:table = {
BUILDING_COAL_POWER_PLANT = 4, --RESOURCE_COAL
BUILDING_FOSSIL_FUEL_POWER_PLANT = 4, --RESOURCE_OIL
BUILDING_POWER_PLANT =16, --RESOURCE_URANIUM
--BUILDING_HYDROELECTRIC_DAM = 6, -- separately
};
-- fill buildings from Buildings_XP2 and MODIFIER_SINGLE_CITY_ADJUST_FREE_POWER modifiers
function InitializePowerBuildings()
end
-- Re: Power from CityPanelPower
-- Consumed - these are sources that give power - here PowerProduced!
-- Required - these are buildings that require power - here PowerConsumed!
-- Generated - seems to be empty
--2021-05-13 Monopolies and Corporations
local eImprovementIndustry:number = -1;
local eImprovementCorporation:number = -1;
if bIsMonopolies then
eImprovementIndustry = GameInfo.Improvements.IMPROVEMENT_INDUSTRY.Index;
eImprovementCorporation = GameInfo.Improvements.IMPROVEMENT_CORPORATION.Index;
end
function AppendXP2CityData(data:table) -- data is the main city data record filled with tons of info
local pCity:table = data.City;
local pCityPower:table = pCity:GetPower();
-- Power consumption [icon required_number / consumed_number]
data.IsUnderpowered = false;
data.PowerIcon = "";
data.PowerRequired = 0;
data.PowerConsumed = 0;
data.PowerConsumedTT = {};
-- Power: Status from CityPanelPower
local freePower:number = pCityPower:GetFreePower();
local temporaryPower:number = pCityPower:GetTemporaryPower();
local currentPower:number = freePower + temporaryPower;
local requiredPower:number = pCityPower:GetRequiredPower();
local powerStatusName:string = "LOC_POWER_STATUS_POWERED_NAME"; -- [ICON_Power] Powered
local powerStatusDescription:string = "LOC_POWER_STATUS_POWERED_DESCRIPTION"; -- Buildings or Projects which require [ICON_Power] Power are fully effective.
data.PowerIcon = "[ICON_Power]";
if (requiredPower == 0) then
powerStatusName = "LOC_POWER_STATUS_NO_POWER_NEEDED_NAME"; -- Normal
powerStatusDescription = "LOC_POWER_STATUS_NO_POWER_NEEDED_DESCRIPTION"; -- This city does not require any [ICON_Power] Power.
data.PowerIcon = "";
elseif (not pCityPower:IsFullyPowered()) then
powerStatusName = "LOC_POWER_STATUS_UNPOWERED_NAME"; -- [ICON_PowerInsufficient] Unpowered
powerStatusDescription = "LOC_POWER_STATUS_UNPOWERED_DESCRIPTION";
data.PowerIcon = "[ICON_PowerInsufficient]";
data.IsUnderpowered = true;
elseif (pCityPower:IsFullyPoweredByActiveProject()) then
currentPower = requiredPower;
data.PowerIcon = "[ICON_Power][COLOR_Green]![ENDCOLOR]"
end
table.insert(data.PowerConsumedTT, Locale.Lookup(powerStatusName));
table.insert(data.PowerConsumedTT, Locale.Lookup(powerStatusDescription));
----Required from CityPanelPower.lua
if requiredPower > 0 then
table.insert(data.PowerConsumedTT, "");
table.insert(data.PowerConsumedTT, Locale.Lookup("LOC_POWER_PANEL_REQUIRED_POWER")); --..Round(requiredPower, 1)); -- [SIZE:16]{1_PowerAmount} [SIZE:12]Required
end
local requiredPowerBreakdown:table = pCityPower:GetRequiredPowerSources();
for _,innerTable in ipairs(requiredPowerBreakdown) do
local scoreSource, scoreValue = next(innerTable);
table.insert(data.PowerConsumedTT, string.format("[ICON_Bullet]%d[ICON_Power] %s", scoreValue, scoreSource));
end
-----Consumed from CityPanelPower.lua
if currentPower > 0 then
table.insert(data.PowerConsumedTT, "");
table.insert(data.PowerConsumedTT, Locale.Lookup("LOC_POWER_PANEL_CONSUMED_POWER")); --..Round(currentPower, 1)); -- [SIZE:16]{1_PowerAmount} [SIZE:12]Consumed
end
local temporaryPowerBreakdown:table = pCityPower:GetTemporaryPowerSources();
for _,innerTable in ipairs(temporaryPowerBreakdown) do
local scoreSource, scoreValue = next(innerTable);
table.insert(data.PowerConsumedTT, string.format("[ICON_Bullet]%d[ICON_Power] %s", scoreValue, scoreSource));
end
local freePowerBreakdown:table = pCityPower:GetFreePowerSources();
for _,innerTable in ipairs(freePowerBreakdown) do
local scoreSource, scoreValue = next(innerTable);
table.insert(data.PowerConsumedTT, string.format("[ICON_Bullet]%d[ICON_Power] %s", scoreValue, scoreSource));
end
data.PowerRequired = requiredPower;
data.PowerConsumed = currentPower;
data.PowerConsumedTT = table.concat(data.PowerConsumedTT, "[NEWLINE]");
-- Power produced [number]
-- buildings, improvements. Details in tooltip.
data.PowerProduced = 0; -- sort by
data.PowerProducedTT = {}; -- list of buildings and improvements
data.PowerPlantResType = "Bullet";
data.PowerPlantResUsed = 0;
-- Resource_Consumption.PowerProvided
table.insert(data.PowerProducedTT, Locale.Lookup("LOC_POWER_PANEL_GENERATED_POWER")); --..Round(data.PowerProduced, 1)); -- [SIZE:16]{1_PowerAmount} [SIZE:12]Required
-- buildings
for building,power in pairs(tPowerBuildings) do
if GameInfo.Buildings[building] ~= nil and pCity:GetBuildings():HasBuilding( GameInfo.Buildings[building].Index ) then
--data.PowerProduced = data.PowerProduced + power;
data.PowerPlantResType = GameInfo.Buildings_XP2[building].ResourceTypeConvertedToPower;
table.insert(data.PowerProducedTT, string.format("[ICON_Bullet][ICON_%s]%s", data.PowerPlantResType, Locale.Lookup(GameInfo.Buildings[building].Name)));
break; -- there can be only one!
end
end
-----Generated from CityPanelPower
local generatedPowerBreakdown:table = pCityPower:GetGeneratedPowerSources();
--if #generatedPowerBreakdown > 0 then
--end
local iPlantPower:number = 0;
for _,innerTable in ipairs(generatedPowerBreakdown) do
local scoreSource, scoreValue = next(innerTable);
--print("powerplant", data.PowerPlantRes, "score", scoreSource, scoreValue);
table.insert(data.PowerProducedTT, string.format("[ICON_Bullet]%s [ICON_Power]%d", scoreSource, scoreValue));
if string.find(scoreSource, data.PowerPlantResType) ~= nil then
iPlantPower = iPlantPower + scoreValue; -- sum up all places where power goes
end
end
-- calculate how many resources are consumed
if data.PowerPlantResType ~= "Bullet" then
local iPowerProvided:number = GameInfo.Resource_Consumption[data.PowerPlantResType].PowerProvided;
data.PowerPlantResUsed = math.floor(iPlantPower/iPowerProvided);
if data.PowerPlantResUsed * iPowerProvided < iPlantPower then data.PowerPlantResUsed = data.PowerPlantResUsed + 1; end
data.PowerProduced = data.PowerProduced + data.PowerPlantResUsed * iPowerProvided;
table.insert(data.PowerProducedTT, string.format("[ICON_Bullet]%s %d[ICON_%s] [Icon_GoingTo] %d[ICON_Power]",
Locale.Lookup("LOC_UI_PEDIA_POWER_COST"),
data.PowerPlantResUsed, data.PowerPlantResType,
data.PowerPlantResUsed * iPowerProvided));
end
-- treat Hydroelectric Dam separately for now
if GameInfo.Buildings.BUILDING_HYDROELECTRIC_DAM ~= nil and pCity:GetBuildings():HasBuilding( GameInfo.Buildings.BUILDING_HYDROELECTRIC_DAM.Index ) then
local power = 6;
data.PowerProduced = data.PowerProduced + power;
table.insert(data.PowerProducedTT, string.format("[ICON_Bullet]%d[ICON_Power] %s", power, Locale.Lookup(GameInfo.Buildings.BUILDING_HYDROELECTRIC_DAM.Name)));
end
-- support for Hydroelectric Dam Upgrade from RBU
if GameInfo.Buildings.BUILDING_HYDROELECTRIC_DAM_UPGRADE ~= nil and pCity:GetBuildings():HasBuilding( GameInfo.Buildings.BUILDING_HYDROELECTRIC_DAM_UPGRADE.Index ) then
local power = 2;
data.PowerProduced = data.PowerProduced + power;
table.insert(data.PowerProducedTT, string.format("[ICON_Bullet]%d[ICON_Power] %s", power, Locale.Lookup(GameInfo.Buildings.BUILDING_HYDROELECTRIC_DAM_UPGRADE.Name)));
end
-- Cities: CO2 footprint calculation? Is it possible?
--"Resource_Consumption" table has a field "CO2perkWh" INTEGER NOT NULL DEFAULT 0,
--GameClimate.GetPlayerResourceCO2Footprint( m_playerID, kResourceInfo.Index );
data.CO2Footprint = 0; -- must be calculated manually; sort by
data.CO2FootprintTT = "";
if data.PowerPlantResUsed > 0 then
local resConsInfo = GameInfo.Resource_Consumption[data.PowerPlantResType];
data.CO2Footprint = data.PowerPlantResUsed * resConsInfo.PowerProvided * resConsInfo.CO2perkWh / 1000;
data.CO2FootprintTT = string.format("%d[ICON_%s] @ %d", data.PowerPlantResUsed, data.PowerPlantResType, resConsInfo.CO2perkWh);
end
-- Cities: Nuclear power plant [risk_icon / nuclear icon / num turns]
data.HasNuclearPowerPlant = false;
if GameInfo.Buildings["BUILDING_POWER_PLANT"] ~= nil and pCity:GetBuildings():HasBuilding( GameInfo.Buildings["BUILDING_POWER_PLANT"].Index ) then data.HasNuclearPowerPlant = true; end
data.ReactorAge = -1;
data.NuclearAccidentIcon = "[ICON_CheckmarkBlue]";
data.NuclearPowerPlantTT = {};
-- code from ToolTipLoader_Expansion2
local kFalloutManager = Game.GetFalloutManager();
local iReactorAge:number = kFalloutManager:GetReactorAge(pCity);
if (iReactorAge ~= nil) then
data.ReactorAge = iReactorAge;
table.insert(data.NuclearPowerPlantTT, Locale.Lookup("LOC_TOOLTIP_PROJECT_REACTOR_AGE", iReactorAge));
end
local iAccidentThreshold:number = kFalloutManager:GetReactorAccidentThreshold(pCity);
if (iAccidentThreshold ~= nil) then
if (iAccidentThreshold > 0) then
data.NuclearAccidentIcon = "[COLOR_Red]![ENDCOLOR]";
table.insert(data.NuclearPowerPlantTT, Locale.Lookup("LOC_TOOLTIP_PROJECT_REACTOR_ACCIDENT1_POSSIBLE"));
end
if (iAccidentThreshold > 1) then
data.NuclearAccidentIcon = "[COLOR_Red]!![ENDCOLOR]";
table.insert(data.NuclearPowerPlantTT, Locale.Lookup("LOC_TOOLTIP_PROJECT_REACTOR_ACCIDENT2_POSSIBLE"));
end
if (iAccidentThreshold > 2) then
data.NuclearAccidentIcon = "[COLOR_Red]!!![ENDCOLOR]";
table.insert(data.NuclearPowerPlantTT, Locale.Lookup("LOC_TOOLTIP_PROJECT_REACTOR_ACCIDENT3_POSSIBLE"));
end
end
data.NuclearPowerPlantTT = table.concat(data.NuclearPowerPlantTT, "[NEWLINE]");
-- Dam district & Flood info [num tiles / dam icon]
-- Flood indicator, dam yes/no.
data.NumRiverFloodTiles = 0; -- sort by
data.HasDamDistrict = HasCityDistrict(data, "DISTRICT_DAM");
data.RiverFloodDamTT = {};
-- Info about Flood barrier. [num tiles / flood barrier icon]
-- Num of endangered tiles, per level. Tooltip - info about features (improvement, district, etc).
data.NumFloodTiles = 0; -- sort by
data.HasFloodBarrier = false;
if GameInfo.Buildings["BUILDING_FLOOD_BARRIER"] ~= nil and pCity:GetBuildings():HasBuilding( GameInfo.Buildings["BUILDING_FLOOD_BARRIER"].Index ) then data.HasFloodBarrier = true; end
data.FloodTilesTT = {};
-- Flood Barrier Per turn maintenance. [number]
-- probably manually calculated?
local iBaseMaintenance:number = 0;
if GameInfo.Buildings.BUILDING_FLOOD_BARRIER ~= nil then iBaseMaintenance = GameInfo.Buildings.BUILDING_FLOOD_BARRIER.Maintenance; end
data.FloodBarrierMaintenance = 0;
data.FloodBarrierMaintenanceTT = "";
-- from ClimateScreen.lua
local m_firstSeaLevelEvent = -1;
local m_currentSeaLevelEvent, m_currentSeaLevelPhase = -1, 0;
local iCurrentClimateChangePoints = GameClimate.GetClimateChangeForLastSeaLevelEvent();
for row in GameInfo.RandomEvents() do
if (row.EffectOperatorType == "SEA_LEVEL") then
if (m_firstSeaLevelEvent == -1) then
m_firstSeaLevelEvent = row.Index;
end
if (row.ClimateChangePoints == iCurrentClimateChangePoints) then
m_currentSeaLevelEvent = row.Index;
m_currentSeaLevelPhase = m_currentSeaLevelEvent - m_firstSeaLevelEvent + 1;
end
end
end
-- Cities: Number of RR tiles in the city borders [number]
-- this seems easy - iterate through tiles and use Plot:GetRouteType()
data.NumRailroads = 0; -- sort by
data.NumRailroadsTT = "";
-- iterate through city plots and check tiles
local cityPlots:table = Map.GetCityPlots():GetPurchasedPlots(pCity);
for _, plotID in ipairs(cityPlots) do
local plot:table = Map.GetPlotByIndex(plotID);
local plotX : number = plot:GetX()
local plotY : number = plot:GetY()
-- power sources from improvements
-- they are all done via modifiers - add later more dynamic approach
local eImprovementType:number = plot:GetImprovementType();
if eImprovementType > -1 then
local imprInfo:table = GameInfo.Improvements[eImprovementType];
if imprInfo ~= nil and tPowerImprovements[imprInfo.ImprovementType] ~= nil then
if plot:IsImprovementPillaged() then
table.insert(data.PowerProducedTT, string.format("[ICON_Bullet]%d[ICON_Power] %s %s", 0, Locale.Lookup(imprInfo.Name), Locale.Lookup("LOC_TOOLTIP_PLOT_PILLAGED_TEXT")));
else
data.PowerProduced = data.PowerProduced + tPowerImprovements[imprInfo.ImprovementType];
table.insert(data.PowerProducedTT, string.format("[ICON_Bullet]%d[ICON_Power] %s", tPowerImprovements[imprInfo.ImprovementType], Locale.Lookup(imprInfo.Name)));
end
end
end
-- tiles that can be flooded by a river LOC_FLOOD_WARNING_ICON_TOOLTIP
local function CheckPlotContent(plot:table, tooltip:table, extra:string)
if plot:GetDistrictType() ~= -1 then table.insert(tooltip, string.format("%s %s", Locale.Lookup(GameInfo.Districts[plot:GetDistrictType()].Name), extra)); end
if plot:GetImprovementType() ~= -1 then
local str = string.format("%s %s", Locale.Lookup(GameInfo.Improvements[plot:GetImprovementType()].Name), extra);
if plot:GetResourceType() ~= -1 then
local resource = GameInfo.Resources[plot:GetResourceType()];
str = "[ICON_"..resource.ResourceType.."]"..Locale.Lookup(resource.Name).." "..str;
end
table.insert(tooltip, str);
end
end
if RiverManager.CanBeFlooded(plot) then
data.NumRiverFloodTiles = data.NumRiverFloodTiles + 1;
CheckPlotContent(plot, data.RiverFloodDamTT, "");
end
-- tiles that can be submerged
local eCoastalLowland:number = TerrainManager.GetCoastalLowlandType(plot);
if eCoastalLowland ~= -1 then
local extra:string = "";
if TerrainManager.IsFlooded(plot) then extra = Locale.Lookup("LOC_COASTAL_LOWLAND_FLOODED"); end
if TerrainManager.IsSubmerged(plot) then extra = Locale.Lookup("LOC_COASTAL_LOWLAND_SUBMERGED"); end
data.NumFloodTiles = data.NumFloodTiles + 1;
CheckPlotContent(plot, data.FloodTilesTT, extra);
end
-- railroads
local eRoute:number = plot:GetRouteType()
if eRoute ~= -1 and GameInfo.Routes[eRoute] ~= nil and GameInfo.Routes[eRoute].RouteType == "ROUTE_RAILROAD" then data.NumRailroads = data.NumRailroads + 1; end
end
data.RiverFloodDamTT = table.concat(data.RiverFloodDamTT, "[NEWLINE]");
data.FloodTilesTT = table.concat(data.FloodTilesTT, "[NEWLINE]");
data.FloodBarrierMaintenance = iBaseMaintenance * (m_currentSeaLevelPhase+1) * data.NumFloodTiles;
--data.FloodBarrierMaintenanceTT = string.format("%d %d %d", iBaseMaintenance, m_currentSeaLevelPhase, data.NumFloodTiles);
if #data.PowerProducedTT == 1 then data.PowerProducedTT = "";
else data.PowerProducedTT = table.concat(data.PowerProducedTT, "[NEWLINE]"); end
-- Canals
data.NumCanals = 0;
for _,district in ipairs(data.BuildingsAndDistricts) do
if district.isBuilt and district.Type == "DISTRICT_CANAL" then data.NumCanals = data.NumCanals + 1; end
end
-- 2021-05-21 Monopolies and Corporations Mode
if bIsMonopolies then
data.HasIndustry = false;
data.HasCorporation = false;
data.Industry = "";
data.IndustryTT = "";
local localPlayerID:number = Game.GetLocalPlayer();
local pGameEconomic:table = Game.GetEconomicManager();
local sResList:string, sResListTT:string = "", ""; -- resource list - just to see what is possible
local bHasRes:boolean = false;
-- iterate through city plots
for _, plotID in ipairs(cityPlots) do
local plot:table = Map.GetPlotByIndex(plotID);
local plotX : number = plot:GetX()
local plotY : number = plot:GetY()
local eResourceType:number = plot:GetResourceType();
-- is there a resource at all
if eResourceType > -1 then
local resourceInfo:table = GameInfo.Resources[eResourceType];
local sResourceType:string = resourceInfo.ResourceType;
if resourceInfo.ResourceClassType == "RESOURCECLASS_LUXURY" and GameInfo.ResourceIndustries[sResourceType] ~= nil then -- also check if there is an industry around it!
-- only luxuries are important
local sResIcon:string = "[ICON_"..sResourceType.."]";
-- find industry effect and type - match [ICON_xxx]
local sEffectI:string = LL(GameInfo.ResourceIndustries[sResourceType].ResourceEffectTExt);
local sIndustryType:string = string.match(sEffectI, "%[ICON_%a+%]");
-- find corporation effect and type - match [ICON_xxx]
local sEffectC:string = LL(GameInfo.ResourceCorporations[sResourceType].ResourceEffectTExt);
local sCorpoType:string = string.match(sEffectC, "%[ICON_%a+%]");
-- check for industry / corpo
local eImprovementType:number = plot:GetImprovementType();
-- there can be only 1 industry or corpo in a city, so check first for that
if eImprovementType == eImprovementCorporation then
-- there is a corporation
data.HasCorporation = true;
data.Industry = string.format("[ICON_%s] %s [ICON_GreatWork_Product]", sResourceType, sCorpoType);
data.IndustryTT = string.format("%s[NEWLINE][ICON_%s] %s%s", LL("LOC_IMPROVEMENT_CORPORATION_NAME"), sResourceType, LL(resourceInfo.Name), sEffectC);
elseif eImprovementType == eImprovementIndustry then
-- there is an industry
data.HasIndustry = true;
data.Industry = sResIcon..sIndustryType;
data.IndustryTT = string.format("%s[NEWLINE]%s %s%s", LL("LOC_IMPROVEMENT_INDUSTRY_NAME"), sResIcon, LL(resourceInfo.Name), sEffectI);
-- check if we can upgrade it to corporation
if pGameEconomic:CanHaveCorporation(localPlayerID, eResourceType) then
data.Industry = data.Industry.."[COLOR_Green]![ENDCOLOR]";
data.IndustryTT = data.IndustryTT.."[NEWLINE][ICON_GoingTo]"..LL("LOC_IMPROVEMENT_CORPORATION_NAME")..sEffectC;
end
else -- build resource list
-- add resource only if there is no industry nor corpo yet around it
if not pGameEconomic:HasIndustryOf(localPlayerID, eResourceType) and not pGameEconomic:HasCorporationOf(localPlayerID, eResourceType) then
sResList = sResList..sResIcon;
sResListTT = sResListTT..(bHasRes and "[NEWLINE]" or "")..sResIcon..LL(resourceInfo.Name)..sEffectI;
bHasRes = true;
-- if we can have an industry - add the mark
if pGameEconomic:CanHaveIndustry(localPlayerID, eResourceType) then
sResList = sResList.."[COLOR_Green]![ENDCOLOR]";
sResListTT = sResListTT.."[NEWLINE][ICON_GoingTo]"..LL("LOC_IMPROVEMENT_INDUSTRY_NAME");
end
end -- no IC yet
end
end -- luxury only
end -- resource check
-- if there is no industry nor corpo - put res list
if not data.HasIndustry and not data.HasCorporation then
data.Industry = sResList;
data.IndustryTT = sResListTT;
end
end -- city plots
end -- monopolies mode
end
-- ===========================================================================
-- Set a group to it's proper collapse/open state
-- Set + - in group row
-- ===========================================================================
function RealizeGroup( instance:table )
local v :number = (instance["isCollapsed"]==false and instance.RowExpandCheck:GetSizeY() or 0);
instance.RowExpandCheck:SetTextureOffsetVal(0, v);
instance.ContentStack:CalculateSize();
instance.CollapseScroll:CalculateSize();
local groupHeight :number = instance.ContentStack:GetSizeY();
instance.CollapseAnim:SetBeginVal(0, -(groupHeight - instance["CollapsePadding"]));
instance.CollapseScroll:SetSizeY( groupHeight );
instance.Top:ReprocessAnchoring();
end
-- ===========================================================================
-- Callback
-- Expand or contract a group based on its existing state.
-- ===========================================================================
function OnToggleCollapseGroup( instance:table )
instance["isCollapsed"] = not instance["isCollapsed"];
instance.CollapseAnim:Reverse();
RealizeGroup( instance );
end
-- ===========================================================================
-- Toggle a group expanding / collapsing
-- instance, A group instance.
-- ===========================================================================
function OnAnimGroupCollapse( instance:table)
-- Helper
function lerp(y1:number,y2:number,x:number)
return y1 + (y2-y1)*x;
end
local groupHeight :number = instance.ContentStack:GetSizeY();
local collapseHeight:number = instance["CollapsePadding"]~=nil and instance["CollapsePadding"] or 0;
local startY :number = instance["isCollapsed"]==true and groupHeight or collapseHeight;
local endY :number = instance["isCollapsed"]==false and groupHeight or collapseHeight;
local progress :number = instance.CollapseAnim:GetProgress();
local sizeY :number = lerp(startY,endY,progress);
instance.CollapseAnim:SetSizeY( groupHeight ); -- BRS added, INFIXO CHECK
instance.CollapseScroll:SetSizeY( sizeY );
instance.ContentStack:ReprocessAnchoring();
instance.Top:ReprocessAnchoring()
Controls.Stack:CalculateSize();
Controls.Scroll:CalculateSize();
end
-- ===========================================================================
function SetGroupCollapsePadding( instance:table, amount:number )
instance["CollapsePadding"] = amount;
end
-- ===========================================================================
function ResetTabForNewPageContent()
m_uiGroups = {};
m_simpleIM:ResetInstances();
m_groupIM:ResetInstances();
m_isCollapsing = true;
Controls.CollapseAll:LocalizeAndSetText("LOC_HUD_REPORTS_COLLAPSE_ALL");
Controls.Scroll:SetScrollValue( 0 );
m_kGossipInstances = {};
end
-- ===========================================================================
-- Instantiate a new collapsable row (group) holder & wire it up.
-- ARGS: (optional) isCollapsed
-- RETURNS: New group instance
-- ===========================================================================
function NewCollapsibleGroupInstance( isCollapsed:boolean )
if isCollapsed == nil then
isCollapsed = false;
end
local instance:table = m_groupIM:GetInstance();
instance.ContentStack:DestroyAllChildren();
instance["isCollapsed"] = isCollapsed;
instance["CollapsePadding"] = nil; -- reset any prior collapse padding
--BRS !! added
instance["Children"] = {}
instance["Descend"] = false
-- !!
instance.CollapseAnim:SetToBeginning();
if isCollapsed == false then
instance.CollapseAnim:SetToEnd();
end
instance.RowHeaderButton:RegisterCallback( Mouse.eLClick, function() OnToggleCollapseGroup(instance); end );
instance.RowHeaderButton:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end);
instance.CollapseAnim:RegisterAnimCallback( function() OnAnimGroupCollapse( instance ); end );
table.insert( m_uiGroups, instance );
return instance;
end
-- ===========================================================================
-- debug - Create a test page.
-- ===========================================================================
function ViewTestPage()
ResetTabForNewPageContent();
local instance:table = NewCollapsibleGroupInstance();
instance.RowHeaderButton:SetText( "Test City Icon 1" );
instance.Top:SetID("foo");
local pHeaderInstance:table = {}
ContextPtr:BuildInstanceForControl( "CityIncomeHeaderInstance", pHeaderInstance, instance.ContentStack ) ;
local pCityInstance:table = {};
ContextPtr:BuildInstanceForControl( "CityIncomeInstance", pCityInstance, instance.ContentStack ) ;
for i=1,3,1 do
local pLineItemInstance:table = {};
ContextPtr:BuildInstanceForControl("CityIncomeLineItemInstance", pLineItemInstance, pCityInstance.LineItemStack );
end
local pFooterInstance:table = {};
ContextPtr:BuildInstanceForControl("CityIncomeFooterInstance", pFooterInstance, instance.ContentStack );
SetGroupCollapsePadding(instance, pFooterInstance.Top:GetSizeY() );
RealizeGroup( instance );
Controls.BottomYieldTotals:SetHide( true );
Controls.BottomResourceTotals:SetHide( true );
Controls.BottomPoliciesFilters:SetHide( true );
Controls.Scroll:SetSizeY( Controls.Main:GetSizeY() - (Controls.BottomYieldTotals:GetSizeY() + SIZE_HEIGHT_PADDING_BOTTOM_ADJUST ) );
end
--BRS !! sort features for income
local sortCities : table = { by = "CityName", descend = false }
local function sortByCities( name )
if name == sortCities.by then
sortCities.descend = not sortCities.descend
else
sortCities.by = name
sortCities.descend = true
if name == "CityName" then sortCities.descend = false; end -- exception
end
ViewYieldsPage()
end
local function sortFunction( t, a, b )
if sortCities.by == "TourismPerTurn" then
if sortCities.descend then
return t[b].WorkedTileYields["TOURISM"] < t[a].WorkedTileYields["TOURISM"]
else
return t[b].WorkedTileYields["TOURISM"] > t[a].WorkedTileYields["TOURISM"]
end
else
if sortCities.descend then
return t[b][sortCities.by] < t[a][sortCities.by]
else
return t[b][sortCities.by] > t[a][sortCities.by]
end
end
end
-- ===========================================================================
-- Tab Callback
-- ===========================================================================
local populationToCultureScale:number = GameInfo.GlobalParameters["CULTURE_PERCENTAGE_YIELD_PER_POP"].Value / 100;
local populationToScienceScale:number = GameInfo.GlobalParameters["SCIENCE_PERCENTAGE_YIELD_PER_POP"].Value / 100; -- Infixo added science per pop
function ViewYieldsPage()
ResetTabForNewPageContent();
local pPlayer:table = Players[Game.GetLocalPlayer()]; --BRS
local instance:table = nil;
instance = NewCollapsibleGroupInstance();
instance.RowHeaderButton:SetText( Locale.Lookup("LOC_HUD_REPORTS_ROW_CITY_INCOME") );
instance.RowHeaderLabel:SetHide( true ); --BRS
instance.AmenitiesContainer:SetHide(true);
instance.IndustryContainer:SetHide(true); -- 2021-05-21
instance.MonopolyContainer:SetHide(true); -- 2021-05-21
local pHeaderInstance:table = {}
ContextPtr:BuildInstanceForControl( "CityIncomeHeaderInstance", pHeaderInstance, instance.ContentStack ) ;
--BRS sorting
-- sorting is a bit weird because ViewYieldsPage is called again and entire tab is recreated, so new callbacks are registered
pHeaderInstance.CityNameButton:RegisterCallback( Mouse.eLClick, function() sortByCities( "CityName" ) end )
pHeaderInstance.ProductionButton:RegisterCallback( Mouse.eLClick, function() sortByCities( "ProductionPerTurn" ) end )
--pHeaderInstance.FoodButton:RegisterCallback( Mouse.eLClick, function() sortByCities( "FoodPerTurn" ) end )
pHeaderInstance.FoodButton:RegisterCallback( Mouse.eLClick, function() sortByCities( "TotalFoodSurplus" ) end )
pHeaderInstance.GoldButton:RegisterCallback( Mouse.eLClick, function() sortByCities( "GoldPerTurn" ) end )
pHeaderInstance.FaithButton:RegisterCallback( Mouse.eLClick, function() sortByCities( "FaithPerTurn" ) end )
pHeaderInstance.ScienceButton:RegisterCallback( Mouse.eLClick, function() sortByCities( "SciencePerTurn" ) end )
pHeaderInstance.CultureButton:RegisterCallback( Mouse.eLClick, function() sortByCities( "CulturePerTurn" ) end )
pHeaderInstance.TourismButton:RegisterCallback( Mouse.eLClick, function() sortByCities( "TourismPerTurn" ) end )
local goldCityTotal :number = 0;
local faithCityTotal :number = 0;
local scienceCityTotal :number = 0;
local cultureCityTotal :number = 0;
local tourismCityTotal :number = 0;
-- helper for calculating lines from modifiers
local function GetEmptyYieldsTable()
return { YIELD_PRODUCTION = 0, YIELD_FOOD = 0, YIELD_GOLD = 0, YIELD_FAITH = 0, YIELD_SCIENCE = 0, YIELD_CULTURE = 0 };
end
-- Infixo needed to properly calculate yields from % modifiers (like amenities)
local kBaseYields:table = GetEmptyYieldsTable();
kBaseYields.TOURISM = 0;
local function StoreInBaseYields(sYield:string, fValue:number) kBaseYields[ sYield ] = kBaseYields[ sYield ] + fValue; end
-- ========== City Income ==========
function CreatLineItemInstance(cityInstance:table, name:string, production:number, gold:number, food:number, science:number, culture:number, faith:number, bDontStore:boolean)
local lineInstance:table = {};
ContextPtr:BuildInstanceForControl("CityIncomeLineItemInstance", lineInstance, cityInstance.LineItemStack );
TruncateStringWithTooltipClean(lineInstance.LineItemName, 345, name);
lineInstance.Production:SetText( toPlusMinusNoneString(production));
lineInstance.Food:SetText( toPlusMinusNoneString(food));
lineInstance.Gold:SetText( toPlusMinusNoneString(gold));
lineInstance.Faith:SetText( toPlusMinusNoneString(faith));
lineInstance.Science:SetText( toPlusMinusNoneString(science));
lineInstance.Culture:SetText( toPlusMinusNoneString(culture));
--BRS Infixo needed to properly calculate yields from % modifiers (like amenities)
if bDontStore then return lineInstance; end -- default: omit param and store
StoreInBaseYields("YIELD_PRODUCTION", production);
StoreInBaseYields("YIELD_FOOD", food);
StoreInBaseYields("YIELD_GOLD", gold);
StoreInBaseYields("YIELD_FAITH", faith);
StoreInBaseYields("YIELD_SCIENCE", science);
StoreInBaseYields("YIELD_CULTURE", culture);
StoreInBaseYields("TOURISM", 0); -- not passed here
--BRS end
return lineInstance;
end
--BRS this function will be used to set singular fields in LineItemInstance, based on YieldType
function SetFieldInLineItemInstance(lineItemInstance:table, yieldType:string, yieldValue:number)
if yieldType == "YIELD_PRODUCTION" then lineItemInstance.Production:SetText( toPlusMinusNoneString(yieldValue) );
elseif yieldType == "YIELD_FOOD" then lineItemInstance.Food:SetText( toPlusMinusNoneString(yieldValue) );
elseif yieldType == "YIELD_GOLD" then lineItemInstance.Gold:SetText( toPlusMinusNoneString(yieldValue) );
elseif yieldType == "YIELD_FAITH" then lineItemInstance.Faith:SetText( toPlusMinusNoneString(yieldValue) );
elseif yieldType == "YIELD_SCIENCE" then lineItemInstance.Science:SetText( toPlusMinusNoneString(yieldValue) );
elseif yieldType == "YIELD_CULTURE" then lineItemInstance.Culture:SetText( toPlusMinusNoneString(yieldValue) );
end
StoreInBaseYields(yieldType, yieldValue);
end
for cityName,kCityData in spairs( m_kCityData, function( t, a, b ) return sortFunction( t, a, b ) end ) do --BRS sorting
local pCityInstance:table = {};
ContextPtr:BuildInstanceForControl( "CityIncomeInstance", pCityInstance, instance.ContentStack ) ;
pCityInstance.LineItemStack:DestroyAllChildren();
TruncateStringWithTooltip(pCityInstance.CityName, 230, (kCityData.IsCapital and "[ICON_Capital]" or "")..Locale.Lookup(kCityData.CityName));
pCityInstance.CityPopulation:SetText(kCityData.Population);
--Great works
local greatWorks:table = GetGreatWorksForCity(kCityData.City);
-- Infixo reset base for amenities
for yield,_ in pairs(kBaseYields) do kBaseYields[ yield ] = 0; end
-- go to the city after clicking
pCityInstance.GoToCityButton:RegisterCallback( Mouse.eLClick, function() Close(); UI.LookAtPlot( kCityData.City:GetX(), kCityData.City:GetY() ); UI.SelectCity( kCityData.City ); end );
pCityInstance.GoToCityButton:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound( "Main_Menu_Mouse_Over" ); end );
-- Current Production
local kCurrentProduction:table = kCityData.ProductionQueue[1]; -- this returns a table from GetCurrentProductionInfoOfCity() modified a bit in CitySupport.lua
pCityInstance.CurrentProduction:SetHide( kCurrentProduction == nil );
if kCurrentProduction ~= nil then
--print("**********", cityName); dshowrectable(kCurrentProduction);
local tooltip:string = kCurrentProduction.Name.." [ICON_Turn]"..tostring(kCurrentProduction.Turns)..string.format(" (%d%%)", kCurrentProduction.PercentComplete*100);
if kCurrentProduction.Description ~= nil then
tooltip = tooltip .. "[NEWLINE]" .. Locale.Lookup(kCurrentProduction.Description);
end
pCityInstance.CurrentProduction:SetToolTipString( tooltip );
if kCurrentProduction.Icons ~= nil then
pCityInstance.CityBannerBackground:SetHide( false );
-- Gathering Storm - there are 5 icons returned now
for _,iconName in ipairs(kCurrentProduction.Icons) do
if iconName ~= nil and pCityInstance.CurrentProduction:TrySetIcon(iconName) then break; end
end
pCityInstance.CityProductionMeter:SetPercent( kCurrentProduction.PercentComplete );
pCityInstance.CityProductionNextTurn:SetPercent( kCurrentProduction.PercentCompleteNextTurn );
pCityInstance.ProductionBorder:SetHide( kCurrentProduction.Type == ProductionType.DISTRICT );
else
pCityInstance.CityBannerBackground:SetHide( true );
end
end
-- Infixo: this is the place to add Yield Focus
local function SetYieldTextAndFocusFlag(pLabel:table, fValue:number, eYieldType:number)
local sText:string = toPlusMinusString(fValue);
local sToolTip:string = "";
if kCityData.YieldFilters[eYieldType] == YIELD_STATE.FAVORED then
sText = sText.." [COLOR:0,255,0,255]!"; -- [ICON_FoodSurplus][ICON_CheckSuccess]
sToolTip = Locale.Lookup("LOC_HUD_CITY_YIELD_FOCUSING", GameInfo.Yields[eYieldType].Name);
elseif kCityData.YieldFilters[eYieldType] == YIELD_STATE.IGNORED then
sText = sText.." [COLOR:255,0,0,255]!"; -- [ICON_FoodDeficit][ICON_CheckFail]
sToolTip = Locale.Lookup("LOC_HUD_CITY_YIELD_IGNORING", GameInfo.Yields[eYieldType].Name);
end
pLabel:SetText( sText );
pLabel:SetToolTipString( sToolTip );
end
SetYieldTextAndFocusFlag( pCityInstance.Production,kCityData.ProductionPerTurn,YieldTypes.PRODUCTION );
--SetYieldTextAndFocusFlag( pCityInstance.Food, kCityData.FoodPerTurn, YieldTypes.FOOD );
SetYieldTextAndFocusFlag( pCityInstance.Food, kCityData.TotalFoodSurplus, YieldTypes.FOOD );
SetYieldTextAndFocusFlag( pCityInstance.Gold, kCityData.GoldPerTurn, YieldTypes.GOLD );
SetYieldTextAndFocusFlag( pCityInstance.Faith, kCityData.FaithPerTurn, YieldTypes.FAITH );
SetYieldTextAndFocusFlag( pCityInstance.Science, kCityData.SciencePerTurn, YieldTypes.SCIENCE );
SetYieldTextAndFocusFlag( pCityInstance.Culture, kCityData.CulturePerTurn, YieldTypes.CULTURE );
pCityInstance.Tourism:SetText( toPlusMinusString(kCityData.WorkedTileYields["TOURISM"]) ); -- unchanged (no focus feature here)
-- BIG food tooltip
pCityInstance.FoodContainer:SetToolTipString(kCityData.TotalFoodSurplusToolTip);
-- Add to all cities totals
goldCityTotal = goldCityTotal + kCityData.GoldPerTurn;
faithCityTotal = faithCityTotal + kCityData.FaithPerTurn;
scienceCityTotal= scienceCityTotal + kCityData.SciencePerTurn;
cultureCityTotal= cultureCityTotal + kCityData.CulturePerTurn;
tourismCityTotal= tourismCityTotal + kCityData.WorkedTileYields["TOURISM"];
if not Controls.HideCityBuildingsCheckbox:IsSelected() then --BRS
-- Worked Tiles
if kCityData.NumWorkedTiles > 0 then
CreatLineItemInstance( pCityInstance,
Locale.Lookup("LOC_HUD_REPORTS_WORKED_TILES")..string.format(" [COLOR_White]%d[ENDCOLOR]", kCityData.NumWorkedTiles),
kCityData.WorkedTileYields["YIELD_PRODUCTION"],
kCityData.WorkedTileYields["YIELD_GOLD"],
kCityData.WorkedTileYields["YIELD_FOOD"],
kCityData.WorkedTileYields["YIELD_SCIENCE"],
kCityData.WorkedTileYields["YIELD_CULTURE"],
kCityData.WorkedTileYields["YIELD_FAITH"]);
end
-- Specialists
if kCityData.NumSpecialists > 0 then
CreatLineItemInstance( pCityInstance,
Locale.Lookup("LOC_BRS_SPECIALISTS")..string.format(" [COLOR_White]%d[ENDCOLOR]", kCityData.NumSpecialists),
kCityData.SpecialistYields["YIELD_PRODUCTION"],
kCityData.SpecialistYields["YIELD_GOLD"],
kCityData.SpecialistYields["YIELD_FOOD"],
kCityData.SpecialistYields["YIELD_SCIENCE"],
kCityData.SpecialistYields["YIELD_CULTURE"],
kCityData.SpecialistYields["YIELD_FAITH"]);
end
-- Additional Yields from Population
-- added modifiers with EFFECT_ADJUST_CITY_YIELD_PER_POPULATION
local tPopYields:table = GetEmptyYieldsTable(); -- will always show
for _,mod in ipairs(kCityData.Modifiers) do
if mod.Modifier.EffectType == "EFFECT_ADJUST_CITY_YIELD_PER_POPULATION" then
tPopYields[ mod.Arguments.YieldType ] = tPopYields[ mod.Arguments.YieldType ] + kCityData.Population * tonumber(mod.Arguments.Amount);
end
end
CreatLineItemInstance( pCityInstance,
Locale.Lookup("LOC_HUD_CITY_POPULATION")..string.format(" [COLOR_White]%d[ENDCOLOR]", kCityData.Population),
tPopYields.YIELD_PRODUCTION,
tPopYields.YIELD_GOLD,
tPopYields.YIELD_FOOD + kCityData.FoodConsumption, -- food
tPopYields.YIELD_SCIENCE + kCityData.Population * populationToScienceScale,
tPopYields.YIELD_CULTURE + kCityData.Population * populationToCultureScale,
tPopYields.YIELD_FAITH);
-- Main loop for all districts and buildings
for i,kDistrict in ipairs(kCityData.BuildingsAndDistricts) do
--District line item
--BRS GetYield() includes also GetAdjacencyYield(), so must subtract to not duplicate them
local districtInstance = CreatLineItemInstance( pCityInstance,
(kDistrict.isBuilt and kDistrict.Name) or Locale.Lookup("LOC_CITY_BANNER_PRODUCING", kDistrict.Name),
kDistrict.Production - kDistrict.AdjacencyBonus.Production,
kDistrict.Gold - kDistrict.AdjacencyBonus.Gold,
kDistrict.Food - kDistrict.AdjacencyBonus.Food,
kDistrict.Science - kDistrict.AdjacencyBonus.Science,
kDistrict.Culture - kDistrict.AdjacencyBonus.Culture,
kDistrict.Faith - kDistrict.AdjacencyBonus.Faith);
districtInstance.DistrictIcon:SetHide(false);
districtInstance.DistrictIcon:SetIcon(kDistrict.Icon);
function HasValidAdjacencyBonus(adjacencyTable:table)
for _, yield in pairs(adjacencyTable) do
if yield ~= 0 then
return true;
end
end
return false;
end
--Adjacency
if kDistrict.isBuilt and HasValidAdjacencyBonus(kDistrict.AdjacencyBonus) then -- Infixo fix for checking if it is actually built!
CreatLineItemInstance( pCityInstance,
INDENT_STRING .. Locale.Lookup("LOC_HUD_REPORTS_ADJACENCY_BONUS"),
kDistrict.AdjacencyBonus.Production,
kDistrict.AdjacencyBonus.Gold,
kDistrict.AdjacencyBonus.Food,
kDistrict.AdjacencyBonus.Science,
kDistrict.AdjacencyBonus.Culture,
kDistrict.AdjacencyBonus.Faith);
end
for i,kBuilding in ipairs(kDistrict.Buildings) do
CreatLineItemInstance( pCityInstance,
INDENT_STRING .. kBuilding.Name,
kBuilding.ProductionPerTurn,
kBuilding.GoldPerTurn,
kBuilding.FoodPerTurn,
kBuilding.SciencePerTurn,
kBuilding.CulturePerTurn,
kBuilding.FaithPerTurn);
--Add great works
if greatWorks[kBuilding.Type] ~= nil then
--Add our line items!
for _, kGreatWork in ipairs(greatWorks[kBuilding.Type]) do
local sIconString:string = GameInfo.GreatWorkObjectTypes[ kGreatWork.GreatWorkObjectType ].IconString;
local pLineItemInstance:table = CreatLineItemInstance(pCityInstance, INDENT_STRING..INDENT_STRING..sIconString..Locale.Lookup(kGreatWork.Name), 0, 0, 0, 0, 0, 0);
for _, yield in ipairs(kGreatWork.YieldChanges) do
SetFieldInLineItemInstance(pLineItemInstance, yield.YieldType, yield.YieldChange);
end
end
end
end
end
-- Display wonder yields
if kCityData.Wonders then
for _, wonder in ipairs(kCityData.Wonders) do
if wonder.Yields[1] ~= nil or greatWorks[wonder.Type] ~= nil then
-- Assign yields to the line item
local pLineItemInstance:table = CreatLineItemInstance(pCityInstance, wonder.Name, 0, 0, 0, 0, 0, 0);
pLineItemInstance.DistrictIcon:SetHide(false);
pLineItemInstance.DistrictIcon:SetIcon("ICON_DISTRICT_WONDER");
-- Show yields
for _, yield in ipairs(wonder.Yields) do
SetFieldInLineItemInstance(pLineItemInstance, yield.YieldType, yield.YieldChange);
end
end
--Add great works
if greatWorks[wonder.Type] ~= nil then
--Add our line items!
for _, kGreatWork in ipairs(greatWorks[wonder.Type]) do
local sIconString:string = GameInfo.GreatWorkObjectTypes[ kGreatWork.GreatWorkObjectType ].IconString;
local pLineItemInstance:table = CreatLineItemInstance(pCityInstance, INDENT_STRING..sIconString..Locale.Lookup(kGreatWork.Name), 0, 0, 0, 0, 0, 0);
for _, yield in ipairs(kGreatWork.YieldChanges) do
SetFieldInLineItemInstance(pLineItemInstance, yield.YieldType, yield.YieldChange);
end
end
end
end
end
-- Display route yields
if kCityData.OutgoingRoutes then
for i,route in ipairs(kCityData.OutgoingRoutes) do
if route ~= nil then
if route.OriginYields then
-- Find destination city
local pDestPlayer:table = Players[route.DestinationCityPlayer];
local pDestPlayerCities:table = pDestPlayer:GetCities();
local pDestCity:table = pDestPlayerCities:FindID(route.DestinationCityID);
--Assign yields to the line item
local pLineItemInstance:table = CreatLineItemInstance(pCityInstance, Locale.Lookup("LOC_HUD_REPORTS_TRADE_WITH", Locale.Lookup(pDestCity:GetName())), 0, 0, 0, 0, 0, 0);
for j,yield in ipairs(route.OriginYields) do
local yieldInfo = GameInfo.Yields[yield.YieldIndex];
if yieldInfo then
SetFieldInLineItemInstance(pLineItemInstance, yieldInfo.YieldType, yield.Amount);
end
end
end
end
end
end
-- Flat yields from Modifiers EFFECT_ADJUST_CITY_YIELD_CHANGE
local tFlatYields:table = GetEmptyYieldsTable();
local bFlatYields:boolean = false;
for _,mod in ipairs(kCityData.Modifiers) do
if mod.Modifier.EffectType == "EFFECT_ADJUST_CITY_YIELD_CHANGE" then
tFlatYields[ mod.Arguments.YieldType ] = tFlatYields[ mod.Arguments.YieldType ] + tonumber(mod.Arguments.Amount);
bFlatYields = true;
end
end
--print("MOD from FLAT YIELDS"); for k,v in pairs(tFlatYields) do print(k,v); end
if bFlatYields then
CreatLineItemInstance(
pCityInstance, Locale.Lookup("LOC_BRS_FROM_MODIFIERS"),
tFlatYields.YIELD_PRODUCTION, tFlatYields.YIELD_GOLD, tFlatYields.YIELD_FOOD, tFlatYields.YIELD_SCIENCE, tFlatYields.YIELD_CULTURE, tFlatYields.YIELD_FAITH
); -- this one needs to be stored
end
-- Flat yields from Modifiers EFFECT_ADJUST_CITY_YIELD_PER_DISTRICT
if kCityData.NumSpecialtyDistricts > 0 then
tFlatYields = GetEmptyYieldsTable();
bFlatYields = false;
for _,mod in ipairs(kCityData.Modifiers) do
if mod.Modifier.EffectType == "EFFECT_ADJUST_CITY_YIELD_PER_DISTRICT" then
tFlatYields[ mod.Arguments.YieldType ] = tFlatYields[ mod.Arguments.YieldType ] + tonumber(mod.Arguments.Amount) * kCityData.NumSpecialtyDistricts;
bFlatYields = true;
end
end
if bFlatYields then
CreatLineItemInstance(
pCityInstance, Locale.Lookup("LOC_BRS_HAVING_DISTRICTS", kCityData.NumSpecialtyDistricts),
tFlatYields.YIELD_PRODUCTION, tFlatYields.YIELD_GOLD, tFlatYields.YIELD_FOOD, tFlatYields.YIELD_SCIENCE, tFlatYields.YIELD_CULTURE, tFlatYields.YIELD_FAITH
); -- this one needs to be stored
end
end
-- Flat yields from Modifiers EFFECT_ADJUST_CITY_PRODUCTION_BUILDING
if kCityData.CurrentProductionType == "BUILDING" then
tFlatYields = GetEmptyYieldsTable();
bFlatYields = false;
for _,mod in ipairs(kCityData.Modifiers) do
if mod.Modifier.EffectType == "EFFECT_ADJUST_CITY_PRODUCTION_BUILDING" then
tFlatYields.YIELD_PRODUCTION = tFlatYields.YIELD_PRODUCTION + tonumber(mod.Arguments.Amount);
bFlatYields = true;
end
end
if bFlatYields then
CreatLineItemInstance(
pCityInstance, Locale.Lookup("LOC_BRS_PROD_BUILDINGS"),
tFlatYields.YIELD_PRODUCTION, tFlatYields.YIELD_GOLD, tFlatYields.YIELD_FOOD, tFlatYields.YIELD_SCIENCE, tFlatYields.YIELD_CULTURE, tFlatYields.YIELD_FAITH
); -- this one needs to be stored
end
end
-- Flat yields from Modifiers EFFECT_ADJUST_CITY_PRODUCTION_DISTRICT
if kCityData.CurrentProductionType == "DISTRICT" then
tFlatYields = GetEmptyYieldsTable();
bFlatYields = false;
for _,mod in ipairs(kCityData.Modifiers) do
if mod.Modifier.EffectType == "EFFECT_ADJUST_CITY_PRODUCTION_DISTRICT" then
tFlatYields.YIELD_PRODUCTION = tFlatYields.YIELD_PRODUCTION + tonumber(mod.Arguments.Amount);
bFlatYields = true;
end
end
if bFlatYields then
CreatLineItemInstance(
pCityInstance, Locale.Lookup("LOC_BRS_PROD_DISTRICTS"),
tFlatYields.YIELD_PRODUCTION, tFlatYields.YIELD_GOLD, tFlatYields.YIELD_FOOD, tFlatYields.YIELD_SCIENCE, tFlatYields.YIELD_CULTURE, tFlatYields.YIELD_FAITH
); -- this one needs to be stored
end
end
-- Flat yields from Modifiers EFFECT_ADJUST_CITY_PRODUCTION_UNIT
if kCityData.CurrentProductionType == "UNIT" then
tFlatYields = GetEmptyYieldsTable();
bFlatYields = false;
for _,mod in ipairs(kCityData.Modifiers) do
if mod.Modifier.EffectType == "EFFECT_ADJUST_CITY_PRODUCTION_UNIT" then
tFlatYields.YIELD_PRODUCTION = tFlatYields.YIELD_PRODUCTION + tonumber(mod.Arguments.Amount);
bFlatYields = true;
end
end
if bFlatYields then
CreatLineItemInstance(
pCityInstance, Locale.Lookup("LOC_BRS_PROD_UNITS"),
tFlatYields.YIELD_PRODUCTION, tFlatYields.YIELD_GOLD, tFlatYields.YIELD_FOOD, tFlatYields.YIELD_SCIENCE, tFlatYields.YIELD_CULTURE, tFlatYields.YIELD_FAITH
); -- this one needs to be stored
end
end
-- Religious followers EFFECT_ADJUST_FOLLOWER_YIELD_MODIFIER
local tFollowersModifiers:table = GetEmptyYieldsTable(); -- not yields, but stores numbers anyway
local bShowFollowers:boolean = false;
for _,mod in ipairs(kCityData.Modifiers) do
if mod.Modifier.EffectType == "EFFECT_ADJUST_FOLLOWER_YIELD_MODIFIER" then
tFollowersModifiers[ mod.Arguments.YieldType ] = tFollowersModifiers[ mod.Arguments.YieldType ] + tonumber(mod.Arguments.Amount);
bShowFollowers = true;
end
end
--print("MOD from FOLLOWERS"); for k,v in pairs(tFollowersModifiers) do print(k,v); end
if bShowFollowers then
CreatLineItemInstance( pCityInstance,
Locale.Lookup("LOC_UI_RELIGION_FOLLOWERS")..string.format(" [COLOR_White]%d[ENDCOLOR]", kCityData.MajorityReligionFollowers),
kBaseYields.YIELD_PRODUCTION * tFollowersModifiers.YIELD_PRODUCTION * kCityData.MajorityReligionFollowers / 100.0,
kBaseYields.YIELD_GOLD * tFollowersModifiers.YIELD_GOLD * kCityData.MajorityReligionFollowers / 100.0,
kBaseYields.YIELD_FOOD * tFollowersModifiers.YIELD_FOOD * kCityData.MajorityReligionFollowers / 100.0,
kBaseYields.YIELD_SCIENCE * tFollowersModifiers.YIELD_SCIENCE * kCityData.MajorityReligionFollowers / 100.0,
kBaseYields.YIELD_CULTURE * tFollowersModifiers.YIELD_CULTURE * kCityData.MajorityReligionFollowers / 100.0,
kBaseYields.YIELD_FAITH * tFollowersModifiers.YIELD_FAITH * kCityData.MajorityReligionFollowers / 100.0,
true); -- don't store in base yields, we'll need it for other rows
end
-- Percentage scaled yields from Modifiers EFFECT_ADJUST_CITY_YIELD_MODIFIER
local tPercYields:table = GetEmptyYieldsTable();
local bPercYields:boolean = false;
for _,mod in ipairs(kCityData.Modifiers) do
if mod.Modifier.EffectType == "EFFECT_ADJUST_CITY_YIELD_MODIFIER" then
if tonumber(mod.Arguments.Amount) == nil then
-- 2020-05-29 Special case for Maya civ - yields and percentages are encoded in a single argument as a group of values delimited with comma
local yields:table, percentages:table = {}, {};
for str in string.gmatch( mod.Arguments.YieldType, "[_%a]+" ) do table.insert(yields, str) end
for str in string.gmatch( mod.Arguments.Amount, "-?%d+" ) do table.insert(percentages, str) end
if #yields == #percentages then -- extra precaution for mods
for i,yield in ipairs(yields) do
tPercYields[ yield ] = tPercYields[ yield ] + tonumber(percentages[i]);
end
end
--dshowtable(yields); dshowtable(percentages); dshowtable(tPercYields); -- debug
else
tPercYields[ mod.Arguments.YieldType ] = tPercYields[ mod.Arguments.YieldType ] + tonumber(mod.Arguments.Amount);
end
bPercYields = true;
end
end
--print("MOD from PERC YIELDS", cityName); for k,v in pairs(tPercYields) do print(k,v); end
if bPercYields then
CreatLineItemInstance( pCityInstance,
Locale.Lookup("LOC_BRS_FROM_MODIFIERS_PERCENT"),
kBaseYields.YIELD_PRODUCTION * tPercYields.YIELD_PRODUCTION / 100.0,
kBaseYields.YIELD_GOLD * tPercYields.YIELD_GOLD / 100.0,
kBaseYields.YIELD_FOOD * tPercYields.YIELD_FOOD / 100.0,
kBaseYields.YIELD_SCIENCE * tPercYields.YIELD_SCIENCE / 100.0,
kBaseYields.YIELD_CULTURE * tPercYields.YIELD_CULTURE / 100.0,
kBaseYields.YIELD_FAITH * tPercYields.YIELD_FAITH / 100.0,
true); -- don't store in base yields, we'll need it for other rows
end
-- Yields from Amenities -- Infixo TOTALLY WRONG amenities are applied to all yields, not only Worked Tiles; also must be the LAST calculated entry
--local iYieldPercent = (Round(1 + (kCityData.HappinessNonFoodYieldModifier/100), 2)*.1); -- Infixo Buggy formula
local fYieldPercent:number = kCityData.HappinessNonFoodYieldModifier/100.0;
local sModifierColor:string;
if kCityData.HappinessNonFoodYieldModifier == 0 then sModifierColor = "COLOR_White";
elseif kCityData.HappinessNonFoodYieldModifier > 0 then sModifierColor = "COLOR_Green";
else sModifierColor = "COLOR_Red"; -- <0
end
local lineInstance:table = CreatLineItemInstance( pCityInstance,
Locale.Lookup("LOC_HUD_REPORTS_HEADER_AMENITIES")..string.format(" ["..sModifierColor.."]%+d%%[ENDCOLOR]", kCityData.HappinessNonFoodYieldModifier),
kBaseYields.YIELD_PRODUCTION * fYieldPercent,
kBaseYields.YIELD_GOLD * fYieldPercent,
0,
kBaseYields.YIELD_SCIENCE * fYieldPercent,
kBaseYields.YIELD_CULTURE * fYieldPercent,
kBaseYields.YIELD_FAITH * fYieldPercent,
true); -- don't store in base yields, we'll need it for other rows
-- show base yields in the tooltips
lineInstance.Production:SetToolTipString( kBaseYields.YIELD_PRODUCTION );
lineInstance.Gold:SetToolTipString( kBaseYields.YIELD_GOLD );
lineInstance.Science:SetToolTipString( kBaseYields.YIELD_SCIENCE );
lineInstance.Culture:SetToolTipString( kBaseYields.YIELD_CULTURE );
lineInstance.Faith:SetToolTipString( kBaseYields.YIELD_FAITH );
pCityInstance.LineItemStack:CalculateSize();
pCityInstance.Darken:SetSizeY( pCityInstance.LineItemStack:GetSizeY() + DARKEN_CITY_INCOME_AREA_ADDITIONAL_Y );
pCityInstance.Top:ReprocessAnchoring();
end --BRS if HideCityBuildingsCheckbox:IsSelected
end
local pFooterInstance:table = {};
ContextPtr:BuildInstanceForControl("CityIncomeFooterInstance", pFooterInstance, instance.ContentStack );
pFooterInstance.Gold:SetText( "[Icon_GOLD]"..toPlusMinusString(goldCityTotal) );
pFooterInstance.Faith:SetText( "[Icon_FAITH]"..toPlusMinusString(faithCityTotal) );
pFooterInstance.Science:SetText( "[Icon_SCIENCE]"..toPlusMinusString(scienceCityTotal) );
pFooterInstance.Culture:SetText( "[Icon_CULTURE]"..toPlusMinusString(cultureCityTotal) );
pFooterInstance.Tourism:SetText( "[Icon_TOURISM]"..toPlusMinusString(tourismCityTotal) );
SetGroupCollapsePadding(instance, pFooterInstance.Top:GetSizeY() );
RealizeGroup( instance );
-- ========== Building Expenses ==========
--BRS It displays a long list with multiple same entries - no fun at all
-- Collapse it in the same way as Units, i.e. show Name / Count / Gold
local kBuildingExpenses:table = {};
for cityName,kCityData in pairs(m_kCityData) do
for _,kDistrict in ipairs(kCityData.BuildingsAndDistricts) do
local key = kDistrict.Name;
-- GS change: don't count pillaged districts and must be built
if kDistrict.isPillaged == false and kDistrict.isBuilt == true then
if kBuildingExpenses[key] == nil then kBuildingExpenses[key] = { Count = 0, Maintenance = 0 }; end -- init entry
kBuildingExpenses[key].Count = kBuildingExpenses[key].Count + 1;
kBuildingExpenses[key].Maintenance = kBuildingExpenses[key].Maintenance + kDistrict.Maintenance;
end
-- 2021-05-18 fix for missing Maintenance data
for _,kBuilding in ipairs(kDistrict.Buildings) do
kBuilding.Maintenance = 0;
if GameInfo.Buildings[kBuilding.Type] then
kBuilding.Maintenance = GameInfo.Buildings[kBuilding.Type].Maintenance;
end
--dshowtable(kBuilding); -- debug
local key = kBuilding.Name;
-- GS change: don't count pillaged buildings
if kBuilding.isPillaged == false then
if kBuildingExpenses[key] == nil then kBuildingExpenses[key] = { Count = 0, Maintenance = 0 }; end -- init entry
kBuildingExpenses[key].Count = kBuildingExpenses[key].Count + 1;
kBuildingExpenses[key].Maintenance = kBuildingExpenses[key].Maintenance + kBuilding.Maintenance;
end
end
end
--[[
for _,kBuilding in ipairs(kCityData.Buildings) do
dshowtable(kBuilding); -- debug
local key = kBuilding.Name;
-- GS change: don't count pillaged buildings
if kBuilding.isPillaged == false then
if kBuildingExpenses[key] == nil then kBuildingExpenses[key] = { Count = 0, Maintenance = 0 }; end -- init entry
kBuildingExpenses[key].Count = kBuildingExpenses[key].Count + 1;
kBuildingExpenses[key].Maintenance = kBuildingExpenses[key].Maintenance + kBuilding.Maintenance;
end
end
--]]
end
--BRS sort by name here somehow?
instance = NewCollapsibleGroupInstance();
instance.RowHeaderButton:SetText( Locale.Lookup("LOC_HUD_REPORTS_ROW_BUILDING_EXPENSES") );
instance.RowHeaderLabel:SetHide( true ); --BRS
instance.AmenitiesContainer:SetHide(true);
instance.IndustryContainer:SetHide(true); -- 2021-05-21
instance.MonopolyContainer:SetHide(true); -- 2021-05-21
-- Header
local pHeader:table = {};
ContextPtr:BuildInstanceForControl( "BuildingExpensesHeaderInstance", pHeader, instance.ContentStack ) ;
-- Buildings
local iTotalBuildingMaintenance :number = 0;
local bHideFreeBuildings:boolean = Controls.HideFreeBuildingsCheckbox:IsSelected(); --BRS
for sName, data in spairs( kBuildingExpenses, function( t, a, b ) return Locale.Lookup(a) < Locale.Lookup(b) end ) do -- sorting by name (key)
if data.Maintenance ~= 0 or not bHideFreeBuildings then
local pBuildingInstance:table = {};
ContextPtr:BuildInstanceForControl( "BuildingExpensesEntryInstance", pBuildingInstance, instance.ContentStack );
TruncateStringWithTooltip(pBuildingInstance.BuildingName, 224, Locale.Lookup(sName));
pBuildingInstance.BuildingCount:SetText( Locale.Lookup(data.Count) );
pBuildingInstance.Gold:SetText( data.Maintenance == 0 and "0" or "-"..tostring(data.Maintenance));
iTotalBuildingMaintenance = iTotalBuildingMaintenance - data.Maintenance;
end
end
-- Footer
local pBuildingFooterInstance:table = {};
ContextPtr:BuildInstanceForControl( "GoldFooterInstance", pBuildingFooterInstance, instance.ContentStack ) ;
pBuildingFooterInstance.Gold:SetText("[ICON_Gold]"..tostring(iTotalBuildingMaintenance) );
SetGroupCollapsePadding(instance, pBuildingFooterInstance.Top:GetSizeY() );
RealizeGroup( instance );
-- ========== Unit Expenses ==========
if GameCapabilities.HasCapability("CAPABILITY_REPORTS_UNIT_EXPENSES") then
instance = NewCollapsibleGroupInstance();
instance.RowHeaderButton:SetText( Locale.Lookup("LOC_HUD_REPORTS_ROW_UNIT_EXPENSES") );
instance.RowHeaderLabel:SetHide( true ); --BRS
instance.AmenitiesContainer:SetHide(true);
instance.IndustryContainer:SetHide(true); -- 2021-05-21
instance.MonopolyContainer:SetHide(true); -- 2021-05-21
-- Header
local pHeader:table = {};
ContextPtr:BuildInstanceForControl( "UnitExpensesHeaderInstance", pHeader, instance.ContentStack ) ;
-- Units
local iTotalUnitMaintenance:number = 0;
local bHideFreeUnits:boolean = Controls.HideFreeUnitsCheckbox:IsSelected(); --BRS
-- sort units by name field, which already contains a localized name, and by military formation
for _,kUnitData in spairs( m_kUnitData, function(t,a,b) if t[a].Name == t[b].Name then return t[a].Formation < t[b].Formation else return t[a].Name < t[b].Name end end ) do
if kUnitData.Maintenance ~= 0 or not bHideFreeUnits then
local pUnitInstance:table = {};
ContextPtr:BuildInstanceForControl( "UnitExpensesEntryInstance", pUnitInstance, instance.ContentStack );
if kUnitData.Formation == MilitaryFormationTypes.CORPS_FORMATION then pUnitInstance.UnitName:SetText(kUnitData.Name.." [ICON_Corps]");
elseif kUnitData.Formation == MilitaryFormationTypes.ARMY_FORMATION then pUnitInstance.UnitName:SetText(kUnitData.Name.." [ICON_Army]");
else pUnitInstance.UnitName:SetText(kUnitData.Name); end
pUnitInstance.UnitCount:SetText(kUnitData.Count);
pUnitInstance.Gold:SetText( kUnitData.Maintenance == 0 and "0" or "-"..tostring(kUnitData.Maintenance) );
if bIsGatheringStorm and kUnitData.ResCount > 0 then
pUnitInstance.UnitCount:SetText( kUnitData.Count..string.format(" /-%d%s", kUnitData.ResCount, kUnitData.ResIcon) );
end
iTotalUnitMaintenance = iTotalUnitMaintenance - kUnitData.Maintenance;
end
end
-- Footer
local pUnitFooterInstance:table = {};
ContextPtr:BuildInstanceForControl( "GoldFooterInstance", pUnitFooterInstance, instance.ContentStack ) ;
pUnitFooterInstance.Gold:SetText("[ICON_Gold]"..tostring(iTotalUnitMaintenance) );
SetGroupCollapsePadding(instance, pUnitFooterInstance.Top:GetSizeY() );
RealizeGroup( instance );
end
-- ========== Diplomatic Deals Expenses ==========
if GameCapabilities.HasCapability("CAPABILITY_REPORTS_DIPLOMATIC_DEALS") then
instance = NewCollapsibleGroupInstance();
instance.RowHeaderButton:SetText( Locale.Lookup("LOC_HUD_REPORTS_ROW_DIPLOMATIC_DEALS") );
instance.RowHeaderLabel:SetHide( true ); --BRS
instance.AmenitiesContainer:SetHide(true);
instance.IndustryContainer:SetHide(true); -- 2021-05-21
instance.MonopolyContainer:SetHide(true); -- 2021-05-21
local pHeader:table = {};
ContextPtr:BuildInstanceForControl( "DealHeaderInstance", pHeader, instance.ContentStack ) ;
local iTotalDealGold :number = 0;
for i,kDeal in ipairs(m_kDealData) do
if kDeal.Type == DealItemTypes.GOLD then
local pDealInstance:table = {};
ContextPtr:BuildInstanceForControl( "DealEntryInstance", pDealInstance, instance.ContentStack ) ;
pDealInstance.Civilization:SetText( kDeal.Name );
pDealInstance.Duration:SetText( kDeal.Duration );
if kDeal.IsOutgoing then
pDealInstance.Gold:SetText( "-"..tostring(kDeal.Amount) );
iTotalDealGold = iTotalDealGold - kDeal.Amount;
else
pDealInstance.Gold:SetText( "+"..tostring(kDeal.Amount) );
iTotalDealGold = iTotalDealGold + kDeal.Amount;
end
end
end
local pDealFooterInstance:table = {};
ContextPtr:BuildInstanceForControl( "GoldFooterInstance", pDealFooterInstance, instance.ContentStack ) ;
pDealFooterInstance.Gold:SetText("[ICON_Gold]"..tostring(iTotalDealGold) );
SetGroupCollapsePadding(instance, pDealFooterInstance.Top:GetSizeY() );
RealizeGroup( instance );
end
-- ========== TOTALS ==========
Controls.Stack:CalculateSize();
Controls.Scroll:CalculateSize();
-- Totals at the bottom [Definitive values]
local localPlayer = Players[Game.GetLocalPlayer()];
--Gold
local playerTreasury:table = localPlayer:GetTreasury();
Controls.GoldIncome:SetText( toPlusMinusNoneString( playerTreasury:GetGoldYield() ));
Controls.GoldExpense:SetText( toPlusMinusNoneString( -playerTreasury:GetTotalMaintenance() )); -- Flip that value!
Controls.GoldNet:SetText( toPlusMinusNoneString( playerTreasury:GetGoldYield() - playerTreasury:GetTotalMaintenance() ));
Controls.GoldBalance:SetText( m_kCityTotalData.Treasury[YieldTypes.GOLD] );
--Faith
local playerReligion:table = localPlayer:GetReligion();
Controls.FaithIncome:SetText( toPlusMinusNoneString(playerReligion:GetFaithYield()));
Controls.FaithNet:SetText( toPlusMinusNoneString(playerReligion:GetFaithYield()));
Controls.FaithBalance:SetText( m_kCityTotalData.Treasury[YieldTypes.FAITH] );
--Science
local playerTechnology:table = localPlayer:GetTechs();
Controls.ScienceIncome:SetText( toPlusMinusNoneString(playerTechnology:GetScienceYield()));
Controls.ScienceBalance:SetText( m_kCityTotalData.Treasury[YieldTypes.SCIENCE] );
--Culture
local playerCulture:table = localPlayer:GetCulture();
Controls.CultureIncome:SetText(toPlusMinusNoneString(playerCulture:GetCultureYield()));
Controls.CultureBalance:SetText(m_kCityTotalData.Treasury[YieldTypes.CULTURE] );
--Tourism. We don't talk about this one much.
Controls.TourismIncome:SetText( toPlusMinusNoneString( m_kCityTotalData.Income["TOURISM"] ));
Controls.TourismBalance:SetText( m_kCityTotalData.Treasury["TOURISM"] );
Controls.CollapseAll:SetHide( false );
Controls.BottomYieldTotals:SetHide( false ); -- ViewYieldsPage
Controls.BottomYieldTotals:SetSizeY( SIZE_HEIGHT_BOTTOM_YIELDS );
Controls.BottomResourceTotals:SetHide( true );
Controls.BottomPoliciesFilters:SetHide( true );
Controls.BottomMinorsFilters:SetHide( true );
Controls.Scroll:SetSizeY( Controls.Main:GetSizeY() - (Controls.BottomYieldTotals:GetSizeY() + SIZE_HEIGHT_PADDING_BOTTOM_ADJUST ) );
-- Remember this tab when report is next opened: ARISTOS
m_kCurrentTab = 1;
end
-- ===========================================================================
-- RESOURCES PAGE
-- ===========================================================================
function ViewResourcesPage()
ResetTabForNewPageContent();
local strategicResources:string = "";
local luxuryResources :string = "";
local kBonuses :table = {};
local kLuxuries :table = {};
local kStrategics :table = {};
local localPlayerID = Game.GetLocalPlayer();
local localPlayer = Players[localPlayerID];
-- 2021-05-12 Monopolies Mode
-- find out if Mercantilism is unlocked
local bMercantailismUnlocked:boolean = false;
if GameInfo.Civics.CIVIC_MERCANTILISM then
bMercantailismUnlocked = localPlayer:GetCulture():HasCivic(GameInfo.Civics.CIVIC_MERCANTILISM.Index);
end
local function FormatStrategicTotal(iTot:number)
if iTot < 0 then return "[COLOR_Red]"..tostring(iTot).."[ENDCOLOR]";
else return "+"..tostring(iTot); end
end
--for eResourceType,kSingleResourceData in pairs(m_kResourceData) do
for eResourceType,kSingleResourceData in spairs(m_kResourceData, function(t,a,b) return Locale.Lookup(GameInfo.Resources[a].Name) < Locale.Lookup(GameInfo.Resources[b].Name) end) do
local kResource :table = GameInfo.Resources[eResourceType];
--!!ARISTOS: Only display list of selected resource types, according to checkboxes
if (kSingleResourceData.IsStrategic and Controls.StrategicCheckbox:IsSelected()) or
(kSingleResourceData.IsLuxury and Controls.LuxuryCheckbox:IsSelected()) or
(kSingleResourceData.IsBonus and Controls.BonusCheckbox:IsSelected()) then
local instance:table = NewCollapsibleGroupInstance();
instance.RowHeaderButton:SetText( kSingleResourceData.Icon..Locale.Lookup( kResource.Name ) );
instance.RowHeaderLabel:SetHide( false ); --BRS
if kSingleResourceData.Total < 0 then
instance.RowHeaderLabel:SetText( Locale.Lookup("LOC_HUD_REPORTS_TOTALS").." [COLOR_Red]"..tostring(kSingleResourceData.Total).."[ENDCOLOR]" );
else
instance.RowHeaderLabel:SetText( Locale.Lookup("LOC_HUD_REPORTS_TOTALS").." "..tostring(kSingleResourceData.Total) );
end
if bIsGatheringStorm and kSingleResourceData.IsStrategic then
instance.RowHeaderLabel:SetText( Locale.Lookup("LOC_HUD_REPORTS_TOTALS")..string.format(" %d/%d ", kSingleResourceData.Stockpile, kSingleResourceData.Maximum)..FormatStrategicTotal(kSingleResourceData.Total) );
end
local pHeaderInstance:table = {};
ContextPtr:BuildInstanceForControl( "ResourcesHeaderInstance", pHeaderInstance, instance.ContentStack ) ;
local kResourceEntries:table = kSingleResourceData.EntryList;
for i,kEntry in ipairs(kResourceEntries) do
local pEntryInstance:table = {};
ContextPtr:BuildInstanceForControl( "ResourcesEntryInstance", pEntryInstance, instance.ContentStack ) ;
pEntryInstance.CityName:SetText( Locale.Lookup(kEntry.EntryText) );
pEntryInstance.Control:SetText( Locale.Lookup(kEntry.ControlText) );
pEntryInstance.Amount:SetText( (kEntry.Amount<=0) and tostring(kEntry.Amount) or "+"..tostring(kEntry.Amount) );
end
--local pFooterInstance:table = {};
--ContextPtr:BuildInstanceForControl( "ResourcesFooterInstance", pFooterInstance, instance.ContentStack ) ;
--pFooterInstance.Amount:SetText( tostring(kSingleResourceData.Total) );
-- Show how many of this resource are being allocated to what cities
local citiesProvidedTo: table = localPlayer:GetResources():GetResourceAllocationCities(GameInfo.Resources[kResource.ResourceType].Index);
local numCitiesProvidingTo: number = table.count(citiesProvidedTo);
if (numCitiesProvidingTo > 0) then
--pFooterInstance.AmenitiesContainer:SetHide(false);
instance.AmenitiesContainer:SetHide(false); ---BRS
--pFooterInstance.Amenities:SetText("[ICON_Amenities][ICON_GoingTo]"..numCitiesProvidingTo.." "..Locale.Lookup("LOC_PEDIA_CONCEPTS_PAGEGROUP_CITIES_NAME"));
instance.Amenities:SetText("[ICON_Amenities][ICON_GoingTo]"..Locale.Lookup("LOC_HUD_REPORTS_CITY_AMENITIES", numCitiesProvidingTo));
local amenitiesTooltip: string = "";
local playerCities = localPlayer:GetCities();
for i,city in ipairs(citiesProvidedTo) do
local cityName = Locale.Lookup(playerCities:FindID(city.CityID):GetName());
if i ~=1 then
amenitiesTooltip = amenitiesTooltip.. "[NEWLINE]";
end
amenitiesTooltip = amenitiesTooltip.. city.AllocationAmount.." [ICON_".. kResource.ResourceType.."] [Icon_GoingTo] " ..cityName;
end
--pFooterInstance.Amenities:SetToolTipString(amenitiesTooltip);
instance.Amenities:SetToolTipString(amenitiesTooltip);
else
--pFooterInstance.AmenitiesContainer:SetHide(true);
instance.AmenitiesContainer:SetHide(true);
end
-- 2021-05-12 Monopolies Mode
if bIsMonopolies and kSingleResourceData.IsLuxury and GameInfo.ResourceIndustries[kResource.ResourceType] ~= nil then -- also check if there is an industry around it!
local pGameEconomic:table = Game.GetEconomicManager();
local iControlled:number = pGameEconomic:GetNumControlledResources(localPlayerID, eResourceType);
local sText:string, sTT:string = "", "";
local sTTHead = "[ICON_".. kResource.ResourceType.."]"..LL(kResource.Name);
-- find industry effect and type - match [ICON_xxx]
local sEffectI:string = LL(GameInfo.ResourceIndustries[kResource.ResourceType].ResourceEffectTExt);
local sIndustryType:string = string.match(sEffectI, "%[ICON_%a+%]");
-- find corporation effect and type - match [ICON_xxx]
local sEffectC:string = LL(GameInfo.ResourceCorporations[kResource.ResourceType].ResourceEffectTExt);
local sCorpoType:string = string.match(sEffectC, "%[ICON_%a+%]");
-- logic goes top-down, i.e. from corporation to industry
if pGameEconomic:HasCorporationOf(localPlayerID, eResourceType) then
-- corpo: YES
sText = string.format("%d %s [ICON_GreatWork_Product][ICON_GreatWork_Product] %s", iControlled, sCorpoType, LL("LOC_IMPROVEMENT_CORPORATION_NAME"));
sTT = sTTHead..sEffectC;
else
-- corpo: NO, check Industry
if pGameEconomic:HasIndustryOf(localPlayerID, eResourceType) then
sText = string.format("%d %s [ICON_GreatWork_Product] %s", iControlled, sIndustryType, LL("LOC_IMPROVEMENT_INDUSTRY_NAME"));
else
sText = string.format("%d %s [ICON_Not]", iControlled, sIndustryType);
end
sTT = sTTHead..sEffectI;
end
-- if we can have an industry - add the mark
if pGameEconomic:CanHaveIndustry(localPlayerID, eResourceType) then
sText = sText.." [ICON_New] "..LL("LOC_IMPROVEMENT_INDUSTRY_NAME");
sTT = sTT.."[NEWLINE]"..LL("LOC_NOTIFICATION_INDUSTRY_OPPORTUNITY_SUMMARY", iControlled, "[ICON_".. kResource.ResourceType.."]", LL(kResource.Name)); -- {1_num} {2_ResourceIcon} {3_Resource}
end
-- if we can have a corpo - add the mark
if pGameEconomic:CanHaveCorporation(localPlayerID, eResourceType) then
sText = sText.." [ICON_New] "..LL("LOC_IMPROVEMENT_CORPORATION_NAME");
sTT = sTT.."[NEWLINE]"..LL("LOC_NOTIFICATION_CORPORATION_OPPORTUNITY_SUMMARY", iControlled, "[ICON_".. kResource.ResourceType.."]", LL(kResource.Name)); -- {1_num} {2_ResourceIcon} {3_Resource}
sTT = sTT.."[NEWLINE][ICON_GoingTo]"..LL("LOC_IMPROVEMENT_CORPORATION_NAME")..sEffectC;
end
-- show info
instance.Industry:SetText(sText);
instance.Industry:SetToolTipString(sTT);
instance.IndustryContainer:SetHide(false);
else
instance.IndustryContainer:SetHide(true);
end
-- 2021-05-12 Monopolies Mode
if bIsMonopolies and kSingleResourceData.IsLuxury and GameInfo.ResourceIndustries[kResource.ResourceType] ~= nil and bMercantailismUnlocked then
local pGameEconomic:table = Game.GetEconomicManager();
local iControlled:number = pGameEconomic:GetNumControlledResources(localPlayerID, eResourceType);
local kMapResources:table = pGameEconomic:GetMapResources();
local iTotal:number = kMapResources[eResourceType];
local iMonopolyID:number = pGameEconomic:GetResourceMonopolyPlayer(eResourceType);
local sText:string = string.format("%d/%d %d%% %s", iControlled, iTotal, 100*iControlled/iTotal, (iMonopolyID == localPlayerID and LL("LOC_RESREPORT_MONOPOLY_NAME") or LL("LOC_RESREPORT_CONTROL")));
if 100*(iControlled+1)/iTotal > 60 then sText = sText.." [ICON_New]"; end
if iMonopolyID == localPlayerID then sText = "[COLOR_Green]"..sText.."[ENDCOLOR]"; end
instance.Monopoly:SetText(sText);
instance.MonopolyContainer:SetHide(false);
else
instance.MonopolyContainer:SetHide(true);
end
--SetGroupCollapsePadding(instance, pFooterInstance.Top:GetSizeY() ); --BRS moved into if
SetGroupCollapsePadding(instance, 0); --BRS no footer
RealizeGroup( instance ); --BRS moved into if
end -- ARISTOS checkboxes
local tResBottomData:table = {
Text = kSingleResourceData.Icon.. tostring(kSingleResourceData.Total),
ToolTip = kSingleResourceData.Icon..Locale.Lookup( kResource.Name ).." "..tostring(kSingleResourceData.Total),
};
if bIsGatheringStorm and kSingleResourceData.IsStrategic then
tResBottomData.Text = string.format("%s%d/%d ", kSingleResourceData.Icon, kSingleResourceData.Stockpile, kSingleResourceData.Maximum)..FormatStrategicTotal(kSingleResourceData.Total);
tResBottomData.ToolTip = string.format("%s %s %d/%d ", kSingleResourceData.Icon, Locale.Lookup( kResource.Name ), kSingleResourceData.Stockpile, kSingleResourceData.Maximum)..FormatStrategicTotal(kSingleResourceData.Total);
end
if kSingleResourceData.IsStrategic then table.insert(kStrategics, tResBottomData);
elseif kSingleResourceData.IsLuxury then table.insert(kLuxuries, tResBottomData);
else table.insert(kBonuses, tResBottomData); end
--SetGroupCollapsePadding(instance, pFooterInstance.Top:GetSizeY() ); --BRS moved into if
--RealizeGroup( instance ); --BRS moved into if
end
local function ShowResources(kResIM:table, kResources:table)
kResIM:ResetInstances();
for i,v in ipairs(kResources) do
local resourceInstance:table = kResIM:GetInstance();
resourceInstance.Info:SetText( v.Text );
resourceInstance.Info:SetToolTipString( v.ToolTip );
end
end
ShowResources(m_strategicResourcesIM, kStrategics);
Controls.StrategicResources:CalculateSize();
Controls.StrategicGrid:ReprocessAnchoring();
ShowResources(m_bonusResourcesIM, kBonuses);
Controls.BonusResources:CalculateSize();
Controls.BonusGrid:ReprocessAnchoring();
ShowResources(m_luxuryResourcesIM, kLuxuries);
Controls.LuxuryResources:CalculateSize();
Controls.LuxuryResources:ReprocessAnchoring();
--Controls.LuxuryGrid:ReprocessAnchoring();
Controls.Stack:CalculateSize();
Controls.Scroll:CalculateSize();
Controls.CollapseAll:SetHide( false );
Controls.BottomYieldTotals:SetHide( true );
Controls.BottomResourceTotals:SetHide( false ); -- ViewResourcesPage
Controls.BottomPoliciesFilters:SetHide( true );
Controls.BottomMinorsFilters:SetHide( true );
Controls.Scroll:SetSizeY( Controls.Main:GetSizeY() - (Controls.BottomResourceTotals:GetSizeY() + SIZE_HEIGHT_PADDING_BOTTOM_ADJUST ) );
-- Remember this tab when report is next opened: ARISTOS
m_kCurrentTab = 2;
end
-- ===========================================================================
-- GOSSIP PAGE
-- ===========================================================================
-- Tab Callback
function ViewGossipPage()
ResetTabForNewPageContent();
local playerID:number = Game.GetLocalPlayer();
if playerID == -1 then
--Observer. No report.
return;
end
--Get our Diplomacy
local pLocalPlayerDiplomacy:table = Players[playerID]:GetDiplomacy();
if pLocalPlayerDiplomacy == nil then
--This is a significant error
UI.DataError("Diplomacy is nil! Cannot display Gossip Report");
return;
end
--We use simple instances to mask generic content. So we need to ensure there are no
--leftover children from the last instance.
local instance:table = m_simpleIM:GetInstance();
instance.Top:DestroyAllChildren();
local uiFilterInstance:table = {};
ContextPtr:BuildInstanceForControl("GossipFilterInstance", uiFilterInstance, instance.Top);
--Generate our filters for each group
for i, type in pairs(GOSSIP_GROUP_TYPES) do
local uiFilter:table = {};
uiFilterInstance.GroupFilter:BuildEntry("InstanceOne", uiFilter);
uiFilter.Button:SetText(Locale.Lookup("LOC_HUD_REPORTS_FILTER_" .. type));
uiFilter.Button:SetVoid1(i);
uiFilter.Button:SetSizeX(252);
end
uiFilterInstance.GroupFilter:RegisterSelectionCallback(function(i:number)
uiFilterInstance.GroupFilter:GetButton():SetText(Locale.Lookup("LOC_HUD_REPORTS_FILTER_" .. GOSSIP_GROUP_TYPES[i]));
m_groupFilter = i;
FilterGossip();
end);
uiFilterInstance.GroupFilter:GetButton():SetText(Locale.Lookup("LOC_HUD_REPORTS_FILTER_ALL"));
local pHeaderInstance:table = {}
ContextPtr:BuildInstanceForControl( "GossipHeaderInstance", pHeaderInstance, instance.Top );
local kGossipLog:table = {};
--Make our 'All' Filter for players
local uiAllFilter:table = {};
uiFilterInstance.PlayerFilter:BuildEntry("InstanceOne", uiAllFilter);
uiAllFilter.LeaderIcon.Portrait:SetIcon("ICON_LEADER_ALL");
uiAllFilter.LeaderIcon.Portrait:SetHide(false);
uiAllFilter.LeaderIcon.TeamRibbon:SetHide(true);
uiAllFilter.Button:SetText(Locale.Lookup("LOC_HUD_REPORTS_PLAYER_FILTER_ALL"));
uiAllFilter.Button:SetVoid1(-1);
uiAllFilter.Button:SetSizeX(252);
--Populate with all of our Gossip and build Player Filter
for targetID, kPlayer in pairs(Players) do
--If we are not ourselves, are a major civ, and we have met these people
if targetID ~= playerID and kPlayer:IsMajor() and pLocalPlayerDiplomacy:HasMet(targetID) then
--Append their gossip
local bHasGossip:boolean = false;
local kAppendTable:table = Game.GetGossipManager():GetRecentVisibleGossipStrings(0, playerID, targetID);
for _, entry in pairs(kAppendTable) do
table.insert(kGossipLog, entry);
bHasGossip = true;
end
--If we had gossip, add them as a filter
if bHasGossip then
local uiFilter:table = {};
uiFilterInstance.PlayerFilter:BuildEntry("InstanceOne", uiFilter);
local leaderName:string = PlayerConfigurations[targetID]:GetLeaderTypeName();
local iconName:string = "ICON_" .. leaderName;
--Build and update
local filterLeaderIcon:table = LeaderIcon:AttachInstance(uiFilter.LeaderIcon);
filterLeaderIcon:UpdateIcon(iconName, targetID, true);
uiFilter.Button:SetText(Locale.Lookup(PlayerConfigurations[targetID]:GetLeaderName()));
uiFilter.Button:SetVoid1(targetID);
uiFilter.Button:SetSizeX(252);
end
end
end
uiFilterInstance.PlayerFilter:RegisterSelectionCallback(function(i:number)
if i == -1 then
uiFilterInstance.LeaderIcon.Portrait:SetIcon("ICON_LEADER_ALL");
uiFilterInstance.LeaderIcon.Portrait:SetHide(false);
uiFilterInstance.LeaderIcon.TeamRibbon:SetHide(true);
uiFilterInstance.LeaderIcon.Relationship:SetHide(true);
uiFilterInstance.PlayerFilter:GetButton():SetText(Locale.Lookup("LOC_HUD_REPORTS_PLAYER_FILTER_ALL"));
else
local leaderName:string = PlayerConfigurations[i]:GetLeaderTypeName();
local iconName:string = "ICON_" .. leaderName;
--Build and update
local filterLeaderIcon:table = LeaderIcon:AttachInstance(uiFilterInstance.LeaderIcon);
filterLeaderIcon:UpdateIcon(iconName, i, true);
uiFilterInstance.PlayerFilter:GetButton():SetText(Locale.Lookup(PlayerConfigurations[i]:GetLeaderName()));
end
m_leaderFilter = i;
FilterGossip();
end);
uiFilterInstance.LeaderIcon.Portrait:SetIcon("ICON_LEADER_ALL");
uiFilterInstance.LeaderIcon.Portrait:SetHide(false);
uiFilterInstance.LeaderIcon.TeamRibbon:SetHide(true);
uiFilterInstance.LeaderIcon.Relationship:SetHide(true);
uiFilterInstance.PlayerFilter:GetButton():SetText(Locale.Lookup("LOC_HUD_REPORTS_PLAYER_FILTER_ALL"));
table.sort(kGossipLog, function(a, b) return a[2] > b[2]; end);
for _, kGossipEntry in pairs(kGossipLog) do
local leaderName:string = PlayerConfigurations[kGossipEntry[4]]:GetLeaderTypeName();
local iconName:string = "ICON_" .. leaderName;
local pGossipInstance:table = {}
ContextPtr:BuildInstanceForControl( "GossipEntryInstance", pGossipInstance, instance.Top ) ;
local kGossipData:table = GameInfo.Gossips[kGossipEntry[3]];
--Build and update
local gossipLeaderIcon:table = LeaderIcon:AttachInstance(pGossipInstance.Leader);
gossipLeaderIcon:UpdateIcon(iconName, kGossipEntry[4], true);
pGossipInstance.Date:SetText(kGossipEntry[2]);
pGossipInstance.Icon:SetIcon("ICON_GOSSIP_" .. kGossipData.GroupType);
pGossipInstance.Description:SetText(kGossipEntry[1]);
--Build our references
table.insert(m_kGossipInstances, {instance = pGossipInstance, leaderID = kGossipEntry[4], gossipType = kGossipData.GroupType});
end
--Refresh our sizes
uiFilterInstance.GroupFilter:CalculateInternals();
uiFilterInstance.PlayerFilter:CalculateInternals();
Controls.Stack:CalculateSize();
Controls.Scroll:CalculateSize();
Controls.CollapseAll:SetHide(true);
Controls.BottomYieldTotals:SetHide( true );
Controls.BottomResourceTotals:SetHide( true );
Controls.BottomPoliciesFilters:SetHide( true );
Controls.BottomMinorsFilters:SetHide( true );
Controls.Scroll:SetSizeY( Controls.Main:GetSizeY() - SIZE_HEIGHT_PADDING_BOTTOM_ADJUST );
-- Remember this tab when report is next opened: ARISTOS
m_kCurrentTab = 4;
end
-- Filter Callbacks
function FilterGossip()
local gossipGroupType:string = GOSSIP_GROUP_TYPES[m_groupFilter];
for _, entry in pairs(m_kGossipInstances) do
local bShouldHide:boolean = false;
--Leader matches, or all?
if m_leaderFilter ~= -1 and entry.leaderID ~= m_leaderFilter then
bShouldHide = true;
end
--Group type, or all?
if m_groupFilter ~= 1 and entry.gossipType ~= gossipGroupType then
bShouldHide = true;
end
entry.instance.Top:SetHide(bShouldHide);
end
end
-- ===========================================================================
-- CITY STATUS PAGE
-- ===========================================================================
function GetFontIconForDistrict(sDistrictType:string)
-- exceptions first
--if sDistrictType == "DISTRICT_HOLY_SITE" then return "[ICON_DISTRICT_HOLYSITE]"; end
--if sDistrictType == "DISTRICT_ENTERTAINMENT_COMPLEX" then return "[ICON_DISTRICT_ENTERTAINMENT]"; end
if sDistrictType == "DISTRICT_WATER_ENTERTAINMENT_COMPLEX" then return "[ICON_DISTRICT_ENTERTAINMENT]"; end -- no need to check for mutuals with that
--if sDistrictType == "DISTRICT_AERODROME" then return "[ICON_DISTRICT_WONDER]"; end -- no unique font icon for an aerodrome
--if sDistrictType == "DISTRICT_CANAL" then return "[ICON_DISTRICT_WONDER]"; end -- no unique font icon for a canal
--if sDistrictType == "DISTRICT_DAM" then return "[ICON_DISTRICT_WONDER]"; end -- no unique font icon for a dam
if sDistrictType == "DISTRICT_GOVERNMENT" then return "[ICON_DISTRICT_GOVPLAZA]"; end
-- default icon last
return "[ICON_"..sDistrictType.."]";
end
local tDistrictsOrder:table = {
-- Ancient Era
--"DISTRICT_GOVERNMENT", -- to save space, will be treated separately
"DISTRICT_HOLY_SITE", -- icon is DISTRICT_HOLYSITE
"DISTRICT_CAMPUS",
"DISTRICT_ENCAMPMENT",
-- Classical Era
"DISTRICT_THEATER",
"DISTRICT_COMMERCIAL_HUB",
"DISTRICT_HARBOR",
"DISTRICT_ENTERTAINMENT_COMPLEX", -- with DISTRICT_WATER_ENTERTAINMENT_COMPLEX, icon is DISTRICT_ENTERTAINMENT
-- Medieval Era
"DISTRICT_INDUSTRIAL_ZONE",
-- others
"DISTRICT_AQUEDUCT",
"DISTRICT_NEIGHBORHOOD",
"DISTRICT_SPACEPORT",
"DISTRICT_AERODROME", -- there is no font icon, so we'll use ICON_DISTRICT_WONDER
}
--for k,v in pairs(tDistrictsOrder) do print("tDistrictsOrder",k,v) end;
function HasCityDistrict(kCityData:table, sDistrictType:string)
for _,district in ipairs(kCityData.BuildingsAndDistricts) do
if district.isBuilt then
local sDistrictInCity:string = district.Type;
--if district.DistrictType == sDistrictType then return true; end
if GameInfo.DistrictReplaces[ sDistrictInCity ] then sDistrictInCity = GameInfo.DistrictReplaces[ sDistrictInCity ].ReplacesDistrictType; end
if sDistrictInCity == sDistrictType then return true; end
-- check mutually exclusive
for row in GameInfo.MutuallyExclusiveDistricts() do
if sDistrictInCity == row.District and row.MutuallyExclusiveDistrict == sDistrictType then return true; end
end
end
end
return false;
end
-- districts
function GetDistrictsForCity(kCityData:table)
local sDistricts:string = "";
for _,districtType in ipairs(tDistrictsOrder) do
local sDistrictIcon:string = "[ICON_Bullet]"; -- default empty
if HasCityDistrict(kCityData, districtType) then
sDistrictIcon = GetFontIconForDistrict(districtType);
end
sDistricts = sDistricts..sDistrictIcon;
end
return sDistricts;
end
-- helper from CityPanel.lua
function GetPercentGrowthColor( percent:number )
if percent == 0 then return "Error"; end
if percent <= 0.25 then return "WarningMajor"; end
if percent <= 0.5 then return "WarningMinor"; end
return "StatNormalCSGlow";
end
function city_fields( kCityData, pCityInstance )
local function ColorRed(text) return("[COLOR_Red]"..tostring(text).."[ENDCOLOR]"); end -- Infixo: helper
local function ColorGreen(text) return("[COLOR_Green]"..tostring(text).."[ENDCOLOR]"); end -- Infixo: helper
-- Infixo: status will show various icons
--pCityInstance.Status:SetText( kCityData.IsUnderSiege and Locale.Lookup("LOC_HUD_REPORTS_STATUS_UNDER_SEIGE") or Locale.Lookup("LOC_HUD_REPORTS_STATUS_NORMAL") );
local sStatusText:string = "";
local tStatusToolTip:table = {};
if kCityData.Population > kCityData.Housing then
sStatusText = sStatusText.."[ICON_HousingInsufficient]"; table.insert(tStatusToolTip, ColorRed(LL("LOC_CITY_BANNER_HOUSING_INSUFFICIENT")));
end -- insufficient housing
if kCityData.AmenitiesNum < kCityData.AmenitiesRequiredNum then
sStatusText = sStatusText.."[ICON_AmenitiesInsufficient]"; table.insert(tStatusToolTip, ColorRed(LL("LOC_CITY_BANNER_AMENITIES_INSUFFICIENT")));
end -- insufficient amenities
if kCityData.IsUnderSiege then
sStatusText = sStatusText.."[ICON_UnderSiege]"; table.insert(tStatusToolTip, ColorRed(LL("LOC_HUD_REPORTS_STATUS_UNDER_SEIGE")));
end -- under siege
if kCityData.Occupied then
sStatusText = sStatusText.."[ICON_Occupied]"; table.insert(tStatusToolTip, ColorRed(LL("LOC_HUD_CITY_GROWTH_OCCUPIED")));
end -- occupied
if HasCityDistrict(kCityData, "DISTRICT_GOVERNMENT") then
sStatusText = sStatusText.."[ICON_DISTRICT_GOVPLAZA]"; table.insert(tStatusToolTip, "[COLOR:111,15,143,255]"..Locale.Lookup("LOC_DISTRICT_GOVERNMENT_NAME")..ENDCOLOR); -- ICON_DISTRICT_GOVERNMENT
end
local bHasWonder:boolean = false;
for _,wonder in ipairs(kCityData.Wonders) do
bHasWonder = true;
table.insert(tStatusToolTip, wonder.Name);
end
if bHasWonder then sStatusText = sStatusText.."[ICON_DISTRICT_WONDER]"; end
pCityInstance.Status:SetText( sStatusText );
pCityInstance.Status:SetToolTipString( table.concat(tStatusToolTip, "[NEWLINE]") );
-- Religions
local eCityReligion:number = kCityData.City:GetReligion():GetMajorityReligion();
local eCityPantheon:number = kCityData.City:GetReligion():GetActivePantheon();
local function ShowReligionTooltip(sHeader:string)
local tTT:table = {};
table.insert(tTT, "[ICON_Religion]"..sHeader);
table.sort(kCityData.Religions, function(a,b) return a.Followers > b.Followers; end);
for _,rel in ipairs(kCityData.Religions) do
--print(rel.ID, rel.ReligionType, rel.Followers);
--table.insert(tTT, string.format("%s: %d", Game.GetReligion():GetName( math.max(0, rel.ID) ), rel.Followers)); -- LOC_UI_RELIGION_NUM_FOLLOWERS_TT
table.insert(tTT, Locale.Lookup("LOC_UI_RELIGION_NUM_FOLLOWERS_TT", Game.GetReligion():GetName( math.max(0, rel.ID) ), rel.Followers));
end
pCityInstance.ReligionIcon:SetToolTipString(table.concat(tTT, "[NEWLINE]"));
end
if eCityReligion > 0 then
local iconName : string = "ICON_" .. GameInfo.Religions[eCityReligion].ReligionType;
local majorityReligionColor : number = UI.GetColorValue(GameInfo.Religions[eCityReligion].Color);
if (majorityReligionColor ~= nil) then
pCityInstance.ReligionIcon:SetColor(majorityReligionColor);
end
local textureOffsetX, textureOffsetY, textureSheet = IconManager:FindIconAtlas(iconName,22);
if (textureOffsetX ~= nil) then
pCityInstance.ReligionIcon:SetTexture( textureOffsetX, textureOffsetY, textureSheet );
end
pCityInstance.ReligionIcon:SetHide(false);
--pCityInstance.ReligionIcon:SetToolTipString(Game.GetReligion():GetName(eCityReligion));
ShowReligionTooltip( Game.GetReligion():GetName(eCityReligion) );
elseif eCityPantheon >= 0 then
local iconName : string = "ICON_" .. GameInfo.Religions[0].ReligionType;
local majorityReligionColor : number = UI.GetColorValue(GameInfo.Religions.RELIGION_PANTHEON.Color);
if (majorityReligionColor ~= nil) then
pCityInstance.ReligionIcon:SetColor(majorityReligionColor);
end
local textureOffsetX, textureOffsetY, textureSheet = IconManager:FindIconAtlas(iconName,22);
if (textureOffsetX ~= nil) then
pCityInstance.ReligionIcon:SetTexture( textureOffsetX, textureOffsetY, textureSheet );
end
pCityInstance.ReligionIcon:SetHide(false);
--pCityInstance.ReligionIcon:SetToolTipString(Locale.Lookup("LOC_HUD_CITY_PANTHEON_TT", GameInfo.Beliefs[eCityPantheon].Name));
ShowReligionTooltip( Locale.Lookup("LOC_HUD_CITY_PANTHEON_TT", GameInfo.Beliefs[eCityPantheon].Name) );
else
pCityInstance.ReligionIcon:SetHide(true);
pCityInstance.ReligionIcon:SetToolTipString("");
end
-- CityName
--pCityInstance.CityName:SetText( Locale.Lookup( kCityData.CityName ) );
TruncateStringWithTooltip(pCityInstance.CityName, 178, (kCityData.IsCapital and "[ICON_Capital]" or "")..Locale.Lookup(kCityData.CityName)..((kCityData.DistrictsNum < kCityData.DistrictsPossibleNum) and "[COLOR_Green]![ENDCOLOR]" or ""));
-- Population and Housing
-- a bit more complicated due to real housing from improvements - fix applied earlier
--local fRealHousing:number = kCityData.Housing - kCityData.HousingFromImprovements + kCityData.RealHousingFromImprovements;
local sPopulationText:string = "[COLOR_White]"..tostring(kCityData.Population).."[ENDCOLOR] / ";
if kCityData.Population >= kCityData.Housing then sPopulationText = sPopulationText..ColorRed(kCityData.Housing);
else sPopulationText = sPopulationText..tostring(kCityData.Housing); end
-- check for Sewer
pCityInstance.Population:SetToolTipString("");
if GameInfo.Buildings["BUILDING_SEWER"] ~= nil and kCityData.City:GetBuildings():HasBuilding( GameInfo.Buildings["BUILDING_SEWER"].Index ) then
sPopulationText = sPopulationText..ColorGreen("!");
pCityInstance.Population:SetToolTipString( Locale.Lookup("LOC_BUILDING_SEWER_NAME") );
end
pCityInstance.Population:SetText(sPopulationText);
--[[ debug
local tTT:table = {};
table.insert(tTT, "Housing : "..kCityData.Housing);
table.insert(tTT, "FromImpr: "..kCityData.HousingFromImprovements);
table.insert(tTT, "RealImpr: "..kCityData.RealHousingFromImprovements);
table.insert(tTT, "RealHous: "..kCityData.Housing);
pCityInstance.Population:SetToolTipString(table.concat(tTT, "[NEWLINE]"));
--]]
-- GrowthRateStatus
local sGRStatus:string = "0%";
local sGRStatusTT:string = "LOC_HUD_REPORTS_STATUS_NORMAL";
local sGRColor:string = "";
if kCityData.HousingMultiplier == 0 or kCityData.Occupied then sGRStatus = "LOC_HUD_REPORTS_STATUS_HALTED"; sGRColor = "[COLOR:200,62,52,255]"; sGRStatusTT = sGRStatus; -- Error
elseif kCityData.HousingMultiplier <= 0.25 then sGRStatus = tostring(100 * kCityData.HousingMultiplier - 100).."%"; sGRColor = "[COLOR:200,146,52,255]"; sGRStatusTT = "LOC_HUD_REPORTS_STATUS_SLOWED";
elseif kCityData.HousingMultiplier <= 0.5 then sGRStatus = tostring(100 * kCityData.HousingMultiplier - 100).."%"; sGRColor = "[COLOR:206,199,91,255]"; sGRStatusTT = "LOC_HUD_REPORTS_STATUS_SLOWED";
elseif kCityData.HappinessGrowthModifier > 0 then sGRStatus = "+"..tostring(kCityData.HappinessGrowthModifier).."%"; sGRColor = "[COLOR_White]"; sGRStatusTT = "LOC_HUD_REPORTS_STATUS_ACCELERATED"; end -- GS addition
pCityInstance.GrowthRateStatus:SetText( sGRColor..Locale.Lookup(sGRStatus)..(sGRColor~="" and "[ENDCOLOR]" or "") );
pCityInstance.GrowthRateStatus:SetToolTipString(Locale.Lookup(sGRStatusTT));
--if sGRColor ~= "" then pCityInstance.GrowthRateStatus:SetColorByName( sGRColor ); end
-- Amenities
if kCityData.AmenitiesNum < kCityData.AmenitiesRequiredNum then
pCityInstance.Amenities:SetText( ColorRed(kCityData.AmenitiesNum).." / "..tostring(kCityData.AmenitiesRequiredNum) );
else
pCityInstance.Amenities:SetText( tostring(kCityData.AmenitiesNum).." / "..tostring(kCityData.AmenitiesRequiredNum) );
end
-- Happiness
local happinessFormat:string = "%s";
local happinessText:string = Locale.Lookup( GameInfo.Happinesses[kCityData.Happiness].Name );
local happinessToolTip:string = happinessText;
if kCityData.HappinessGrowthModifier < 0 then happinessFormat = "[COLOR:255,40,50,160]%s[ENDCOLOR]"; end -- StatBadCS Color0="255,40,50,240" StatNormalCS Color0="200,200,200,240"
if kCityData.HappinessGrowthModifier > 0 then happinessFormat = "[COLOR:80,255,90,160]%s[ENDCOLOR]"; end -- StatGoodCS Color0="80,255,90,240"
if kCityData.HappinessGrowthModifier ~= 0 then happinessText = string.format("%+d%% %+d%%", kCityData.HappinessGrowthModifier, kCityData.HappinessNonFoodYieldModifier); end
pCityInstance.CitizenHappiness:SetText( string.format(happinessFormat, happinessText) );
pCityInstance.CitizenHappiness:SetToolTipString( string.format(happinessFormat, happinessToolTip) );
-- Strength and icon for Garrison Unit, and Walls
local sStrength:string = tostring(kCityData.Defense);
local sStrengthToolTip:string = "";
local function CheckForWalls(sWallsType:string)
local pCityBuildings:table = kCityData.City:GetBuildings();
if GameInfo.Buildings[sWallsType] ~= nil and pCityBuildings:HasBuilding( GameInfo.Buildings[sWallsType].Index ) then
sStrengthToolTip = sStrengthToolTip..(string.len(sStrengthToolTip) == 0 and "" or "[NEWLINE]")..Locale.Lookup(GameInfo.Buildings[ sWallsType ].Name);
if pCityBuildings:IsPillaged( GameInfo.Buildings[ sWallsType ].Index ) then
sStrength = sStrength.."[COLOR_Red]!";
sStrengthToolTip = sStrengthToolTip.." "..Locale.Lookup("LOC_TOOLTIP_PLOT_PILLAGED_TEXT");
else
sStrength = sStrength.."[COLOR_Green]!";
end
end
end
CheckForWalls("BUILDING_WALLS");
CheckForWalls("BUILDING_CASTLE");
CheckForWalls("BUILDING_STAR_FORT");
CheckForWalls("BUILDING_TSIKHE"); -- 2020-07-31 Added Tsikhe
-- Garrison
if kCityData.IsGarrisonUnit then
sStrength = sStrength.."[ICON_Fortified]";
sStrengthToolTip = sStrengthToolTip..(string.len(sStrengthToolTip) == 0 and "" or "[NEWLINE]")..Locale.Lookup("LOC_BRS_TOOLTIP_GARRISON").." ("..kCityData.GarrisonUnitName..")";
end
pCityInstance.Strength:SetText( sStrength );
pCityInstance.Strength:SetToolTipString( sStrengthToolTip );
-- WarWeariness
local warWearyValue:number = kCityData.AmenitiesLostFromWarWeariness;
--pCityInstance.WarWeariness:SetText( (warWearyValue==0) and "0" or ColorRed("-"..tostring(warWearyValue)) );
-- Damage
--pCityInstance.Damage:SetText( tostring(kCityData.Damage) ); -- Infixo (vanilla version)
local sDamageWWText:string = "0";
if kCityData.HitpointsTotal > kCityData.HitpointsCurrent then sDamageWWText = ColorRed(kCityData.HitpointsTotal - kCityData.HitpointsCurrent); end
sDamageWWText = sDamageWWText.." / "..( (warWearyValue==0) and "0" or ColorRed("-"..tostring(warWearyValue)) );
pCityInstance.Damage:SetText( sDamageWWText );
--pCityInstance.Damage:SetToolTipString( Locale.Lookup("LOC_HUD_REPORTS_HEADER_DAMAGE").." / "..Locale.Lookup("LOC_HUD_REPORTS_HEADER_WAR_WEARINESS") );
-- Trading Posts
kCityData.IsTradingPost = false;
for _,tpPlayer in ipairs(kCityData.TradingPosts) do
if tpPlayer == Game.GetLocalPlayer() then kCityData.IsTradingPost = true; break; end
end
pCityInstance.TradingPost:SetHide(not kCityData.IsTradingPost);
-- Trading Routes
local tTRTT:table = {};
pCityInstance.TradeRoutes:SetText("[COLOR_White]"..( #kCityData.OutgoingRoutes > 0 and tostring(#kCityData.OutgoingRoutes) or "" ).."[ENDCOLOR]");
for i,route in ipairs(kCityData.OutgoingRoutes) do
-- Find destination city
local pDestPlayer:table = Players[route.DestinationCityPlayer];
local pDestPlayerCities:table = pDestPlayer:GetCities();
local pDestCity:table = pDestPlayerCities:FindID(route.DestinationCityID);
table.insert(tTRTT, Locale.Lookup(pDestCity:GetName()));
end
pCityInstance.TradeRoutes:SetToolTipString( table.concat(tTRTT, ", ") );
-- Districts
pCityInstance.Districts:SetText( GetDistrictsForCity(kCityData) );
if not (bIsRiseFall or bIsGatheringStorm) then return end -- the 2 remaining fields are for Rise & Fall only
-- Loyalty -- Infixo: this is not stored - try to store it for sorting later!
local pCulturalIdentity = kCityData.City:GetCulturalIdentity();
local currentLoyalty = pCulturalIdentity:GetLoyalty();
local maxLoyalty = pCulturalIdentity:GetMaxLoyalty();
local loyaltyPerTurn:number = pCulturalIdentity:GetLoyaltyPerTurn();
local loyaltyFontIcon:string = loyaltyPerTurn >= 0 and "[ICON_PressureUp]" or "[ICON_PressureDown]";
local iNumTurnsLoyalty:number = 0;
if loyaltyPerTurn > 0 then
iNumTurnsLoyalty = math.ceil((maxLoyalty-currentLoyalty)/loyaltyPerTurn);
pCityInstance.Loyalty:SetText( loyaltyFontIcon..""..toPlusMinusString(loyaltyPerTurn).."/"..( iNumTurnsLoyalty == 0 and tostring(iNumTurnsLoyalty) or ColorGreen(iNumTurnsLoyalty) ) );
elseif loyaltyPerTurn < 0 then
iNumTurnsLoyalty = math.ceil(currentLoyalty/(-loyaltyPerTurn));
pCityInstance.Loyalty:SetText( loyaltyFontIcon..""..ColorRed(toPlusMinusString(loyaltyPerTurn).."/"..iNumTurnsLoyalty) );
else
pCityInstance.Loyalty:SetText( loyaltyFontIcon.." 0" );
end
pCityInstance.Loyalty:SetToolTipString(loyaltyFontIcon .. " " .. Round(currentLoyalty, 1) .. "/" .. maxLoyalty);
kCityData.Loyalty = currentLoyalty; -- Infixo: store for sorting
kCityData.LoyaltyPerTurn = loyaltyPerTurn; -- Infixo: store for sorting
-- Governor -- Infixo: this is not stored neither
local pAssignedGovernor = kCityData.City:GetAssignedGovernor();
if pAssignedGovernor then
local eGovernorType = pAssignedGovernor:GetType();
local governorDefinition = GameInfo.Governors[eGovernorType];
local governorMode = pAssignedGovernor:IsEstablished() and "_FILL" or "_SLOT";
local governorIcon = "ICON_" .. governorDefinition.GovernorType .. governorMode;
pCityInstance.Governor:SetText("[" .. governorIcon .. "]");
kCityData.Governor = governorDefinition.GovernorType;
-- name and promotions
local tGovernorTT:table = {};
table.insert(tGovernorTT, Locale.Lookup(governorDefinition.Name)..", "..Locale.Lookup(governorDefinition.Title));
for row in GameInfo.GovernorPromotions() do
if pAssignedGovernor:HasPromotion( row.Index ) then table.insert(tGovernorTT, Locale.Lookup(row.Name)..": "..Locale.Lookup(row.Description)); end
end
pCityInstance.Governor:SetToolTipString(table.concat(tGovernorTT, "[NEWLINE]"));
else
pCityInstance.Governor:SetText("");
pCityInstance.Governor:SetToolTipString("");
kCityData.Governor = "";
end
end
function sort_cities( type, instance )
local i = 0
for _, kCityData in spairs( m_kCityData, function( t, a, b ) return city_sortFunction( instance.Descend, type, t, a, b ); end ) do
i = i + 1
local cityInstance = instance.Children[i]
city_fields( kCityData, cityInstance )
-- go to the city after clicking
cityInstance.GoToCityButton:RegisterCallback( Mouse.eLClick, function() Close(); UI.LookAtPlot( kCityData.City:GetX(), kCityData.City:GetY() ); UI.SelectCity( kCityData.City ); end );
cityInstance.GoToCityButton:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound( "Main_Menu_Mouse_Over" ); end );
end
end
function city_sortFunction( descend, type, t, a, b )
local aCity = 0
local bCity = 0
if type == "name" then
aCity = Locale.Lookup( t[a].CityName )
bCity = Locale.Lookup( t[b].CityName )
elseif type == "gover" then
aCity = t[a].Governor
bCity = t[b].Governor
elseif type == "loyal" then
aCity = t[a].Loyalty
bCity = t[b].Loyalty
if aCity == bCity then
aCity = t[a].City:GetCulturalIdentity():GetLoyaltyPerTurn();
bCity = t[b].City:GetCulturalIdentity():GetLoyaltyPerTurn();
end
elseif type == "pop" then
aCity = t[a].Population
bCity = t[b].Population
if aCity == bCity then -- same pop, sort by Housing
aCity = t[a].Housing
bCity = t[b].Housing
end
elseif type == "house" then -- Infixo: can leave it, will not be used
aCity = t[a].Housing
bCity = t[b].Housing
elseif type == "amen" then
aCity = t[a].AmenitiesNum
bCity = t[b].AmenitiesNum
if aCity == bCity then -- same amenities, sort by required
aCity = t[a].AmenitiesRequiredNum
bCity = t[b].AmenitiesRequiredNum
end
elseif type == "happy" then
aCity = t[a].Happiness
bCity = t[b].Happiness
if aCity == bCity then -- same happiness, sort by difference in amenities
aCity = t[a].AmenitiesNum - t[a].AmenitiesRequiredNum
bCity = t[b].AmenitiesNum - t[b].AmenitiesRequiredNum
end
elseif type == "growth" then
aCity = t[a].HousingMultiplier
bCity = t[b].HousingMultiplier
elseif type == "war" then
aCity = t[a].AmenitiesLostFromWarWeariness
bCity = t[b].AmenitiesLostFromWarWeariness
elseif type == "status" then
if t[a].IsUnderSiege == false then aCity = 10 else aCity = 20 end
if t[b].IsUnderSiege == false then bCity = 10 else bCity = 20 end
elseif type == "str" then
aCity = t[a].Defense
bCity = t[b].Defense
elseif type == "dam" then
aCity = t[a].Damage
bCity = t[b].Damage
elseif type == "trpost" then
aCity = ( t[a].IsTradingPost and 1 or 0 );
bCity = ( t[b].IsTradingPost and 1 or 0 );
elseif type == "numtr" then
aCity = #t[a].OutgoingRoutes;
bCity = #t[b].OutgoingRoutes;
elseif type == "districts" then
aCity = t[a].NumDistricts
bCity = t[b].NumDistricts
elseif type == "religion" then
aCity = t[a].City:GetReligion():GetMajorityReligion();
bCity = t[b].City:GetReligion():GetMajorityReligion();
if aCity > 0 and bCity > 0 then
-- both cities have religion
if descend then return bCity > aCity else return bCity < aCity end
elseif aCity > 0 then
-- only A has religion, must ALWAYS be before B
return true
elseif bCity > 0 then
-- only B has religion, must ALWAYS be before A
end
-- none has, check pantheons
aCity = t[a].City:GetReligion():GetActivePantheon();
bCity = t[b].City:GetReligion():GetActivePantheon();
if aCity > 0 and bCity > 0 then
-- both cities have a pantheon
if descend then return bCity > aCity else return bCity < aCity end
elseif aCity > 0 then
-- only A has pantheon, must ALWAYS be before B
return true
elseif bCity > 0 then
-- only B has pantheon, must ALWAYS be before A
end
-- none has, no more checks
return false
else
-- nothing to do here
end
if descend then return bCity > aCity else return bCity < aCity end
end
function ViewCityStatusPage()
ResetTabForNewPageContent();
local instance:table = m_simpleIM:GetInstance();
instance.Top:DestroyAllChildren();
instance.Children = {}
instance.Descend = true
local pHeaderInstance:table = {};
ContextPtr:BuildInstanceForControl( "CityStatusHeaderInstance", pHeaderInstance, instance.Top );
pHeaderInstance.CityReligionButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities( "religion", instance ) end )
pHeaderInstance.CityNameButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities( "name", instance ) end )
if bIsRiseFall or bIsGatheringStorm then pHeaderInstance.CityGovernorButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities( "gover", instance ) end ) end -- Infixo
if bIsRiseFall or bIsGatheringStorm then pHeaderInstance.CityLoyaltyButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities( "loyal", instance ) end ) end -- Infixo
pHeaderInstance.CityPopulationButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities( "pop", instance ) end )
--pHeaderInstance.CityHousingButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities( "house", instance ) end ) end -- Infixo
pHeaderInstance.CityGrowthButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities( "growth", instance ) end )
pHeaderInstance.CityAmenitiesButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities( "amen", instance ) end )
pHeaderInstance.CityHappinessButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities( "happy", instance ) end )
--pHeaderInstance.CityWarButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities( "war", instance ) end )
pHeaderInstance.CityDistrictsButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities( "districts", instance ) end )
pHeaderInstance.CityStatusButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities( "status", instance ) end )
pHeaderInstance.CityStrengthButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities( "str", instance ) end )
pHeaderInstance.CityDamageButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities( "dam", instance ) end )
pHeaderInstance.CityTradingPostButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities( "trpost", instance ) end );
pHeaderInstance.CityTradeRoutesButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities( "numtr", instance ) end );
--
for _, kCityData in spairs( m_kCityData, function( t, a, b ) return city_sortFunction( true, "name", t, a, b ); end ) do -- initial sort by name ascending
local pCityInstance:table = {}
ContextPtr:BuildInstanceForControl( "CityStatusEntryInstance", pCityInstance, instance.Top );
table.insert( instance.Children, pCityInstance );
city_fields( kCityData, pCityInstance );
-- go to the city after clicking
pCityInstance.GoToCityButton:RegisterCallback( Mouse.eLClick, function() Close(); UI.LookAtPlot( kCityData.City:GetX(), kCityData.City:GetY() ); UI.SelectCity( kCityData.City ); end );
pCityInstance.GoToCityButton:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound( "Main_Menu_Mouse_Over" ); end );
end
Controls.Stack:CalculateSize();
Controls.Scroll:CalculateSize();
Controls.CollapseAll:SetHide( true );
Controls.BottomYieldTotals:SetHide( true );
Controls.BottomResourceTotals:SetHide( true );
Controls.BottomPoliciesFilters:SetHide( true );
Controls.BottomMinorsFilters:SetHide( true );
Controls.Scroll:SetSizeY( Controls.Main:GetSizeY() - SIZE_HEIGHT_PADDING_BOTTOM_ADJUST);
-- Remember this tab when report is next opened: ARISTOS
m_kCurrentTab = 3;
end
-- ===========================================================================
-- UNITS PAGE
-- ===========================================================================
-- returns the name of the City that the unit is currently in, or ""
function GetCityForUnit(pUnit:table)
local pCity:table = Cities.GetCityInPlot( pUnit:GetX(), pUnit:GetY() );
return ( pCity and Locale.Lookup(pCity:GetName()) ) or "";
end
-- returns the icon for the District that the unit is currently in, or ""
function GetDistrictIconForUnit(pUnit:table)
local pPlot:table = Map.GetPlot( pUnit:GetX(), pUnit:GetY() );
if not pPlot then return ""; end -- assert
local eDistrictType:number = pPlot:GetDistrictType();
--print("Unit", pUnit:GetName(), eDistrictType);
if eDistrictType < 0 then return ""; end
local sDistrictType:string = GameInfo.Districts[ eDistrictType ].DistrictType;
if GameInfo.DistrictReplaces[ sDistrictType ] then sDistrictType = GameInfo.DistrictReplaces[ sDistrictType ].ReplacesDistrictType; end
return GetFontIconForDistrict(sDistrictType);
end
function unit_sortFunction( descend, type, t, a, b )
local aUnit, bUnit
if type == "type" then
aUnit = UnitManager.GetTypeName( t[a] )
bUnit = UnitManager.GetTypeName( t[b] )
elseif type == "name" then
aUnit = Locale.Lookup( t[a]:GetName() )
bUnit = Locale.Lookup( t[b]:GetName() )
if aUnit == bUnit then
aUnit = t[a]:GetMilitaryFormation()
bUnit = t[b]:GetMilitaryFormation()
end
elseif type == "maintenance" then
aUnit = t[a].MaintenanceAfterDiscount;
bUnit = t[b].MaintenanceAfterDiscount;
elseif type == "status" then
aUnit = UnitManager.GetActivityType( t[a] )
bUnit = UnitManager.GetActivityType( t[b] )
elseif type == "level" then
aUnit = t[a]:GetExperience():GetLevel();
bUnit = t[b]:GetExperience():GetLevel();
elseif type == "exp" then
aUnit = t[a]:GetExperience():GetExperiencePoints()
bUnit = t[b]:GetExperience():GetExperiencePoints()
elseif type == "health" then
aUnit = t[a]:GetMaxDamage() - t[a]:GetDamage()
bUnit = t[b]:GetMaxDamage() - t[b]:GetDamage()
elseif type == "move" then
if ( t[a]:GetFormationUnitCount() > 1 ) then
aUnit = t[a]:GetFormationMovesRemaining()
else
aUnit = t[a]:GetMovesRemaining()
end
if ( t[b]:GetFormationUnitCount() > 1 ) then
bUnit = t[b]:GetFormationMovesRemaining()
else
bUnit = t[b]:GetMovesRemaining()
end
elseif type == "charge" then
aUnit = t[a]:GetBuildCharges()
bUnit = t[b]:GetBuildCharges()
elseif type == "yield" then
aUnit = t[a].yields
bUnit = t[b].yields
elseif type == "route" then
aUnit = t[a].route
bUnit = t[b].route
elseif type == "class" then
aUnit = t[a]:GetGreatPerson():GetClass()
bUnit = t[b]:GetGreatPerson():GetClass()
elseif type == "strength" then
aUnit = t[a]:GetReligiousStrength()
bUnit = t[b]:GetReligiousStrength()
elseif type == "spread" then
aUnit = t[a]:GetSpreadCharges()
bUnit = t[b]:GetSpreadCharges()
elseif type == "mission" then
aUnit = t[a].mission
bUnit = t[b].mission
elseif type == "turns" then
aUnit = t[a].turns
bUnit = t[b].turns
elseif type == "city" then
aUnit = t[a].NearCityName
bUnit = t[b].NearCityName
if aUnit == bUnit then
aUnit = t[a].NearCityDistance
bUnit = t[b].NearCityDistance
end
--[[
if aUnit ~= "" and bUnit ~= "" then
if descend then return aUnit > bUnit else return aUnit < bUnit end
else
if aUnit == "" then return false;
elseif bUnit == "" then return true;
else return false; end
end
--]]
elseif type == "albums" then
aUnit = t[a].RockBandAlbums;
bUnit = t[b].RockBandAlbums;
--[[
if bIsGatheringStorm and GameInfo.Units[t[a]:GetUnitType()].PromotionClass == "PROMOTION_CLASS_ROCK_BAND" then
aUnit = t[a]:GetRockBand():GetAlbumSales();
end
if bIsGatheringStorm and GameInfo.Units[t[b]:GetUnitType()].PromotionClass == "PROMOTION_CLASS_ROCK_BAND" then
bUnit = t[b]:GetRockBand():GetAlbumSales();
end
--]]
else
return false; -- assert
end
if descend then return aUnit > bUnit else return aUnit < bUnit end
end
function sort_units( type, group, parent )
local i = 0
local unit_group = m_kUnitDataReport[group]
for _, unit in spairs( unit_group.units, function( t, a, b ) return unit_sortFunction( parent.Descend, type, t, a, b ) end ) do
i = i + 1
local unitInstance = parent.Children[i]
common_unit_fields( unit, unitInstance )
if unit_group.func then unit_group.func( unit, unitInstance, group, parent, type ) end
unitInstance.LookAtButton:RegisterCallback( Mouse.eLClick, function() Close(); UI.LookAtPlot( unit:GetX( ), unit:GetY( ) ); UI.SelectUnit( unit ); end )
unitInstance.LookAtButton:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound( "Main_Menu_Mouse_Over" ); end )
end
end
function common_unit_fields( unit, unitInstance )
--if unitInstance.Formation then unitInstance.Formation:SetHide( true ) end
local textureOffsetX:number, textureOffsetY:number, textureSheet:string = IconManager:FindIconAtlas( "ICON_" .. UnitManager.GetTypeName( unit ), 32 )
unitInstance.UnitType:SetTexture( textureOffsetX, textureOffsetY, textureSheet )
--unitInstance.UnitType:SetToolTipString( Locale.Lookup( GameInfo.Units[UnitManager.GetTypeName( unit )].Name ) )
unitInstance.UnitType:SetToolTipString( Locale.Lookup(GameInfo.Units[unit:GetUnitType()].Name).."[NEWLINE]"..Locale.Lookup(GameInfo.Units[unit:GetUnitType()].Description) );
-- debug section to see Modifiers for all units
--[[
local tPromoTT:table = {};
table.insert(tPromoTT, Locale.Lookup( GameInfo.Units[UnitManager.GetTypeName( unit )].Name ));
local tUnitModifiers:table = m_kModifiersUnits[ unit:GetID() ];
if table.count(tUnitModifiers) > 0 then table.insert(tPromoTT, TOOLTIP_SEP); end
local i = 0;
for _,mod in ipairs(tUnitModifiers) do
i = i + 1;
table.insert(tPromoTT, i..". "..Locale.Lookup(mod.OwnerName)..": "..mod.Modifier.ModifierId.." ("..RMA.GetObjectNameForModifier(mod.Modifier.ModifierId)..") "..mod.Modifier.EffectType.." "..( mod.Modifier.Text and "|"..Locale.Lookup(mod.Modifier.Text).."|" or "-"));
end
unitInstance.UnitType:SetToolTipString( table.concat(tPromoTT, "[NEWLINE]") );
--]]
unitInstance.UnitName:SetText( Locale.Lookup(unit:GetName()) );
-- adds the status icon
local activityType:number = UnitManager.GetActivityType( unit )
--print("Unit", unit:GetID(),activityType,unit:GetSpyOperation(),unit:GetSpyOperationEndTurn());
unitInstance.UnitStatus:SetHide( false )
local bIsMoving:boolean = true; -- Infixo
if activityType == ActivityTypes.ACTIVITY_SLEEP then
local textureOffsetX:number, textureOffsetY:number, textureSheet:string = IconManager:FindIconAtlas( "ICON_STATS_SLEEP", 22 )
unitInstance.UnitStatus:SetTexture( textureOffsetX, textureOffsetY, textureSheet )
bIsMoving = false;
elseif activityType == ActivityTypes.ACTIVITY_HOLD then
local textureOffsetX:number, textureOffsetY:number, textureSheet:string = IconManager:FindIconAtlas( "ICON_STATS_SKIP", 22 )
unitInstance.UnitStatus:SetTexture( textureOffsetX, textureOffsetY, textureSheet )
elseif activityType ~= ActivityTypes.ACTIVITY_AWAKE and unit:GetFortifyTurns() > 0 then
local textureOffsetX:number, textureOffsetY:number, textureSheet:string = IconManager:FindIconAtlas( "ICON_DEFENSE", 22 )
unitInstance.UnitStatus:SetTexture( textureOffsetX, textureOffsetY, textureSheet )
bIsMoving = false;
else
-- just use a random icon for sorting purposes
local textureOffsetX:number, textureOffsetY:number, textureSheet:string = IconManager:FindIconAtlas( "ICON_STATS_SPREADCHARGES", 22 )
unitInstance.UnitStatus:SetTexture( textureOffsetX, textureOffsetY, textureSheet )
unitInstance.UnitStatus:SetHide( true )
end
if activityType == ActivityTypes.ACTIVITY_SENTRY then bIsMoving = false; end
if unit:GetSpyOperation() ~= -1 then bIsMoving = false; end
-- moves here to mark units that should move this turn
if ( unit:GetFormationUnitCount() > 1 ) then
unitInstance.UnitMove:SetText( tostring(unit:GetFormationMovesRemaining()).."/"..tostring(unit:GetFormationMaxMoves()).." [ICON_Formation]" );
--unitInstance.Formation:SetHide( false )
unitInstance.UnitMove:SetToolTipString( Locale.Lookup("LOC_HUD_UNIT_ACTION_AUTOEXPLORE_IN_FORMATION") );
elseif unitInstance.UnitMove then
if unit:GetMovesRemaining() == 0 then bIsMoving = false; end
unitInstance.UnitMove:SetText( (bIsMoving and "[COLOR_Red]" or "")..tostring( unit:GetMovesRemaining() ).."/"..tostring( unit:GetMaxMoves() )..(bIsMoving and "[ENDCOLOR]" or "") )
unitInstance.UnitMove:SetToolTipString( "" );
end
unit.District = GetDistrictIconForUnit(unit);
unitInstance.UnitDistrict:SetText(unit.District);
--unit.City = GetCityForUnit(unit);
--unitInstance.UnitCity:SetText(unit.City);
local sCityName:string = ( unit.NearCityIsCapital and "[ICON_Capital]" or "" )..unit.NearCityName;
if unit.NearCityDistance == 0 then sCityName = "[COLOR:16,232,75,160]"..sCityName.."[ENDCOLOR]";
elseif unit.NearCityIsOurs then sCityName = sCityName.." "..unit.NearCityDistance;
else sCityName = "[COLOR_Red]"..sCityName.." "..unit.NearCityDistance.."[ENDCOLOR]"; end
unitInstance.UnitCity:SetText( (unit.NearCityDistance > 3) and "" or sCityName );
unitInstance.UnitMaintenance:SetText( toPlusMinusString(-unit.MaintenanceAfterDiscount) );
if bIsGatheringStorm then
unitInstance.UnitMaintenance:SetText( unit.ResMaint..tostring(unit.MaintenanceAfterDiscount));
end
end
-- simple texts for modifiers' effects
local tTextsForEffects:table = {
EFFECT_ATTACH_MODIFIER = "LOC_GREATPERSON_PASSIVE_NAME_DEFAULT",
EFFECT_ADJUST_UNIT_EXTRACT_SEA_ARTIFACTS = "[ICON_RESOURCE_SHIPWRECK]",
EFFECT_ADJUST_UNIT_NUM_ATTACKS = "LOC_PROMOTION_WOLFPACK_DESCRIPTION",
EFFECT_ADJUST_UNIT_ATTACK_AND_MOVE = "LOC_PROMOTION_GUERRILLA_DESCRIPTION",
EFFECT_ADJUST_UNIT_MOVE_AND_ATTACK = "LOC_PROMOTION_GUERRILLA_DESCRIPTION",
EFFECT_ADJUST_UNIT_BYPASS_COMBAT_UNIT = "LOC_ABILITY_BYPASS_COMBAT_UNIT_NAME",
EFFECT_ADJUST_UNIT_IGNORE_TERRAIN_COST = "LOC_ABILITY_IGNORE_TERRAIN_COST_NAME", -- Arguments.Type = ALL HILLS FOREST
EFFECT_ADJUST_UNIT_PARADROP_ABILITY = "LOC_UNITCOMMAND_PARADROP_DESCRIPTION",
EFFECT_ADJUST_UNIT_SEE_HIDDEN = "LOC_ABILITY_SEE_HIDDEN_NAME",
EFFECT_ADJUST_UNIT_HIDDEN_VISIBILITY = "LOC_ABILITY_STEALTH_NAME",
EFFECT_ADJUST_UNIT_RAIDING = "LOC_ABILITY_COASTAL_RAID_NAME",
EFFECT_ADJUST_UNIT_IGNORE_RIVERS = "LOC_PROMOTION_AMPHIBIOUS_NAME",
EFFECT_ADJUST_UNIT_IGNORE_SHORES = "[ICON_CheckmarkBlue]{LOC_UNITOPERATION_DISEMBARK_DESCRIPTION}",
EFFECT_ADJUST_PLAYER_RANDOM_CIVIC_BOOST_GOODY_HUT = "{LOC_HUD_POPUP_CIVIC_BOOST_UNLOCKED}[ICON_CivicBoosted]",
EFFECT_ADJUST_PLAYER_RANDOM_TECHNOLOGY_BOOST_GOODY_HUT = "{LOC_HUD_POPUP_TECH_BOOST_UNLOCKED}[ICON_TechBoosted]",
};
function group_military( unit, unitInstance, group, parent, type )
-- for military we'll show its base strength also
local eFormation:number = unit:GetMilitaryFormation();
local iCombat:number, iRanged:number, iBombard:number = unit:GetCombat(), unit:GetRangedCombat(), unit:GetBombardCombat();
-- name will be: name .. formation .. strength
local sText:string = Locale.Lookup( unit:GetName() );
if eFormation == MilitaryFormationTypes.CORPS_FORMATION then sText = sText .. " [ICON_Corps]";
elseif eFormation == MilitaryFormationTypes.ARMY_FORMATION then sText = sText .. " [ICON_Army]" ;
end
if iBombard > 0 then sText = sText.." [ICON_Bombard]"..tostring(iBombard);
elseif iRanged > 0 then sText = sText.." [ICON_Ranged]"..tostring(iRanged);
elseif iCombat > 0 then sText = sText.." [ICON_Strength]"..tostring(iCombat);
end
unitInstance.UnitName:SetText( sText );
-- Level and Promotions
local unitExp : table = unit:GetExperience()
local iUnitLevel:number = unitExp:GetLevel();
if iUnitLevel < 2 then unitInstance.UnitLevel:SetText( tostring(iUnitLevel) );
elseif iUnitLevel == 2 then unitInstance.UnitLevel:SetText( tostring(iUnitLevel).." [ICON_Promotion]" );
else unitInstance.UnitLevel:SetText( tostring(iUnitLevel).." [ICON_Promotion]"..string.rep("*", iUnitLevel-2) ); end
local tPromoTT:table = {};
for _,promo in ipairs(unitExp:GetPromotions()) do
table.insert(tPromoTT, Locale.Lookup(GameInfo.UnitPromotions[promo].Name)..": "..Locale.Lookup(GameInfo.UnitPromotions[promo].Description));
end
-- this section might grow!
local tUnitModifiers:table = m_kModifiersUnits[ unit:GetID() ];
local tMod:table = nil;
local sText:string = "";
if table.count(tUnitModifiers) > 0 then table.insert(tPromoTT, TOOLTIP_SEP); end
local iPromoNum:number = 0;
local tExtraTT:table = {};
for _,mod in ipairs(tUnitModifiers) do
local function AddExtraPromoText(sText:string)
--print("AddExtraPromoText", mod.OwnerName, mod.Modifier.ModifierId, sText);
local sExtra:string = Locale.Lookup(mod.OwnerName).." ("..RMA.GetObjectNameForModifier(mod.Modifier.ModifierId)..") "..sText;
for _,txt in ipairs(tExtraTT) do if txt == sExtra then return; end end -- check if already added, do not add duplicates
iPromoNum = iPromoNum + 1;
table.insert(tPromoTT, tonumber(iPromoNum)..". "..sExtra);
table.insert(tExtraTT, sExtra);
end
tMod = mod.Modifier;
sText = ""; if tMod.Text then sText = Locale.Lookup(tMod.Text); end
if sText ~= "" then
AddExtraPromoText( sText );
elseif tMod.EffectType == "EFFECT_ADJUST_PLAYER_STRENGTH_MODIFIER" or tMod.EffectType == "EFFECT_ADJUST_UNIT_DIPLO_VISIBILITY_COMBAT_MODIFIER" then
if tMod.Arguments.Amount ~= nil then
AddExtraPromoText( string.format("%+d [ICON_Strength]", tonumber(tMod.Arguments.Amount))); -- Strength
elseif tMod.Arguments.Max ~= nil then
AddExtraPromoText( string.format("%+d [ICON_Strength]", tonumber(tMod.Arguments.Max))); -- Vampires, stregth from Barbs
else
AddExtraPromoText( "[ICON_Strength]" ); -- Vampires, strength
end
elseif tMod.EffectType == "EFFECT_GRANT_ABILITY" then
local unitAbility:table = GameInfo.UnitAbilities[ tMod.Arguments.AbilityType ];
if unitAbility and unitAbility.Name and unitAbility.Description then -- 2019-08-30 some Abilities have neither Name nor Description
AddExtraPromoText( Locale.Lookup(unitAbility.Name)..": "..Locale.Lookup(unitAbility.Description)); -- LOC_CIVICS_KEY_ABILITY
else
AddExtraPromoText( tMod.EffectType.." [COLOR_Red]"..tMod.Arguments.AbilityType.."[ENDCOLOR]")
end
elseif tMod.EffectType == "EFFECT_GRANT_PROMOTION" then
local unitPromotion:table = GameInfo.UnitPromotions[ tMod.Arguments.PromotionType ];
if unitPromotion then
AddExtraPromoText( Locale.Lookup(unitPromotion.Name)..": "..Locale.Lookup(unitPromotion.Description));
else
AddExtraPromoText( tMod.EffectType.." [COLOR_Red]"..tMod.Arguments.PromotionType.."[ENDCOLOR]")
end
elseif tMod.EffectType == "EFFECT_ADJUST_UNIT_EXPERIENCE_MODIFIER" then
AddExtraPromoText( string.format("%+d%% ", tonumber(tMod.Arguments.Amount))..Locale.Lookup("LOC_HUD_UNIT_PANEL_XP")); -- +x%
elseif tMod.EffectType == "EFFECT_ADJUST_UNIT_FLANKING_BONUS_MODIFIER" then
AddExtraPromoText( Locale.Lookup("LOC_COMBAT_PREVIEW_FLANKING_BONUS_DESC", tMod.Arguments.Percent.."%") ); -- +x%
elseif tMod.EffectType == "EFFECT_ADJUST_UNIT_SEA_MOVEMENT" or tMod.EffectType == "EFFECT_ADJUST_UNIT_MOVEMENT" then
AddExtraPromoText( string.format("%+d [ICON_Movement]", tonumber(tMod.Arguments.Amount))); -- Movement
elseif tMod.EffectType == "EFFECT_ADJUST_UNIT_VALID_TERRAIN" then
AddExtraPromoText( Locale.Lookup( GameInfo.Terrains[tMod.Arguments.TerrainType].Name ) );
elseif tMod.EffectType == "EFFECT_ADJUST_UNIT_ATTACK_RANGE" then
AddExtraPromoText( string.format("%+d [ICON_Range]", tonumber(tMod.Arguments.Amount)));
elseif tTextsForEffects[tMod.EffectType] then
AddExtraPromoText( Locale.Lookup(tTextsForEffects[tMod.EffectType]) );
elseif tMod.EffectType == "EFFECT_ADJUST_UNIT_STRENGTH_REDUCTION_FOR_DAMAGE_MODIFIER" then
AddExtraPromoText( string.format("[ICON_Damaged] -%d%%", tonumber(tMod.Arguments.Amount)) ); -- +x%
elseif tMod.EffectType == "EFFECT_ADJUST_UNIT_POST_COMBAT_HEAL" then
AddExtraPromoText( Locale.Lookup("LOC_BRS_HEADER_HEALTH")..string.format(" %+d", tonumber(tMod.Arguments.Amount)) ); -- +x HP
elseif tMod.EffectType == "EFFECT_ADJUST_UNIT_BARBARIAN_COMBAT" then
local iAdvStr:number = tonumber(tMod.Arguments.Amount);
AddExtraPromoText( string.gsub(Locale.Lookup("LOC_COMBAT_PREVIEW_BONUS_VS_BARBARIANS", iAdvStr), "+"..tostring(iAdvStr), "+"..tostring(iAdvStr).." [ICON_Strength]") ); -- +{1_Value} Advantage vs. Barbarians
elseif tMod.EffectType == "EFFECT_ADJUST_UNIT_SUPPORT_BONUS_MODIFIER" then
AddExtraPromoText( Locale.Lookup("LOC_COMBAT_PREVIEW_SUPPORT_BONUS_DESC", tonumber(tMod.Arguments.Percent)) ); -- +x% support bonus
else
AddExtraPromoText( "[COLOR_Grey]"..tMod.EffectType.."[ENDCOLOR]" );
end
end
unitInstance.UnitLevel:SetToolTipString( table.concat(tPromoTT, "[NEWLINE]") );
-- XP and Promotion Available
local bCanStart, tResults = UnitManager.CanStartCommand( unit, UnitCommandTypes.PROMOTE, true, true );
unitInstance.UnitExp:SetText( tostring(unitExp:GetExperiencePoints()).."/"..tostring(unitExp:GetExperienceForNextLevel())..((bCanStart and tResults) and " [ICON_Promotion]" or "") );
unitInstance.UnitExp:SetToolTipString( (bCanStart and tResults) and Locale.Lookup("LOC_HUD_UNIT_ACTION_AUTOEXPLORE_PROMOTION_AVAILABLE") or "" );
-- Unit Health
local iHealthPoints:number = unit:GetMaxDamage() - unit:GetDamage();
local fHealthPercent:number = iHealthPoints / unit:GetMaxDamage();
local sHealthColor:string = "";
-- Common format is 0xBBGGRRAA (BB blue, GG green, RR red, AA alpha); stupid Firaxis - it's 0xAABBGGRR
if fHealthPercent > 0.7 then sHealthColor = "[COLOR:16,232,75,160]"; -- COLORS.METER_HP_GOOD 0xFF4BE810
elseif fHealthPercent > 0.4 then sHealthColor = "[COLOR:248,255,45,160]"; -- COLORS.METER_HP_OK 0xFF2DFFF8
else sHealthColor = "[COLOR:245,1,1,160]"; end -- COLORS.METER_HP_BAD 0xFF0101F5
unitInstance.UnitHealth:SetText( sHealthColor..tostring(iHealthPoints).."/"..tostring(unit:GetMaxDamage()).."[ENDCOLOR]" );
-- upgrade flag
unitInstance.Upgrade:SetHide( true )
--ARISTOS: a "looser" test for the Upgrade action, to be able to show the disabled arrow if Upgrade is not possible
local bCanStart = UnitManager.CanStartCommand( unit, UnitCommandTypes.UPGRADE, true);
if ( bCanStart ) then
unitInstance.Upgrade:SetHide( false )
--ARISTOS: Now we "really" test if we can Upgrade the unit!
local bCanStartNow, tResults = UnitManager.CanStartCommand( unit, UnitCommandTypes.UPGRADE, false, true);
unitInstance.Upgrade:SetDisabled(not bCanStartNow);
unitInstance.Upgrade:SetAlpha((not bCanStartNow and 0.5) or 1 ); --ARISTOS: dim if not upgradeable
-- upgrade callback
unitInstance.Upgrade:RegisterCallback( Mouse.eLClick, function()
-- the only case where we need to re-sort units preserving current order
-- actual re-sort must be done in Event, otherwise unit info is not refreshed (ui cache?)
tUnitSort.type = type; tUnitSort.group = group; tUnitSort.parent = parent;
UnitManager.RequestCommand( unit, UnitCommandTypes.UPGRADE );
end )
-- tooltip
local upgradeToUnit:table = GameInfo.Units[tResults[UnitCommandResults.UNIT_TYPE]];
local toolTipString:string = Locale.Lookup( "LOC_UNITOPERATION_UPGRADE_INFO", Locale.Lookup(upgradeToUnit.Name), unit:GetUpgradeCost() ); -- Upgrade to {1_Unit}: {2_Amount} [ICON_Gold]Gold
-- Gathering Storm
if bIsGatheringStorm then toolTipString = toolTipString .. AddUpgradeResourceCost(unit, upgradeToUnit); end
if tResults[UnitOperationResults.FAILURE_REASONS] then
-- Add the reason(s) to the tool tip
for i,v in ipairs(tResults[UnitOperationResults.FAILURE_REASONS]) do
toolTipString = toolTipString .. "[NEWLINE]" .. "[COLOR:Red]" .. Locale.Lookup(v) .. "[ENDCOLOR]";
end
end
unitInstance.Upgrade:SetToolTipString( toolTipString );
end
end
-- modified function from UnitPanel_Expansion2.lua, adds also maintenance resource cost
function AddUpgradeResourceCost( pUnit:table, upgradeToUnitInfo:table )
local toolTipString:string = "";
-- requires
local upgradeResource, upgradeResourceCost = pUnit:GetUpgradeResourceCost();
if (upgradeResource ~= nil and upgradeResource >= 0) then
local resourceName:string = Locale.Lookup(GameInfo.Resources[upgradeResource].Name);
local resourceIcon = "[ICON_" .. GameInfo.Resources[upgradeResource].ResourceType .. "]";
toolTipString = toolTipString .. "[NEWLINE]" .. Locale.Lookup("LOC_UNITOPERATION_UPGRADE_RESOURCE_INFO", upgradeResourceCost, resourceIcon, resourceName); -- Requires: {1_Amount} {2_ResourceIcon} {3_ResourceName}
end
-- maintenance info
local unitInfoXP2:table = GameInfo.Units_XP2[ upgradeToUnitInfo.UnitType ];
if unitInfoXP2 ~= nil then
-- upgrade to unit name
toolTipString = toolTipString.."[NEWLINE]"..Locale.Lookup(upgradeToUnitInfo.Name).." [ICON_GoingTo]";
-- gold
if upgradeToUnitInfo.Maintenance > 0 then
toolTipString = toolTipString.." "..Locale.Lookup("LOC_TOOLTIP_BASE_COST", upgradeToUnitInfo.Maintenance, "[ICON_Gold]", "LOC_YIELD_GOLD_NAME"); -- Base Cost: {1_Amount} {2_YieldIcon} {3_YieldName}
end
-- resources
if unitInfoXP2.ResourceMaintenanceType ~= nil then
local resourceName:string = Locale.Lookup(GameInfo.Resources[ unitInfoXP2.ResourceMaintenanceType ].Name);
local resourceIcon = "[ICON_" .. GameInfo.Resources[unitInfoXP2.ResourceMaintenanceType].ResourceType .. "]";
toolTipString = toolTipString.." "..Locale.Lookup("LOC_UNIT_PRODUCTION_FUEL_CONSUMPTION", unitInfoXP2.ResourceMaintenanceAmount, resourceIcon, resourceName); -- Consumes: {1_Amount} {2_Icon} {3_FuelName} per turn.
end
end
return toolTipString;
end
function group_civilian( unit, unitInstance, group, parent, type )
ShowUnitPromotions(unit, unitInstance);
unitInstance.UnitCharges:SetText( tostring(unit:GetBuildCharges()) );
unitInstance.UnitAlbums:SetText("");
if unit.IsRockBand then
unitInstance.UnitCharges:SetText("");
unitInstance.UnitAlbums:SetText( tostring(unit.RockBandAlbums) );
end
end
function group_great( unit, unitInstance, group, parent, type )
unitInstance.UnitClass:SetText( Locale.Lookup( GameInfo.GreatPersonClasses[unit:GetGreatPerson():GetClass()].Name ) )
end
function ShowUnitPromotions(unit:table, unitInstance:table)
-- Level and Promotions
local tPromoTT:table = {};
for _,promo in ipairs(unit:GetExperience():GetPromotions()) do
table.insert(tPromoTT, Locale.Lookup(GameInfo.UnitPromotions[promo].Name)..": "..Locale.Lookup(GameInfo.UnitPromotions[promo].Description));
end
local sLevel:string = "";
if unit.IsRockBand then sLevel = tostring(unit.RockBandLevel); end
if #tPromoTT == 0 then unitInstance.UnitLevel:SetText(sLevel);
elseif #tPromoTT == 1 then unitInstance.UnitLevel:SetText(sLevel.." [ICON_Promotion]");
else unitInstance.UnitLevel:SetText(sLevel.." [ICON_Promotion]"..string.rep("*", #tPromoTT-1) ); end
unitInstance.UnitLevel:SetToolTipString( table.concat(tPromoTT, "[NEWLINE]") );
end
function group_religious( unit, unitInstance, group, parent, type )
ShowUnitPromotions(unit, unitInstance);
unitInstance.UnitSpreads:SetText( unit:GetSpreadCharges() )
unitInstance.UnitStrength:SetText( unit:GetReligiousStrength() )
end
function group_spy( unit, unitInstance, group, parent, type )
ShowUnitPromotions(unit, unitInstance);
-- operation
local operationType : number = unit:GetSpyOperation();
unitInstance.UnitOperation:SetText( "-" );
unitInstance.UnitTurns:SetText( "[COLOR_Red]0[ENDCOLOR]" );
unit.mission = "-";
unit.turns = 0;
if ( operationType ~= -1 ) then
-- Mission Name
local operationInfo:table = GameInfo.UnitOperations[operationType];
unit.mission = Locale.Lookup( operationInfo.Description );
unitInstance.UnitOperation:SetText( unit.mission );
-- Turns Remaining
unit.turns = unit:GetSpyOperationEndTurn() - Game.GetCurrentGameTurn()
--unitInstance.UnitTurns:SetText( Locale.Lookup( "LOC_UNITPANEL_ESPIONAGE_MORE_TURNS", unit:GetSpyOperationEndTurn() - Game.GetCurrentGameTurn() ) )
unitInstance.UnitTurns:SetText( tostring(unit.turns) );
end
end
function group_trader( unit, unitInstance, group, parent, type )
local owningPlayer:table = Players[unit:GetOwner()];
local cities:table = owningPlayer:GetCities();
--[[
local yieldtype: table = {
YIELD_FOOD = "[ICON_Food]",
YIELD_PRODUCTION = "[ICON_Production]",
YIELD_GOLD = "[ICON_Gold]",
YIELD_SCIENCE = "[ICON_Science]",
YIELD_CULTURE = "[ICON_Culture]",
YIELD_FAITH = "[ICON_Faith]",
};
--]]
local yields : string = ""
unitInstance.UnitYields:SetText( "" );
unitInstance.UnitRoute:SetText( "[COLOR_Red]"..Locale.Lookup("LOC_UNITOPERATION_MAKE_TRADE_ROUTE_DESCRIPTION") );
unit.yields = ""
unit.route = "No Route"
for _, city in cities:Members() do
local outgoingRoutes:table = city:GetTrade():GetOutgoingRoutes();
for i,route in ipairs(outgoingRoutes) do
if unit:GetID() == route.TraderUnitID then
-- Find origin city
local originCity:table = cities:FindID(route.OriginCityID);
-- Find destination city
local destinationPlayer:table = Players[route.DestinationCityPlayer];
local destinationCities:table = destinationPlayer:GetCities();
local destinationCity:table = destinationCities:FindID(route.DestinationCityID);
-- Set origin to destination name
if originCity and destinationCity then
unitInstance.UnitRoute:SetText( Locale.Lookup("LOC_HUD_UNIT_PANEL_TRADE_ROUTE_NAME", originCity:GetName(), destinationCity:GetName()) )
unit.route = Locale.Lookup("LOC_HUD_UNIT_PANEL_TRADE_ROUTE_NAME", originCity:GetName(), destinationCity:GetName())
end
for j, yieldInfo in pairs( route.OriginYields ) do
if yieldInfo.Amount > 0 then
yields = yields .. GameInfo.Yields[yieldInfo.YieldIndex].IconString .. toPlusMinusString(yieldInfo.Amount);
unitInstance.UnitYields:SetText( yields )
unit.yields = yields
end
end
end
end
end
end
function ViewUnitsPage()
ResetTabForNewPageContent();
tUnitSort.parent = nil;
for iUnitGroup, kUnitGroup in spairs( m_kUnitDataReport, function( t, a, b ) return t[b].ID > t[a].ID end ) do
local instance : table = NewCollapsibleGroupInstance()
instance.RowHeaderButton:SetText( Locale.Lookup(kUnitGroup.Name) );
instance.RowHeaderLabel:SetHide( false ); --BRS
instance.RowHeaderLabel:SetText( Locale.Lookup("LOC_HUD_REPORTS_TOTALS").." "..tostring(#kUnitGroup.units) );
instance.AmenitiesContainer:SetHide(true);
instance.IndustryContainer:SetHide(true); -- 2021-05-21
instance.MonopolyContainer:SetHide(true); -- 2021-05-21
local pHeaderInstance:table = {}
ContextPtr:BuildInstanceForControl( kUnitGroup.Header, pHeaderInstance, instance.ContentStack )
-- Infixo: important info - iUnitGroup is NOT integer nor table, it is a STRING taken from FORMATION_CLASS_xxx
if pHeaderInstance.UnitTypeButton then pHeaderInstance.UnitTypeButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "type", iUnitGroup, instance ) end ) end
if pHeaderInstance.UnitNameButton then pHeaderInstance.UnitNameButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "name", iUnitGroup, instance ) end ) end
if pHeaderInstance.UnitStatusButton then pHeaderInstance.UnitStatusButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "status", iUnitGroup, instance ) end ) end
if pHeaderInstance.UnitLevelButton then pHeaderInstance.UnitLevelButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "level", iUnitGroup, instance ) end ) end
if pHeaderInstance.UnitExpButton then pHeaderInstance.UnitExpButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "exp", iUnitGroup, instance ) end ) end
if pHeaderInstance.UnitHealthButton then pHeaderInstance.UnitHealthButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "health", iUnitGroup, instance ) end ) end
if pHeaderInstance.UnitMoveButton then pHeaderInstance.UnitMoveButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "move", iUnitGroup, instance ) end ) end
if pHeaderInstance.UnitChargeButton then pHeaderInstance.UnitChargeButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "charge", iUnitGroup, instance ) end ) end
if pHeaderInstance.UnitYieldButton then pHeaderInstance.UnitYieldButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "yield", iUnitGroup, instance ) end ) end
if pHeaderInstance.UnitRouteButton then pHeaderInstance.UnitRouteButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "route", iUnitGroup, instance ) end ) end
if pHeaderInstance.UnitClassButton then pHeaderInstance.UnitClassButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "class", iUnitGroup, instance ) end ) end
if pHeaderInstance.UnitStrengthButton then pHeaderInstance.UnitStrengthButton:RegisterCallback(Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "strength", iUnitGroup, instance ) end ) end
if pHeaderInstance.UnitSpreadButton then pHeaderInstance.UnitSpreadButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "spread", iUnitGroup, instance ) end ) end
if pHeaderInstance.UnitMissionButton then pHeaderInstance.UnitMissionButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "mission", iUnitGroup, instance ) end ) end
if pHeaderInstance.UnitTurnsButton then pHeaderInstance.UnitTurnsButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "turns", iUnitGroup, instance ) end ) end
if pHeaderInstance.UnitCityButton then pHeaderInstance.UnitCityButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "city", iUnitGroup, instance ) end ) end
if pHeaderInstance.UnitMaintenanceButton then pHeaderInstance.UnitMaintenanceButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "maintenance", iUnitGroup, instance ) end ) end
if pHeaderInstance.UnitAlbumsButton then
if bIsGatheringStorm then
pHeaderInstance.UnitAlbumsButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "albums", iUnitGroup, instance ) end );
else
pHeaderInstance.UnitAlbumsLabel:SetText("");
end
end
instance.Descend = false;
for _,unit in spairs( kUnitGroup.units, function( t, a, b ) return unit_sortFunction( false, "name", t, a, b ) end ) do -- initial sort by name ascending
local unitInstance:table = {}
table.insert( instance.Children, unitInstance )
ContextPtr:BuildInstanceForControl( kUnitGroup.Entry, unitInstance, instance.ContentStack );
common_unit_fields( unit, unitInstance )
if kUnitGroup.func then kUnitGroup.func( unit, unitInstance, iUnitGroup, instance, "name" ) end
-- allows you to select a unit and zoom to them
unitInstance.LookAtButton:RegisterCallback( Mouse.eLClick, function() Close(); UI.LookAtPlot( unit:GetX( ), unit:GetY( ) ); UI.SelectUnit( unit ); end )
unitInstance.LookAtButton:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound( "Main_Menu_Mouse_Over" ); end )
end
SetGroupCollapsePadding(instance, 0); --pFooterInstance.Top:GetSizeY() )
RealizeGroup( instance );
end
Controls.Stack:CalculateSize();
Controls.Scroll:CalculateSize();
Controls.CollapseAll:SetHide( false );
Controls.BottomYieldTotals:SetHide( true )
Controls.BottomResourceTotals:SetHide( true )
Controls.BottomPoliciesFilters:SetHide( true );
Controls.BottomMinorsFilters:SetHide( true );
Controls.Scroll:SetSizeY( Controls.Main:GetSizeY() - SIZE_HEIGHT_PADDING_BOTTOM_ADJUST );
-- Remember this tab when report is next opened: ARISTOS
m_kCurrentTab = 6;
end
-- ===========================================================================
-- CURRENT DEALS PAGE
-- ===========================================================================
function ViewDealsPage()
ResetTabForNewPageContent();
for j, pDeal in spairs( m_kCurrentDeals, function( t, a, b ) return t[b].EndTurn > t[a].EndTurn end ) do
--print("deal", pDeal.EndTurn, Game.GetCurrentGameTurn(), pDeal.EndTurn-Game.GetCurrentGameTurn());
local iNumTurns:number = pDeal.EndTurn - Game.GetCurrentGameTurn();
--local turns = "turns"
--if ending == 1 then turns = "turn" end
local instance : table = NewCollapsibleGroupInstance()
instance.RowHeaderButton:SetText( Locale.Lookup("LOC_HUD_REPORTS_TRADE_DEAL_WITH")..pDeal.WithCivilization );
instance.RowHeaderLabel:SetText( tostring(iNumTurns).." "..Locale.Lookup("LOC_HUD_REPORTS_TURNS_UNTIL_COMPLETED", iNumTurns).." ("..tostring(pDeal.EndTurn)..")" );
instance.RowHeaderLabel:SetHide( false );
instance.AmenitiesContainer:SetHide(true);
instance.IndustryContainer:SetHide(true); -- 2021-05-21
instance.MonopolyContainer:SetHide(true); -- 2021-05-21
local dealHeaderInstance : table = {}
ContextPtr:BuildInstanceForControl( "DealsHeader", dealHeaderInstance, instance.ContentStack )
local iSlots = #pDeal.Sending
if iSlots < #pDeal.Receiving then iSlots = #pDeal.Receiving end
for i = 1, iSlots do
local dealInstance : table = {}
ContextPtr:BuildInstanceForControl( "DealsInstance", dealInstance, instance.ContentStack )
table.insert( instance.Children, dealInstance )
end
for i, pDealItem in pairs( pDeal.Sending ) do
if pDealItem.Icon then
instance.Children[i].Outgoing:SetText( pDealItem.Icon .. " " .. pDealItem.Name )
else
instance.Children[i].Outgoing:SetText( pDealItem.Name )
end
end
for i, pDealItem in pairs( pDeal.Receiving ) do
if pDealItem.Icon then
instance.Children[i].Incoming:SetText( pDealItem.Icon .. " " .. pDealItem.Name )
else
instance.Children[i].Incoming:SetText( pDealItem.Name )
end
end
local pFooterInstance:table = {}
ContextPtr:BuildInstanceForControl( "DealsFooterInstance", pFooterInstance, instance.ContentStack )
pFooterInstance.Outgoing:SetText( Locale.Lookup("LOC_HUD_REPORTS_TOTALS")..#pDeal.Sending )
pFooterInstance.Incoming:SetText( Locale.Lookup("LOC_HUD_REPORTS_TOTALS")..#pDeal.Receiving )
SetGroupCollapsePadding( instance, pFooterInstance.Top:GetSizeY() )
RealizeGroup( instance );
end
Controls.Stack:CalculateSize();
Controls.Scroll:CalculateSize();
Controls.CollapseAll:SetHide( false );
Controls.BottomYieldTotals:SetHide( true );
Controls.BottomResourceTotals:SetHide( true );
Controls.BottomPoliciesFilters:SetHide( true );
Controls.BottomMinorsFilters:SetHide( true );
Controls.Scroll:SetSizeY( Controls.Main:GetSizeY() - SIZE_HEIGHT_PADDING_BOTTOM_ADJUST);
-- Remember this tab when report is next opened: ARISTOS
m_kCurrentTab = 5;
end
-- ===========================================================================
-- POLICY PAGE
-- ===========================================================================
local tPolicyOrder:table = {
SLOT_MILITARY = 1,
SLOT_ECONOMIC = 2,
SLOT_DIPLOMATIC = 3,
SLOT_GREAT_PERSON = 4,
SLOT_WILDCARD = 5,
SLOT_DARKAGE = 6,
SLOT_PANTHEON = 7,
SLOT_FOLLOWER = 8,
};
local tPolicyGroupNames:table = {};
function InitializePolicyData()
-- Compatbility tweak for mods adding new slot types (e.g. Rule with Faith)
for row in GameInfo.GovernmentSlots() do
if tPolicyOrder[row.GovernmentSlotType] == nil and row.GovernmentSlotType ~= "SLOT_WILDCARD" then
tPolicyOrder[row.GovernmentSlotType] = table.count(tPolicyOrder) + 1;
end
end
-- init group names
for slot,_ in pairs(tPolicyOrder) do
tPolicyGroupNames[ slot ] = Locale.Lookup( string.gsub(slot, "SLOT_", "LOC_GOVT_POLICY_TYPE_") );
end
-- exceptions
tPolicyGroupNames.SLOT_GREAT_PERSON = Locale.Lookup("LOC_PEDIA_GOVERNMENTS_PAGEGROUP_GREATPEOPLE_POLICIES_NAME");
tPolicyGroupNames.SLOT_PANTHEON = Locale.Lookup("LOC_PEDIA_RELIGIONS_PAGEGROUP_PANTHEON_BELIEFS_NAME");
tPolicyGroupNames.SLOT_FOLLOWER = Locale.Lookup("LOC_PEDIA_RELIGIONS_PAGEGROUP_FOLLOWER_BELIEFS_NAME");
-- Rise & Fall
if not (bIsRiseFall or bIsGatheringStorm) then
--tPolicyOrder.SLOT_WILDCARD = nil; -- 2019-01-26: Nubia Scenario uses SLOT_WILDCARD
tPolicyOrder.SLOT_DARKAGE = nil;
end
--print("*** POLICY ORDER ***"); dshowtable(tPolicyOrder);
--print("*** POLICY GROUP NAMES ***"); dshowtable(tPolicyGroupNames);
end
function UpdatePolicyData()
--print("*** UPDATE POLICY DATA ***");
Timer1Start();
m_kPolicyData = {}; for slot,_ in pairs(tPolicyOrder) do m_kPolicyData[slot] = {}; end -- reset all data
local ePlayerID:number = Game.GetLocalPlayer();
local pPlayer:table = Players[ePlayerID];
if not pPlayer then return; end -- assert
local pPlayerCulture:table = pPlayer:GetCulture();
-- find out which polices are slotted now
local tSlottedPolicies:table = {};
for i = 0, pPlayerCulture:GetNumPolicySlots()-1 do
if pPlayerCulture:GetSlotPolicy(i) ~= -1 then tSlottedPolicies[ pPlayerCulture:GetSlotPolicy(i) ] = true; end
end
--print("...Slotted policies"); dshowtable(tSlottedPolicies);
-- iterate through all policies
for policy in GameInfo.Policies() do
local policyData:table = {
Index = policy.Index,
Name = Locale.Lookup(policy.Name),
Description = Locale.Lookup(policy.Description),
--Yields from modifiers
-- Status TODO from Player:GetCulture?
IsActive = (pPlayerCulture:IsPolicyUnlocked(policy.Index) and not pPlayerCulture:IsPolicyObsolete(policy.Index)),
IsSlotted = ((tSlottedPolicies[ policy.Index ] and true) or false),
};
--print("Policy:", policy.Index, policy.PolicyType, policy.GovernmentSlotType, "active/slotted", policyData.IsActive, policyData.IsSlotted);
-- dshowtable(policyData); -- !!!BUG HERE with Aesthetics CTD!!! Also with CRAFTSMEN, could be others - DON'T USE
local sSlotType:string = policy.GovernmentSlotType;
if sSlotType == "SLOT_WILDCARD" then --sSlotType = ((policy.RequiresGovernmentUnlock and "SLOT_WILDCARD") or "SLOT_DARKAGE"); end
-- 2019-01-26: Better check for Dark Age policies
if GameInfo.Policies_XP1 ~= nil and GameInfo.Policies_XP1[policy.PolicyType] ~= nil then sSlotType = "SLOT_DARKAGE"; end
end
--print("...inserting policy", policyData.Name, "into", sSlotType);
table.insert(m_kPolicyData[sSlotType], policyData);
-- policy impact from modifiers
policyData.Impact, policyData.Yields, policyData.ImpactToolTip, policyData.UnknownEffect = RMA.CalculateModifierEffect("Policy", policy.PolicyType, ePlayerID, nil);
policyData.IsImpact = false; -- for toggling options
for _,value in pairs(policyData.Yields) do if value ~= 0 then policyData.IsImpact = true; break; end end
end
-- iterate through all beliefs
for belief in GameInfo.Beliefs() do
if belief.BeliefClassType == "BELIEF_CLASS_PANTHEON" or belief.BeliefClassType == "BELIEF_CLASS_FOLLOWER" then
local policyData:table = {
Index = belief.Index,
Name = Locale.Lookup(belief.Name),
Description = Locale.Lookup(belief.Description),
--Yields from modifiers
-- Status TODO from Player:GetCulture?
IsActive = true, -- not used by pantheons
IsSlotted = ( pPlayer:GetReligion():GetPantheon() == belief.Index ),
};
local sSlotType:string = string.gsub(belief.BeliefClassType, "BELIEF_CLASS_", "SLOT_");
--print("...inserting belief", policyData.Name, "into", sSlotType);
table.insert(m_kPolicyData[sSlotType], policyData);
-- belief impact from modifiers
policyData.Impact, policyData.Yields, policyData.ImpactToolTip, policyData.UnknownEffect = RMA.CalculateModifierEffect("Belief", belief.BeliefType, ePlayerID, nil);
policyData.IsImpact = false; -- for toggling options
for _,value in pairs(policyData.Yields) do if value ~= 0 then policyData.IsImpact = true; break; end end
end -- pantheons
end -- all beliefs
Timer1Tick("--- ALL POLICY DATA ---");
--for policyGroup,policies in pairs(m_kPolicyData) do print(policyGroup, table.count(policies)); end
end
function ViewPolicyPage()
--print("FUN ViewPolicyPage");
ResetTabForNewPageContent();
-- fill
--for iUnitGroup, kUnitGroup in spairs( m_kUnitDataReport, function( t, a, b ) return t[b].ID > t[a].ID end ) do
--for policyGroup,policies in pairs(m_kPolicyData) do
for policyGroup,policies in spairs( m_kPolicyData, function(t,a,b) return tPolicyOrder[a] < tPolicyOrder[b]; end ) do -- simple sort by group code name
--print("PolicyGroup:", policyGroup);
local instance : table = NewCollapsibleGroupInstance()
instance.RowHeaderButton:SetText( tPolicyGroupNames[policyGroup] );
instance.RowHeaderLabel:SetHide( false );
instance.AmenitiesContainer:SetHide(true);
instance.IndustryContainer:SetHide(true); -- 2021-05-21
instance.MonopolyContainer:SetHide(true); -- 2021-05-21
local pHeaderInstance:table = {}
ContextPtr:BuildInstanceForControl( "PolicyHeaderInstance", pHeaderInstance, instance.ContentStack ) -- instance ID, pTable, stack
if policyGroup == "SLOT_PANTHEON" or policyGroup == "SLOT_FOLLOWER" then pHeaderInstance.PolicyHeaderLabelName:SetText( Locale.Lookup("LOC_BELIEF_NAME") ); end
local iNumRows:number = 0;
pHeaderInstance.PolicyHeaderButtonLOYALTY:SetHide( not (bIsRiseFall or bIsGatheringStorm) );
-- set sorting callbacks
--if pHeaderInstance.UnitTypeButton then pHeaderInstance.UnitTypeButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "type", iUnitGroup, instance ) end ) end
--if pHeaderInstance.UnitNameButton then pHeaderInstance.UnitNameButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "name", iUnitGroup, instance ) end ) end
--if pHeaderInstance.UnitStatusButton then pHeaderInstance.UnitStatusButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "status", iUnitGroup, instance ) end ) end
-- fill a single group
--for _,policy in ipairs(policies) do
for _,policy in spairs( policies, function(t,a,b) return t[a].Name < t[b].Name; end ) do -- sort by name
--print("Policy:", policy.Name);
--dshowtable(policy);
--FILTERS
if (not Controls.HideInactivePoliciesCheckbox:IsSelected() or policy.IsActive) and
(not Controls.HideNoImpactPoliciesCheckbox:IsSelected() or policy.IsImpact) then
local pPolicyInstance:table = {}
--table.insert( instance.Children, unitInstance )
ContextPtr:BuildInstanceForControl( "PolicyEntryInstance", pPolicyInstance, instance.ContentStack ) -- instance ID, pTable, stack
pPolicyInstance.PolicyEntryYieldLOYALTY:SetHide( not (bIsRiseFall or bIsGatheringStorm) );
iNumRows = iNumRows + 1;
--common_unit_fields( unit, unitInstance ) -- fill a single entry
-- status with tooltip
local sStatusText:string;
local sStatusToolTip:string = "Id "..tostring(policy.Index);
if policy.IsActive then sStatusText = "[ICON_CheckSuccess]"; sStatusToolTip = sStatusToolTip.." Active policy";
else sStatusText = "[ICON_CheckFail]"; sStatusToolTip = sStatusToolTip.." Inactive policy (obsolete or not yet unlocked)"; end
--print("...status", sStatusText);
pPolicyInstance.PolicyEntryStatus:SetText(sStatusText);
--pPolicyInstance.PolicyEntryStatus:SetToolTipString(sStatusToolTip);
-- name with description
local sPolicyName:string = policy.Name;
if policy.IsSlotted then sPolicyName = "[ICON_Checkmark]"..sPolicyName; end
--print("...description", policy.Description);
TruncateString(pPolicyInstance.PolicyEntryName, 278, sPolicyName); -- [ICON_Checkmark] [ICON_CheckSuccess] [ICON_CheckFail] [ICON_CheckmarkBlue]
pPolicyInstance.PolicyEntryName:SetToolTipString(policy.Description);
-- impact with modifiers
local sPolicyImpact:string = ( policy.Impact == "" and "[ICON_CheckmarkBlue]" ) or policy.Impact;
if policy.UnknownEffect then sPolicyImpact = sPolicyImpact.." [COLOR_Red]!"; end
--print("...impact", sPolicyImpact);
TruncateString(pPolicyInstance.PolicyEntryImpact, 218, sPolicyImpact);
--print("...tooltip", sStatusToolTip, policy.ImpactToolTip);
--print("...tooltip", sStatusToolTip..TOOLTIP_SEP_NEWLINE..policy.ImpactToolTip);
if bOptionModifiers then pPolicyInstance.PolicyEntryImpact:SetToolTipString(sStatusToolTip..TOOLTIP_SEP_NEWLINE..policy.ImpactToolTip); end
--print("Yields:");
-- fill out yields
for yield,value in pairs(policy.Yields) do
--print("...yield,value", yield, value);
if value ~= 0 then pPolicyInstance["PolicyEntryYield"..yield]:SetText(toPlusMinusNoneString(value)); end
end
end -- FILTERS
end
instance.RowHeaderLabel:SetText( Locale.Lookup("LOC_HUD_REPORTS_TOTALS").." "..tostring(iNumRows) );
-- no footer
SetGroupCollapsePadding(instance, 0 );
RealizeGroup( instance );
end
-- finishing
Controls.Stack:CalculateSize();
Controls.Scroll:CalculateSize();
Controls.CollapseAll:SetHide( false );
Controls.BottomYieldTotals:SetHide( true );
Controls.BottomResourceTotals:SetHide( true );
Controls.BottomPoliciesFilters:SetHide( false ); -- ViewPolicyPage
Controls.BottomMinorsFilters:SetHide( true );
Controls.Scroll:SetSizeY( Controls.Main:GetSizeY() - (Controls.BottomPoliciesFilters:GetSizeY() + SIZE_HEIGHT_PADDING_BOTTOM_ADJUST ) );
-- Remember this tab when report is next opened: ARISTOS
m_kCurrentTab = 7;
end
-- ===========================================================================
-- MINORS PAGE
-- ===========================================================================
-- helper to get Category out of Civ Type; categories are: CULTURAL, INDUSTRIAL, MILITARISTIC, etc.
function GetCityStateCategory(sCivType:string)
for row in GameInfo.TypeProperties() do
if row.Type == sCivType and row.Name == "CityStateCategory" then return row.Value; end
end
print("ERROR: GetCityStateCategory() no City State category for", sCivType);
return "UNKNOWN";
end
-- helper to get a Leader for a Minor; assumes only 1 leader per Minor
function GetCityStateLeader(sCivType:string)
for row in GameInfo.CivilizationLeaders() do
if row.CivilizationType == sCivType then return row.LeaderType; end
end
print("ERROR: GetCityStateLeader() no City State leader for", sCivType);
return "UNKNOWN";
end
-- helper to get a Trait for a Minor Leader; assumes only 1 trait per Minor Leader
function GetCityStateTrait(sLeaderType:string)
for row in GameInfo.LeaderTraits() do
if row.LeaderType == sLeaderType then return row.TraitType; end
end
print("ERROR: GetCityStateTrait() no Trait for", sLeaderType);
return "UNKNOWN";
end
function UpdateMinorData()
--print("*** UPDATE MINOR DATA ***");
Timer1Start();
local tMinorBonuses:table = {}; -- helper table to quickly access bonuses
-- prepare empty categories
m_kMinorData = {};
for row in GameInfo.TypeProperties() do
if row.Name == "CityStateCategory" and m_kMinorData[ row.Value ] == nil then
m_kMinorData[ row.Value ] = {};
tMinorBonuses[ row.Value ] = {};
end
end
-- 2019-01-26: Australia scenario removes entries from TypeProperties but still uses those Categories
for leader in GameInfo.Leaders() do
if leader.InheritFrom == "LEADER_MINOR_CIV_DEFAULT" then
local sCategory:string = string.gsub(leader.LeaderType, "LEADER_MINOR_CIV_", "");
if m_kMinorData[ sCategory ] == nil then
print("WARNING: UpdateMinorData() LeaderType", leader.LeaderType, "uses category that doesn't exist in TypeProperties; registering", sCategory);
m_kMinorData[ sCategory ] = {};
tMinorBonuses[ sCategory ] = {};
end
end
end
--print("*** Minors in TypeProperties ***"); dshowrectable(m_kMinorData); -- debug
-- find out our level of involvement with alive Minors
local tMinorRelations:table = {};
local ePlayerID:number = Game.GetLocalPlayer();
for _,minor in ipairs(PlayerManager.GetAliveMinors()) do
-- we need to check for City State actually, because Free Cities are considered Minors as well
if minor:IsMinor() then -- CIVILIZATION_LEVEL_CITY_STATE
local minorRelation:table = {
CivType = PlayerConfigurations[minor:GetID()]:GetCivilizationTypeName(), -- CIVILIZATION_VILNIUS
LeaderType = PlayerConfigurations[minor:GetID()]:GetLeaderTypeName(), -- LEADER_MINOR_CIV_VILNIUS
IsSuzerained = ( minor:GetInfluence():GetSuzerain() == ePlayerID ), -- boolean
NumTokens = minor:GetInfluence():GetTokensReceived(ePlayerID),
HasMet = minor:GetDiplomacy():HasMet(ePlayerID),
--HasMet = Players[ePlayerID]:GetDiplomacy():HasMet(minor:GetID()),
};
tMinorRelations[ minorRelation.CivType ] = minorRelation;
end
end
--print("*** Relations with Alive Minors ***"); dshowrectable(tMinorRelations);
-- iterate through all Minors
-- assumptions: no Civilization Traits are used, only Leader Traits; each has 1 leader; main leader is for Suzerain bonus; Inherited leaders are for small/medium/large bonuses
-- first, fill out Inherited leaders
for leader in GameInfo.Leaders() do
if leader.InheritFrom == "LEADER_MINOR_CIV_DEFAULT" then
local sCategory:string = string.gsub(leader.LeaderType, "LEADER_MINOR_CIV_", "");
local function RegisterLeaderForInfluence(iNumTokens:number, sInfluence:string)
local minorData:table = {
--Index = civ.Index,
CivType = leader.LeaderType,
Category = sCategory,
Name = Locale.Lookup("LOC_MINOR_CIV_"..sInfluence.."_INFLUENCE_ENVOYS"), -- unfortunately this is all hardcoded in LOCs, [ICON_Envoy]
LeaderType = leader.LeaderType,
Description = Locale.Lookup("LOC_MINOR_CIV_"..sCategory.."_TRAIT_"..sInfluence.."_INFLUENCE_BONUS"), -- unfortunately this is all hardcoded in LOCs
NumTokens = iNumTokens, -- required number of envoys to achieve this influence level
Trait = GetCityStateTrait(leader.LeaderType),
Influence = 0, -- this will hold number of City States that with this influence level
IsSuzerained = false, -- not used
HasMet = false, -- will be true if any of that category has been met
--Yields from modifiers
};
--print("registering leader", iNumTokens, sInfluence); dshowtable(minorData);
-- impact from modifiers; the 5th parameter is used to select proper modifiers, it is the ONLY place where it is used
minorData.Impact, minorData.Yields, minorData.ImpactToolTip, minorData.UnknownEffect = RMA.CalculateModifierEffect("Trait", minorData.Trait, ePlayerID, nil, sInfluence);
minorData.IsImpact = false; -- for toggling options
for _,value in pairs(minorData.Yields) do if value ~= 0 then minorData.IsImpact = true; break; end end
-- done!
table.insert(m_kMinorData[ minorData.Category ], minorData);
tMinorBonuses[ minorData.Category ][ iNumTokens ] = minorData;
end
-- we will have to actually triple this
RegisterLeaderForInfluence(1, "SMALL"); -- unfortunately this is all hardcoded in LOCs
RegisterLeaderForInfluence(3, "MEDIUM");
RegisterLeaderForInfluence(6, "LARGE");
end
end
--dshowrectable(tMinorBonuses); -- debug
-- OK UP TO THIS POINT
-- second, fill out Main leaders
for civ in GameInfo.Civilizations() do
if civ.StartingCivilizationLevelType == "CIVILIZATION_LEVEL_CITY_STATE" then
local minorData:table = {
--Index = civ.Index,
CivType = civ.CivilizationType,
Category = GetCityStateCategory(civ.CivilizationType),
Name = Locale.Lookup(civ.Name),
LeaderType = GetCityStateLeader(civ.CivilizationType),
Description = "", -- later
NumTokens = 0, -- always 0
Trait = "", -- later
Influence = 0, -- this will hold number of envoys sent to this CS
IsSuzerained = false, -- later
HasMet = false, -- later
--Yields from modifiers
};
--print("*** Found CS ***"); dshowtable(minorData);
minorData.Trait = GetCityStateTrait(minorData.LeaderType);
local tMinorRelation:table = tMinorRelations[ civ.CivilizationType ];
if tMinorRelation ~= nil then
minorData.Influence = tMinorRelation.NumTokens;
minorData.IsSuzerained = tMinorRelation.IsSuzerained;
minorData.HasMet = tMinorRelation.HasMet;
-- register in bonuses
for _,bonus in pairs(tMinorBonuses[minorData.Category]) do
if minorData.Influence >= bonus.NumTokens then bonus.Influence = bonus.Influence + 1; end
if minorData.HasMet then bonus.HasMet = true; end
end
end
-- description is actually a suzerain bonus descripion
-- it can contain many lines, from many Traits
local tStr:table = {};
for row in GameInfo.LeaderTraits() do
if row.LeaderType == minorData.LeaderType then
local sLeaderTrait:string = row.TraitType;
for trait in GameInfo.Traits() do
if trait.TraitType == sLeaderTrait and not trait.InternalOnly then table.insert(tStr, Locale.Lookup(trait.Description)); end
end
end
end
if #tStr == 0 then print("WARNING: UpdateMinorData() no traits for", minorData.Name); end
minorData.Description = table.concat(tStr, "[NEWLINE]");
--print("=== before RMA ===");
-- impact from modifiers
minorData.Impact, minorData.Yields, minorData.ImpactToolTip, minorData.UnknownEffect = RMA.CalculateModifierEffect("Trait", minorData.Trait, ePlayerID, nil);
--print("=== after RMA ===");
minorData.IsImpact = false; -- for toggling options
for _,value in pairs(minorData.Yields) do if value ~= 0 then minorData.IsImpact = true; break; end end
-- done!
--print("*** Inserting CS ***"); dshowtable(minorData);
table.insert(m_kMinorData[ minorData.Category ], minorData);
end -- level City State
end -- all civs
Timer1Tick("--- ALL MINOR DATA ---");
--dshowrectable(m_kMinorData);
end
function ViewMinorPage()
ResetTabForNewPageContent();
for minorGroup,minors in spairs( m_kMinorData, function(t,a,b) return a < b; end ) do -- simple sort by group code name
local instance : table = NewCollapsibleGroupInstance()
instance.RowHeaderButton:SetText( Locale.Lookup("LOC_CITY_STATES_TYPE_"..minorGroup) );
instance.RowHeaderLabel:SetHide( false );
instance.AmenitiesContainer:SetHide(true);
instance.IndustryContainer:SetHide(true); -- 2021-05-21
instance.MonopolyContainer:SetHide(true); -- 2021-05-21
local pHeaderInstance:table = {}
ContextPtr:BuildInstanceForControl( "PolicyHeaderInstance", pHeaderInstance, instance.ContentStack ) -- instance ID, pTable, stack
pHeaderInstance.PolicyHeaderLabelName:SetText( Locale.Lookup("LOC_HUD_REPORTS_CITY_STATE") );
local iNumRows:number = 0;
pHeaderInstance.PolicyHeaderButtonLOYALTY:SetHide( not (bIsRiseFall or bIsGatheringStorm) );
-- set sorting callbacks
--if pHeaderInstance.UnitTypeButton then pHeaderInstance.UnitTypeButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "type", iUnitGroup, instance ) end ) end
--if pHeaderInstance.UnitNameButton then pHeaderInstance.UnitNameButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "name", iUnitGroup, instance ) end ) end
--if pHeaderInstance.UnitStatusButton then pHeaderInstance.UnitStatusButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_units( "status", iUnitGroup, instance ) end ) end
-- fill a single group
--for _,policy in ipairs(policies) do
for _,minor in spairs( minors, function(t,a,b) return t[a].Name < t[b].Name; end ) do -- sort by name
--FILTERS
if (not Controls.HideNotMetMinorsCheckbox:IsSelected() or minor.HasMet) and
(not Controls.HideNoImpactMinorsCheckbox:IsSelected() or minor.IsImpact) then
local pMinorInstance:table = {}
ContextPtr:BuildInstanceForControl( "PolicyEntryInstance", pMinorInstance, instance.ContentStack ) -- instance ID, pTable, stack
pMinorInstance.PolicyEntryYieldLOYALTY:SetHide( not (bIsRiseFall or bIsGatheringStorm) );
if minor.NumTokens == 0 then iNumRows = iNumRows + 1; end
-- status with tooltip
local sStatusText:string = "";
local sStatusToolTip:string = "";
if minor.Influence > 0 then sStatusText = "[ICON_CheckSuccess]"; sStatusToolTip = Locale.Lookup("LOC_ENVOY_NAME"); end
if minor.IsSuzerained then sStatusText = "[ICON_Checkmark]"; sStatusToolTip = Locale.Lookup("LOC_CITY_STATES_SUZERAIN"); end
pMinorInstance.PolicyEntryStatus:SetText(sStatusText);
pMinorInstance.PolicyEntryStatus:SetToolTipString(sStatusToolTip);
-- name with description
local sMinorName:string = minor.Name;
if minor.HasMet and minor.NumTokens == 0 then sMinorName = "[ICON_Capital]"..sMinorName; end
if minor.NumTokens > 0 then sMinorName = sMinorName.." "..tostring(minor.Influence);
elseif minor.Influence > 0 then sMinorName = sMinorName.." [COLOR_White]"..tostring(minor.Influence).."[ENDCOLOR] [ICON_Envoy]"; end
TruncateString(pMinorInstance.PolicyEntryName, 278, sMinorName); -- [ICON_Checkmark] [ICON_CheckSuccess] [ICON_CheckFail] [ICON_CheckmarkBlue]
pMinorInstance.PolicyEntryName:SetToolTipString(minor.Description);
-- impact with modifiers
local sMinorImpact:string = ( minor.Impact == "" and "[ICON_CheckmarkBlue]" ) or minor.Impact;
if minor.UnknownEffect then sMinorImpact = sMinorImpact.." [COLOR_Red]!"; end
-- this plugin shows actual impact as an additional info; only for influence bonuses
if minor.NumTokens > 0 then
local tActualYields:table = {};
for yield,value in pairs(minor.Yields) do tActualYields[yield] = value * minor.Influence; end
local sActualInfo:string = RMA.YieldTableGetInfo(tActualYields);
if sActualInfo ~= "" then sMinorImpact = sMinorImpact.." ("..sActualInfo..")"; end
end
TruncateString(pMinorInstance.PolicyEntryImpact, 218, sMinorImpact);
if bOptionModifiers then pMinorInstance.PolicyEntryImpact:SetToolTipString(minor.CivType.." / "..minor.LeaderType.."[NEWLINE]"..minor.Trait..TOOLTIP_SEP_NEWLINE..minor.ImpactToolTip); end
-- fill out yields
for yield,value in pairs(minor.Yields) do
if value ~= 0 then pMinorInstance["PolicyEntryYield"..yield]:SetText(toPlusMinusNoneString(value)); end
end
end -- FILTERS
end
instance.RowHeaderLabel:SetText( Locale.Lookup("LOC_HUD_REPORTS_TOTALS").." "..tostring(iNumRows) );
-- no footer
SetGroupCollapsePadding(instance, 0);
RealizeGroup( instance );
end
-- finishing
Controls.Stack:CalculateSize();
Controls.Scroll:CalculateSize();
Controls.CollapseAll:SetHide( false );
Controls.BottomYieldTotals:SetHide( true );
Controls.BottomResourceTotals:SetHide( true );
Controls.BottomPoliciesFilters:SetHide( true );
Controls.BottomMinorsFilters:SetHide( false ); -- ViewMinorPage
Controls.Scroll:SetSizeY( Controls.Main:GetSizeY() - (Controls.BottomMinorsFilters:GetSizeY() + SIZE_HEIGHT_PADDING_BOTTOM_ADJUST ) );
-- Remember this tab when report is next opened: ARISTOS
m_kCurrentTab = 8;
end
-- ===========================================================================
-- CITIES 2 PAGE - GATHERING STORM
-- ===========================================================================
-- helpers
function city2_fields( kCityData, pCityInstance )
local function ColorRed(text) return("[COLOR_Red]"..tostring(text).."[ENDCOLOR]"); end -- Infixo: helper
local function ColorGreen(text) return("[COLOR_Green]"..tostring(text).."[ENDCOLOR]"); end -- Infixo: helper
local function ColorWhite(text) return("[COLOR_White]"..tostring(text).."[ENDCOLOR]"); end -- Infixo: helper
local sText:string = "";
local tToolTip:table = {};
-- Status
--if kCityData.IsNuclearRisk then
--sText = sText.."[ICON_RESOURCE_URANIUM]"; table.insert(tToolTip, Locale.Lookup("LOC_EMERGENCY_NAME_NUCLEAR"));
--end
--if kCityData.IsUnderpowered then
--sText = sText.."[ICON_PowerInsufficient]"; table.insert(tToolTip, Locale.Lookup("LOC_POWER_STATUS_UNPOWERED_NAME"));
--end
pCityInstance.Status:SetText( sText );
pCityInstance.Status:SetToolTipString( table.concat(tToolTip, "[NEWLINE]") );
-- Icon
-- not used
-- CityName
TruncateStringWithTooltip(pCityInstance.CityName, 178, (kCityData.IsCapital and "[ICON_Capital]" or "")..Locale.Lookup(kCityData.CityName));
-- Population
pCityInstance.Population:SetText(ColorWhite(kCityData.Population));
pCityInstance.Population:SetToolTipString("");
-- Power consumption [icon required_number / consumed_number]
pCityInstance.PowerConsumed:SetText(string.format("%s %s / %s",
kCityData.PowerIcon,
kCityData.PowerRequired > 0 and ColorWhite(kCityData.PowerRequired) or tostring(kCityData.PowerRequired),
kCityData.IsUnderpowered and ColorRed(kCityData.PowerConsumed) or tostring(kCityData.PowerConsumed)));
pCityInstance.PowerConsumed:SetToolTipString(kCityData.PowerConsumedTT);
-- Power produced [number]
pCityInstance.PowerProduced:SetText(string.format("[ICON_%s] %d", kCityData.PowerPlantResType, kCityData.PowerProduced));
pCityInstance.PowerProduced:SetToolTipString(kCityData.PowerProducedTT);
-- CO2 footprint [resource number]
--if kCityData.CO2Footprint > 0 then
pCityInstance.CO2Footprint:SetText(string.format("[ICON_%s] %.1f", kCityData.PowerPlantResType, kCityData.CO2Footprint));
pCityInstance.CO2Footprint:SetToolTipString(kCityData.CO2FootprintTT);
--else
--pCityInstance.CO2Footprint:SetText("0");
--pCityInstance.CO2Footprint:SetToolTipString(kCityData.CO2FootprintTT);
--end
-- Nuclear power plant [nuclear icon / num turns]
if kCityData.HasNuclearPowerPlant then sText = kCityData.NuclearAccidentIcon.."[ICON_RESOURCE_URANIUM]"..ColorWhite(kCityData.ReactorAge);
else sText = "[ICON_Bullet]"; end
pCityInstance.NuclearPowerPlant:SetText(sText);
pCityInstance.NuclearPowerPlant:SetToolTipString(kCityData.NuclearPowerPlantTT);
-- Dam district & Flood info [num tiles / dam icon]
sText = tostring(kCityData.NumRiverFloodTiles);
if kCityData.HasDamDistrict then sText = sText.." [ICON_Checkmark]"; end
pCityInstance.RiverFloodDam:SetText(sText);
pCityInstance.RiverFloodDam:SetToolTipString(kCityData.RiverFloodDamTT);
-- Info about Flood barrier. [num tiles / flood barrier icon]
sText = tostring(kCityData.NumFloodTiles);
if kCityData.HasFloodBarrier then sText = sText.." [ICON_Checkmark]"; end
pCityInstance.FloodBarrier:SetText(sText);
pCityInstance.FloodBarrier:SetToolTipString(kCityData.FloodTilesTT);
-- Flood Barrier Per turn maintenance [number]
pCityInstance.BarrierMaintenance:SetText(kCityData.HasFloodBarrier and ColorWhite(kCityData.FloodBarrierMaintenance) or tostring(kCityData.FloodBarrierMaintenance));
pCityInstance.BarrierMaintenance:SetToolTipString(kCityData.FloodBarrierMaintenanceTT);
-- Number of RR tiles in the city borders [number]
pCityInstance.Railroads:SetText(tostring(kCityData.NumRailroads));
pCityInstance.Railroads:SetToolTipString(kCityData.NumRailroadsTT);
-- Number of Canal districts [icons]
pCityInstance.Canals:SetText(string.rep("[ICON_DISTRICT_CANAL]", kCityData.NumCanals));
-- 2021-05-21 Monopolies and Corporations Mode
if bIsMonopolies then
pCityInstance.Industry:SetText(kCityData.Industry);
pCityInstance.Industry:SetToolTipString(kCityData.IndustryTT);
pCityInstance.Industry:SetHide(false);
else
pCityInstance.Industry:SetHide(true);
end
end
function sort_cities2( type, instance )
local i = 0
for _, kCityData in spairs( m_kCityData, function( t, a, b ) return city2_sortFunction( instance.Descend, type, t, a, b ); end ) do
i = i + 1
local cityInstance = instance.Children[i]
city2_fields( kCityData, cityInstance )
-- go to the city after clicking
cityInstance.GoToCityButton:RegisterCallback( Mouse.eLClick, function() Close(); UI.LookAtPlot( kCityData.City:GetX(), kCityData.City:GetY() ); UI.SelectCity( kCityData.City ); end );
cityInstance.GoToCityButton:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound( "Main_Menu_Mouse_Over" ); end );
end
end
function city2_sortFunction( descend, type, t, a, b )
local aCity = 0
local bCity = 0
if type == "name" then
aCity = Locale.Lookup( t[a].CityName );
bCity = Locale.Lookup( t[b].CityName );
elseif type == "pop" then
aCity = t[a].Population;
bCity = t[b].Population;
elseif type == "status" then
--if t[a].IsUnderpowered then aCity = aCity + 20; else aCity = aCity + 10; end
--if t[b].IsUnderpowered then bCity = bCity + 20; else bCity = bCity + 10; end
--if t[a].IsNuclearRisk then aCity = aCity + 20; else aCity = aCity + 10; end
--if t[b].IsNuclearRisk then bCity = bCity + 20; else bCity = bCity + 10; end
elseif type == "icon" then
-- not used
elseif type == "powcon" then
aCity = t[a].PowerRequired;
bCity = t[b].PowerRequired;
if aCity == bCity then
aCity = t[a].PowerConsumed;
bCity = t[b].PowerConsumed;
end
elseif type == "pwprod" then
aCity = t[a].PowerProduced;
bCity = t[b].PowerProduced;
elseif type == "co2" then
--aCity = t[a].CO2Footprint;
--bCity = t[b].CO2Footprint;
elseif type == "nuclear" then
aCity = t[a].ReactorAge;
bCity = t[b].ReactorAge;
elseif type == "dam" then
aCity = t[a].NumRiverFloodTiles;
bCity = t[b].NumRiverFloodTiles;
elseif type == "barrier" then
aCity = t[a].NumFloodTiles;
bCity = t[b].NumFloodTiles;
elseif type == "fbcost" then
aCity = t[a].FloodBarrierMaintenance;
bCity = t[b].FloodBarrierMaintenance;
elseif type == "numrr" then
aCity = t[a].NumRailroads;
bCity = t[b].NumRailroads;
else
-- nothing to do here
end
if descend then return bCity > aCity; else return bCity < aCity; end
end
function ViewCities2Page()
ResetTabForNewPageContent();
local instance:table = m_simpleIM:GetInstance();
instance.Top:DestroyAllChildren();
instance.Children = {}
instance.Descend = true
local pHeaderInstance:table = {};
ContextPtr:BuildInstanceForControl( "CityStatus2HeaderInstance", pHeaderInstance, instance.Top );
pHeaderInstance.CityStatusButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities2( "status", instance ) end )
pHeaderInstance.CityIconButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities2( "icon", instance ) end )
pHeaderInstance.CityNameButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities2( "name", instance ) end )
pHeaderInstance.CityPopulationButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities2( "pop", instance ) end )
pHeaderInstance.CityPowerConsumedButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities2( "powcon", instance ) end )
pHeaderInstance.CityPowerProducedButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities2( "pwprod", instance ) end )
--pHeaderInstance.CityCO2FootprintButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities2( "co2", instance ) end )
pHeaderInstance.CityNuclearPowerPlantButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities2( "nuclear", instance ) end )
pHeaderInstance.CityRiverFloodDamButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities2( "dam", instance ) end )
pHeaderInstance.CityFloodBarrierButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities2( "barrier", instance ) end )
pHeaderInstance.CityBarrierMaintenanceButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities2( "fbcost", instance ) end );
pHeaderInstance.CityRailroadsButton:RegisterCallback( Mouse.eLClick, function() instance.Descend = not instance.Descend; sort_cities2( "numrr", instance ) end );
pHeaderInstance.CityIndustryButton:SetHide(not bIsMonopolies);
--
for _, kCityData in spairs( m_kCityData, function( t, a, b ) return city2_sortFunction( true, "name", t, a, b ); end ) do -- initial sort by name ascending
local pCityInstance:table = {}
ContextPtr:BuildInstanceForControl( "CityStatus2EntryInstance", pCityInstance, instance.Top );
table.insert( instance.Children, pCityInstance );
city2_fields( kCityData, pCityInstance );
-- go to the city after clicking
pCityInstance.GoToCityButton:RegisterCallback( Mouse.eLClick, function() Close(); UI.LookAtPlot( kCityData.City:GetX(), kCityData.City:GetY() ); UI.SelectCity( kCityData.City ); end );
pCityInstance.GoToCityButton:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound( "Main_Menu_Mouse_Over" ); end );
end
Controls.Stack:CalculateSize();
Controls.Scroll:CalculateSize();
Controls.CollapseAll:SetHide( true );
Controls.BottomYieldTotals:SetHide( true );
Controls.BottomResourceTotals:SetHide( true );
Controls.BottomPoliciesFilters:SetHide( true );
Controls.BottomMinorsFilters:SetHide( true );
Controls.Scroll:SetSizeY( Controls.Main:GetSizeY() - SIZE_HEIGHT_PADDING_BOTTOM_ADJUST);
-- Remember this tab when report is next opened: ARISTOS
m_kCurrentTab = 9;
end
-- ===========================================================================
--
-- ===========================================================================
function AddTabSection( name:string, populateCallback:ifunction )
local kTab :table = m_tabIM:GetInstance();
kTab.Button[DATA_FIELD_SELECTION] = kTab.Selection;
local callback :ifunction = function()
if m_tabs.prevSelectedControl ~= nil then
m_tabs.prevSelectedControl[DATA_FIELD_SELECTION]:SetHide(true);
end
kTab.Selection:SetHide(false);
Timer1Start();
populateCallback();
Timer1Tick("Section "..Locale.Lookup(name).." populated");
end
kTab.Button:GetTextControl():SetText( Locale.Lookup(name) );
kTab.Button:SetSizeToText( 0, 20 ); -- default 40,20
kTab.Button:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end);
m_tabs.AddTab( kTab.Button, callback );
end
-- ===========================================================================
-- UI Callback
-- ===========================================================================
function OnInputHandler( pInputStruct:table )
local uiMsg :number = pInputStruct:GetMessageType();
if uiMsg == KeyEvents.KeyUp then
local uiKey = pInputStruct:GetKey();
if uiKey == Keys.VK_ESCAPE then
if ContextPtr:IsHidden()==false then
Close();
return true;
end
end
end
return false;
end
local m_ToggleReportsId:number = Input.GetActionId("ToggleReports");
--print("ToggleReports key is", m_ToggleReportsId);
function OnInputActionTriggered( actionId )
--print("FUN OnInputActionTriggered", actionId);
if actionId == m_ToggleReportsId then
--print(".....Detected F8.....")
if ContextPtr:IsHidden() then Open(); else Close(); end
end
end
-- ===========================================================================
function Resize()
local topPanelSizeY:number = 30;
x,y = UIManager:GetScreenSizeVal();
Controls.Main:SetSizeY( y - topPanelSizeY );
Controls.Main:SetOffsetY( topPanelSizeY * 0.5 );
end
-- ===========================================================================
-- Game Event Callback
-- ===========================================================================
function OnLocalPlayerTurnEnd()
if(GameConfiguration.IsHotseat()) then
OnCloseButton();
end
end
-- ===========================================================================
function LateInitialize()
--Resize(); -- June Patch
m_tabs = CreateTabs( Controls.TabContainer, 42, 34, UI.GetColorValueFromHexLiteral(0xFF331D05) );
--AddTabSection( "Test", ViewTestPage ); --TRONSTER debug
--AddTabSection( "Test2", ViewTestPage ); --TRONSTER debug
AddTabSection( "LOC_HUD_REPORTS_TAB_YIELDS", ViewYieldsPage );
AddTabSection( "LOC_HUD_REPORTS_TAB_RESOURCES", ViewResourcesPage );
AddTabSection( "LOC_HUD_REPORTS_TAB_CITIES", ViewCityStatusPage );
if GameCapabilities.HasCapability("CAPABILITY_GOSSIP_REPORT") then
AddTabSection( "LOC_HUD_REPORTS_TAB_GOSSIP", ViewGossipPage );
end
AddTabSection( "LOC_HUD_REPORTS_TAB_DEALS", ViewDealsPage );
AddTabSection( "LOC_HUD_REPORTS_TAB_UNITS", ViewUnitsPage );
AddTabSection( "LOC_HUD_REPORTS_TAB_POLICIES", ViewPolicyPage );
AddTabSection( "LOC_HUD_REPORTS_TAB_MINORS", ViewMinorPage );
if bIsGatheringStorm then AddTabSection( "LOC_HUD_REPORTS_TAB_CITIES2", ViewCities2Page ); end
m_tabs.SameSizedTabs(20);
m_tabs.CenterAlignTabs(-10);
end
-- ===========================================================================
-- UI Event
-- ===========================================================================
function OnInit( isReload:boolean )
LateInitialize();
if isReload then
if ContextPtr:IsHidden() == false then
Open();
end
end
m_tabs.AddAnimDeco(Controls.TabAnim, Controls.TabArrow);
end
-- ===========================================================================
-- CHECKBOXES
-- ===========================================================================
-- Checkboxes for hiding city details and free units/buildings
function OnToggleHideCityBuildings()
local isChecked = Controls.HideCityBuildingsCheckbox:IsSelected();
Controls.HideCityBuildingsCheckbox:SetSelected( not isChecked );
ViewYieldsPage()
end
function OnToggleHideFreeBuildings()
local isChecked = Controls.HideFreeBuildingsCheckbox:IsSelected();
Controls.HideFreeBuildingsCheckbox:SetSelected( not isChecked );
ViewYieldsPage()
end
function OnToggleHideFreeUnits()
local isChecked = Controls.HideFreeUnitsCheckbox:IsSelected();
Controls.HideFreeUnitsCheckbox:SetSelected( not isChecked );
ViewYieldsPage()
end
-- Checkboxes for different resources in Resources tab
function OnToggleStrategic()
local isChecked = Controls.StrategicCheckbox:IsSelected();
Controls.StrategicCheckbox:SetSelected( not isChecked );
ViewResourcesPage();
end
function OnToggleLuxury()
local isChecked = Controls.LuxuryCheckbox:IsSelected();
Controls.LuxuryCheckbox:SetSelected( not isChecked );
ViewResourcesPage();
end
function OnToggleBonus()
local isChecked = Controls.BonusCheckbox:IsSelected();
Controls.BonusCheckbox:SetSelected( not isChecked );
ViewResourcesPage();
end
-- Checkboxes for policy filters
function OnToggleInactivePolicies()
local isChecked = Controls.HideInactivePoliciesCheckbox:IsSelected();
Controls.HideInactivePoliciesCheckbox:SetSelected( not isChecked );
ViewPolicyPage();
end
function OnToggleNoImpactPolicies()
local isChecked = Controls.HideNoImpactPoliciesCheckbox:IsSelected();
Controls.HideNoImpactPoliciesCheckbox:SetSelected( not isChecked );
ViewPolicyPage();
end
-- Checkboxes for minors filters
function OnToggleNotMetMinors()
local isChecked = Controls.HideNotMetMinorsCheckbox:IsSelected();
Controls.HideNotMetMinorsCheckbox:SetSelected( not isChecked );
ViewMinorPage();
end
function OnToggleNoImpactMinors()
local isChecked = Controls.HideNoImpactMinorsCheckbox:IsSelected();
Controls.HideNoImpactMinorsCheckbox:SetSelected( not isChecked );
ViewMinorPage();
end
-- ===========================================================================
function Initialize()
InitializePolicyData();
-- UI Callbacks
ContextPtr:SetInitHandler( OnInit );
ContextPtr:SetInputHandler( OnInputHandler, true );
Events.UnitUpgraded.Add(
function()
if not tUnitSort.parent then return; end
-- refresh data and re-sort group which upgraded unit was from
m_kCityData, m_kCityTotalData, m_kResourceData, m_kUnitData, m_kDealData, m_kCurrentDeals, m_kUnitDataReport = GetData();
UpdatePolicyData();
UpdateMinorData();
sort_units( tUnitSort.type, tUnitSort.group, tUnitSort.parent );
end );
Controls.CloseButton:RegisterCallback( Mouse.eLClick, OnCloseButton );
Controls.CloseButton:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end);
Controls.CollapseAll:RegisterCallback( Mouse.eLClick, OnCollapseAllButton );
Controls.CollapseAll:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end);
--BRS Yields tab toggle
Controls.HideCityBuildingsCheckbox:RegisterCallback( Mouse.eLClick, OnToggleHideCityBuildings )
Controls.HideCityBuildingsCheckbox:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end )
Controls.HideCityBuildingsCheckbox:SetSelected( true );
Controls.HideFreeBuildingsCheckbox:RegisterCallback( Mouse.eLClick, OnToggleHideFreeBuildings )
Controls.HideFreeBuildingsCheckbox:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end )
Controls.HideFreeBuildingsCheckbox:SetSelected( true );
Controls.HideFreeUnitsCheckbox:RegisterCallback( Mouse.eLClick, OnToggleHideFreeUnits )
Controls.HideFreeUnitsCheckbox:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end )
Controls.HideFreeUnitsCheckbox:SetSelected( true );
--ARISTOS: Resources toggle
Controls.LuxuryCheckbox:RegisterCallback( Mouse.eLClick, OnToggleLuxury );
Controls.LuxuryCheckbox:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end );
Controls.LuxuryCheckbox:SetSelected( true );
Controls.StrategicCheckbox:RegisterCallback( Mouse.eLClick, OnToggleStrategic );
Controls.StrategicCheckbox:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end );
Controls.StrategicCheckbox:SetSelected( true );
Controls.BonusCheckbox:RegisterCallback( Mouse.eLClick, OnToggleBonus );
Controls.BonusCheckbox:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end );
Controls.BonusCheckbox:SetSelected( false ); -- not so important
-- Polices Filters
Controls.HideInactivePoliciesCheckbox:RegisterCallback( Mouse.eLClick, OnToggleInactivePolicies );
Controls.HideInactivePoliciesCheckbox:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end );
Controls.HideInactivePoliciesCheckbox:SetSelected( true );
Controls.HideNoImpactPoliciesCheckbox:RegisterCallback( Mouse.eLClick, OnToggleNoImpactPolicies );
Controls.HideNoImpactPoliciesCheckbox:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end );
Controls.HideNoImpactPoliciesCheckbox:SetSelected( false );
-- Minors Filters
Controls.HideNotMetMinorsCheckbox:RegisterCallback( Mouse.eLClick, OnToggleNotMetMinors );
Controls.HideNotMetMinorsCheckbox:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end );
Controls.HideNotMetMinorsCheckbox:SetSelected( true );
Controls.HideNoImpactMinorsCheckbox:RegisterCallback( Mouse.eLClick, OnToggleNoImpactMinors );
Controls.HideNoImpactMinorsCheckbox:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end );
Controls.HideNoImpactMinorsCheckbox:SetSelected( false );
-- Events
LuaEvents.TopPanel_OpenReportsScreen.Add( function() Open(); end );
LuaEvents.TopPanel_CloseReportsScreen.Add( function() Close(); end );
LuaEvents.ReportsList_OpenYields.Add( function() Open(1); end );
LuaEvents.ReportsList_OpenResources.Add( function() Open(2); end );
LuaEvents.ReportsList_OpenCityStatus.Add( function() Open(3); end );
if GameCapabilities.HasCapability("CAPABILITY_GOSSIP_REPORT") then
LuaEvents.ReportsList_OpenGossip.Add( function() Open(4); end );
end
LuaEvents.ReportsList_OpenDeals.Add( function() Open(5); end );
LuaEvents.ReportsList_OpenUnits.Add( function() Open(6); end );
LuaEvents.ReportsList_OpenPolicies.Add( function() Open(7); end );
LuaEvents.ReportsList_OpenMinors.Add( function() Open(8); end );
if bIsGatheringStorm then LuaEvents.ReportsList_OpenCities2.Add( function() Open(9); end ); end
Events.LocalPlayerTurnEnd.Add( OnLocalPlayerTurnEnd );
Events.InputActionTriggered.Add( OnInputActionTriggered );
end
Initialize();
print("OK loaded ReportScreen.lua from Better Report Screen");
|
local stringx = require('pl.stringx')
local cmd = torch.CmdLine()
cmd:option("-batch_size",128,"batch size")
cmd:option("-dimension",512,"vector dimensionality")
cmd:option("-dropout",0.2,"dropout rate")
cmd:option("-train_file","../data/t_given_s_train.txt","")
cmd:option("-dev_file","../data/t_given_s_dev.txt","")
cmd:option("-test_file","../data/t_given_s_test.txt","")
cmd:option("-init_weight",0.1,"")
cmd:option("-alpha",1,"")
cmd:option("-start_halve",6,"")
cmd:option("-max_length",100,"");
cmd:option("-vocab_source",25010,"")
cmd:option("-vocab_target",25010,"")
cmd:option("-thres",5,"gradient clipping thres")
cmd:option("-max_iter",8,"max number of iteration")
cmd:option("-source_max_length",50,"")
cmd:option("-target_max_length",50,"")
cmd:option("-layers",2,"")
cmd:option("-saveFolder","save","")
cmd:option("-reverse",false,"")
cmd:option("-gpu_index",1,"the index of GPU to use")
cmd:option("-saveModel",true,"")
cmd:option("-dictPath","../data/movie_25000","")
local params= cmd:parse(arg)
params.save_prefix=params.saveFolder.."/model"
params.save_params_file=params.saveFolder.."/params"
params.output_file=params.saveFolder.."/log"
paths.mkdir(params.saveFolder)
print(params)
return params;
|
local st = require "util.stanza";
module:depends("http");
local uuid_new = require "util.uuid".generate;
local os_time = os.time;
local t_remove = table.remove;
local add_task = require "util.timer".add_task;
local jid_bare = require "util.jid".bare;
local function get_room_from_jid() end;
local is_component = module:get_host_type() == "component";
if is_component then
local mod_muc = module:depends "muc";
local muc_rooms = rawget(mod_muc, "rooms");
get_room_from_jid = rawget(mod_muc, "get_room_from_jid") or
function (jid)
return muc_rooms[jid];
end
end
local utf8_pattern = "[\194-\244][\128-\191]*$";
local function drop_invalid_utf8(seq)
local start = seq:byte();
module:log("debug", "utf8: %d, %d", start, #seq);
if (start <= 223 and #seq < 2)
or (start >= 224 and start <= 239 and #seq < 3)
or (start >= 240 and start <= 244 and #seq < 4)
or (start > 244) then
return "";
end
return seq;
end
local function utf8_length(str)
local _, count = string.gsub(str, "[^\128-\193]", "");
return count;
end
local pastebin_private_messages = module:get_option_boolean("pastebin_private_messages", not is_component);
local length_threshold = module:get_option_number("pastebin_threshold", 500);
local line_threshold = module:get_option_number("pastebin_line_threshold", 4);
local max_summary_length = module:get_option_number("pastebin_summary_length", 150);
local html_preview = module:get_option_boolean("pastebin_html_preview", true);
local base_url = module:get_option_string("pastebin_url", module:http_url()):gsub("/$", "").."/";
-- Seconds a paste should live for in seconds (config is in hours), default 24 hours
local expire_after = math.floor(module:get_option_number("pastebin_expire_after", 24) * 3600);
local trigger_string = module:get_option_string("pastebin_trigger");
trigger_string = (trigger_string and trigger_string .. " ");
local pastes = {};
local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im";
local xmlns_xhtml = "http://www.w3.org/1999/xhtml";
function pastebin_text(text)
local uuid = uuid_new();
pastes[uuid] = { body = text, time = os_time(), };
pastes[#pastes+1] = uuid;
if not pastes[2] then -- No other pastes, give the timer a kick
add_task(expire_after, expire_pastes);
end
return base_url..uuid;
end
function handle_request(event, pasteid)
event.response.headers.content_type = "text/plain; charset=utf-8";
if not pasteid then
return "Invalid paste id, perhaps it expired?";
end
--module:log("debug", "Received request, replying: %s", pastes[pasteid].text);
local paste = pastes[pasteid];
if not paste then
return "Invalid paste id, perhaps it expired?";
end
return paste.body;
end
local function replace_tag(s, replacement)
local once = false;
s:maptags(function (tag)
if tag.name == replacement.name and tag.attr.xmlns == replacement.attr.xmlns then
if not once then
once = true;
return replacement;
else
return nil;
end
end
return tag;
end);
if not once then
s:add_child(replacement);
end
end
local line_count_pattern = string.rep("[^\n]*\n", line_threshold + 1):sub(1,-2);
function check_message(data)
local stanza = data.stanza;
-- Only check for MUC presence when loaded on a component.
if is_component then
local room = get_room_from_jid(jid_bare(stanza.attr.to));
if not room then return; end
local nick = room._jid_nick[stanza.attr.from];
if not nick then return; end
end
local body = stanza:get_child_text();
if not body then return; end
--module:log("debug", "Body(%s) length: %d", type(body), #(body or ""));
if ( #body > length_threshold and utf8_length(body) > length_threshold ) or
(trigger_string and body:find(trigger_string, 1, true) == 1) or
body:find(line_count_pattern) then
if trigger_string and body:sub(1, #trigger_string) == trigger_string then
body = body:sub(#trigger_string+1);
end
local url = pastebin_text(body);
module:log("debug", "Pasted message as %s", url);
--module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex]));
local summary = (body:sub(1, max_summary_length):gsub(utf8_pattern, drop_invalid_utf8) or ""):match("[^\n]+") or "";
summary = summary:match("^%s*(.-)%s*$");
local summary_prefixed = summary:match("[,:]$");
replace_tag(stanza, st.stanza("body"):text(summary .. "\n" .. url));
stanza:add_child(st.stanza("query", { xmlns = "jabber:iq:oob" }):tag("url"):text(url));
if html_preview then
local line_count = select(2, body:gsub("\n", "%0")) + 1;
local link_text = ("[view %spaste (%d line%s)]"):format(summary_prefixed and "" or "rest of ", line_count, line_count == 1 and "" or "s");
local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml });
html:tag("p"):text(summary.." "):up();
html:tag("a", { href = url }):text(link_text):up();
replace_tag(stanza, html);
end
end
end
module:hook("message/bare", check_message);
if pastebin_private_messages then
module:hook("message/full", check_message);
end
module:hook("muc-disco#info", function (event)
local reply, form, formdata = event.reply, event.form, event.formdata;
reply:tag("feature", { var = "https://modules.prosody.im/mod_pastebin" }):up();
table.insert(form, { name = "https://modules.prosody.im/mod_pastebin#max_lines", datatype = "xs:integer" });
table.insert(form, { name = "https://modules.prosody.im/mod_pastebin#max_characters", datatype = "xs:integer" });
formdata["https://modules.prosody.im/mod_pastebin#max_lines"] = tostring(line_threshold);
formdata["https://modules.prosody.im/mod_pastebin#max_characters"] = tostring(length_threshold);
end);
function expire_pastes(time)
time = time or os_time(); -- COMPAT with 0.5
if pastes[1] then
pastes[pastes[1]] = nil;
t_remove(pastes, 1);
if pastes[1] then
return (expire_after - (time - pastes[pastes[1]].time)) + 1;
end
end
end
module:provides("http", {
route = {
["GET /*"] = handle_request;
};
});
local function set_pastes_metatable()
-- luacheck: ignore 212/pastes 431/pastes
if expire_after == 0 then
local dm = require "util.datamanager";
setmetatable(pastes, {
__index = function (pastes, id)
if type(id) == "string" then
return dm.load(id, module.host, "pastebin");
end
end;
__newindex = function (pastes, id, data)
if type(id) == "string" then
dm.store(id, module.host, "pastebin", data);
end
end;
});
else
setmetatable(pastes, nil);
end
end
module.load = set_pastes_metatable;
function module.save()
return { pastes = pastes };
end
function module.restore(data)
pastes = data.pastes or pastes;
set_pastes_metatable();
end
|
-->8
-- scumm-8 core engine
-- ############################
-- you should not need to
-- modify anything below here
-- ############################
function shake(bc)
bd,be=bc,bc and 1 or be
end
function bf(bg)
local bh="lookat"
if has_flag(bg.classes,"class_talkable") then
bh="talkto"
elseif has_flag(bg.classes,"class_openable") then
if bg.state=="state_closed"then
bh="open"
else
bh="close"
end
end
for bi in all(verbs) do
bj=get_verb(bi)
if bj[2]==bh then bh=bi break end
end
return bh
end
function bk(bl,bm,bn)
local bo=has_flag(bm.classes,"class_actor")
if bl=="walkto"then
return
elseif bl=="pickup"then
say_line(bo and"i don't need them"or"i don't need that")
elseif bl=="use"then
say_line(bo and"i can't just *use* someone"or
((bn and has_flag(bn.classes,class_actor)) and"i can't use that on someone!"or"that doesn't work"))
elseif bl=="give"then
say_line(bo and"i don't think i should be giving this away"or"i can't do that")
elseif bl=="lookat"then
say_line(bo and"i think it's alive"or"looks pretty ordinary")
elseif bl=="open"or bl=="close"then
say_line((bo and"they don't"or"it doesn't").." seem to "..bl)
elseif bl=="push"or bl=="pull"then
say_line(bo and"moving them would accomplish nothing"or"it won't budge!")
elseif bl=="talkto"then
say_line(bo and"erm ... i don't think they want to talk"or"i am not talking to that!")
else
say_line"hmm. no."
end
end
function camera_at(bp)
cam_x,bq,br=bs(bp)
end
function camera_follow(bt)
stop_script(bu)
br,bq=bt
bu=function()
while br do
if(br.in_room==room_curr) cam_x=bs(br)
yield()
end
end
start_script(bu,true)
if(br.in_room!=room_curr) change_room(br.in_room,1)
end
function camera_pan_to(bp)
bq,br=bs(bp)
bu=function()
while cam_x~=bq do
cam_x+=sgn(bq-cam_x)/2
yield()
end
bq=nil
end
start_script(bu,true)
end
function wait_for_camera()
while script_running(bu) do
yield()
end
end
function cutscene(type,bv,bw)
bx={
by=type,
bz=cocreate(bv),
ca=bw,
cb=br
}
add(cc,bx)
cd=bx
break_time()
end
function dialog_set(ce)
for msg in all(ce) do
dialog_add(msg)
end
end
function dialog_add(msg)
cf=cf or{cg={}}
ch=ci(msg,32)
cj=ck(ch)
cl={
num=#cf.cg+1,
msg=msg,
ch=ch,
cm=cj
}
add(cf.cg,cl)
end
function dialog_start(col,cn)
cf.col=col
cf.cn=cn
cf.co=true
selected_sentence=nil
end
function dialog_hide()
cf.co=false
end
function dialog_clear()
cf.cg={}
selected_sentence=nil
end
function dialog_end()
cf=nil
end
function get_use_pos(bg)
local cp,y,x=bg.use_pos or"pos_infront",bg.y,bg.x
if cq(cp) then
x,y=cp[1],cp[2]
else
local cr={
pos_left={-2,bg.h*8-2},
pos_right={bg.w*8,bg.h*8-2},
pos_above={bg.w*4-4,-2},
pos_center={bg.w*4,bg.h*4-4},
pos_infront={bg.w*4-4,bg.h*8+2}
}
if cp=="pos_left"and bg.cs then
x-=(bg.w*8+4)
y+=1
else
x+=cr[cp][1]
y+=cr[cp][2]
end
end
return{x=x,y=y}
end
function do_anim(ct,cu,cv)
if cu=="face_towards"then
if cq(cv) then
cw=atan2(ct.x-cv.x,cv.y-ct.y)
cx=93*(3.1415/180)
cw=cx-cw
cy=(cw*360)%360
cv=4-flr(cy/90)
cv=cz[cv]
end
face_dir=cz[ct.face_dir]
cv=cz[cv]
while face_dir!=cv do
if face_dir<cv then
face_dir+=1
else
face_dir-=1
end
ct.face_dir=cz[face_dir]
ct.flip=(ct.face_dir=="face_left")
break_time(10)
end
else
ct.curr_anim=cu
ct.da=1
ct.db=1
end
end
function open_door(dc,dd)
if dc.state=="state_open"then
say_line"it's already open"
else
dc.state="state_open"
if(dd) dd.state="state_open"
end
end
function close_door(dc,dd)
if dc.state=="state_closed"then
say_line"it's already closed"
else
dc.state="state_closed"
if(dd) dd.state="state_closed"
end
end
function come_out_door(de,df,dg)
if(df==nil) dh("target door does not exist") return
if(de.state~="state_open") say_line("the door is closed") return
di=df.in_room
if(di!=room_curr) change_room(di,dg)
local dj=get_use_pos(df)
put_at(selected_actor,dj.x,dj.y,di)
if df.use_dir then
dk=cz[(cz[df.use_dir]+1)%4+1]
else
dk="face_front"
end
selected_actor.face_dir=dk
selected_actor.flip=(selected_actor.face_dir=="face_left")
end
dl={
open=open_door,
close=close_door,
walkto=come_out_door
}
function fades(dm,dir)
local dn=25-25*dir
while true do
dn+=dir*2
if dn>50
or dn<0 then
return
end
if(dm==1) dp=min(dn,32)
yield()
end
end
function change_room(di,dm)
if(not di) dh("room does not exist") return
stop_script(dq)
if dm and room_curr then
fades(dm,1)
end
if(room_curr and room_curr.exit) room_curr.exit(room_curr)
dr={}
ds()
room_curr=di
if(not br or br.in_room!=room_curr) cam_x=0
stop_talking()
if dm then
dq=function()
fades(dm,-1)
end
start_script(dq,true)
else
dp=0
end
if room_curr.enter then
room_curr.enter(room_curr)
end
end
function valid_verb(bl,dt)
if(not dt or not dt.verbs) return false
if cq(bl) then
if(dt.verbs[bl[1]]) return true
else
if(dt.verbs[bl]) return true
end
end
function pickup_obj(bg,bt)
bt=bt or selected_actor
add(bt.du,bg)
bg.owner=bt
del(bg.in_room.objects,bg)
end
function start_script(dv,dw,dx,q)
local bz=cocreate(dv)
add(dw and dy or dr,{dv,bz,dx,q})
end
function script_running(dv)
for dz in all({dr,dy}) do
for ea,eb in pairs(dz) do
if eb[1]==dv then
return eb
end
end
end
end
function stop_script(dv)
eb=script_running(dv)
del(dr,eb)
del(dy,eb)
end
function break_time(ec)
for x=1,ec or 1 do
yield()
end
end
function wait_for_message()
while ed do
yield()
end
end
function say_line(bt,msg,ee,ef)
if type(bt)=="string"then
msg,bt=bt,selected_actor
end
eg=bt
print_line(msg,bt.x,bt.y-bt.h*8+4,bt.col,1,ee,ef)
end
function stop_talking()
ed,eg=nil
end
function print_line(msg,x,y,col,eh,ee,ef,ei)
col=col or 7
eh=eh or 0
local ej=127-(x-cam_x)
if(eh==1) ej=min(x-cam_x,ej)
local ek=max(flr(ej/2),16)
local el=""
for em=1,#msg do
local en=sub(msg,em,em)
if en==":"then
el=sub(msg,em+1)
msg=sub(msg,1,em-1)
break
end
end
local ch=ci(msg,ek)
local cj=ck(ch)
eo=x-cam_x
if(eh==1) eo-=cj*(ei and 4 or 2)
local eo,ep=max(2,eo),max(18,y)
eo=min(eo,127-(cj*4)-1)
ed={
eq=ch,
x=eo,
y=ep,
col=col,
eh=eh,
er=ef or#msg*8,
cm=cj,
ee=ee,
ei=ei
}
if#el>0 then
es=eg
wait_for_message()
eg=es
print_line(el,x,y,col,eh,ee,nil,ei)
end
wait_for_message()
end
function put_at(bg,x,y,et)
if et then
if not has_flag(bg.classes,"class_actor") then
if(bg.in_room) del(bg.in_room.objects,bg)
add(et.objects,bg)
bg.owner=nil
end
bg.in_room=et
end
bg.x,bg.y=x,y
end
function stop_actor(bt)
bt.eu,bt.curr_anim=0
ds()
end
function walk_to(bt,x,y)
local ev=ew(bt)
local ex,ey=flr(x/8)+room_curr.map[1],flr(y/8)+room_curr.map[2]
local ez={ex,ey}
local fa=fb(ev,ez,{x,y})
bt.eu=1
for fc=1,#fa do
local fd=fa[fc]
local fe=bt.walk_speed*(bt.scale or bt.ff)
local fg,fh=(fd[1]-room_curr.map[1])*8+4,(fd[2]-room_curr.map[2])*8+4
if(fc==#fa and x>=fg-4 and x<=fg+4 and y>=fh-4 and y<=fh+4) fg,fh=x,y
local fi=sqrt((fg-bt.x)^2+(fh-bt.y)^2)
local fj=fe*(fg-bt.x)/fi
local fk=fe*(fh-bt.y)/fi
if fi>0 then
for em=0,fi/fe-1 do
if bt.eu==0 then
return
end
bt.flip=fj<0
if abs(fj)<fe/2 then
bt.curr_anim=fk>0 and bt.walk_anim_front or bt.walk_anim_back
bt.face_dir=fk>0 and"face_front"or"face_back"
else
bt.curr_anim=bt.walk_anim_side
bt.face_dir=bt.flip and"face_left"or"face_right"
end
bt.x+=fj
bt.y+=fk
yield()
end
end
end
bt.eu,bt.curr_anim=2
end
function wait_for_actor(bt)
bt=bt or selected_actor
while bt.eu!=2 do
yield()
end
end
function proximity(bm,bn)
return bm.in_room==bn.in_room and sqrt((bm.x-bn.x)^2+(bm.y-bn.y)^2) or 1000
end
stage_top=16
cam_x,be=0,0
fl,fm,fn,fo=63.5,63.5,0,1
fp={
{spr=ui_uparrowspr,x=75,y=stage_top+60},
{spr=ui_dnarrowspr,x=75,y=stage_top+72}
}
cz={
"face_front",
"face_left",
"face_back",
"face_right",
face_front=1,
face_left=2,
face_back=3,
face_right=4
}
function fq(bg)
local fr={}
for ea,bi in pairs(bg) do
add(fr,ea)
end
return fr
end
function get_verb(bg)
local bl,fr={},fq(bg[1])
add(bl,fr[1])
add(bl,bg[1][fr[1]])
add(bl,bg.text)
return bl
end
function ds()
fs,ft,fu,fv,fw,j=get_verb(verb_default),false,""
end
ds()
cd=nil
dy={}
dr={}
cc={}
fx={}
dp,dp=0,0
fy=0
function _init()
poke(0x5f2d,1)
fz()
start_script(startup_script,true)
end
function _update60()
if selected_actor and selected_actor.bz
and not coresume(selected_actor.bz) then
selected_actor.bz=nil
end
ga(dy)
if cd then
if cd.bz
and not coresume(cd.bz) then
if cd.by!=3
and cd.cb
then
camera_follow(cd.cb)
selected_actor=cd.cb
end
del(cc,cd)
if#cc>0 then
cd=cc[#cc]
else
if(cd.by!=2) fy=3
cd=nil
end
end
else
ga(dr)
end
gb()
gc()
gd,ge=1.5-rnd(3),1.5-rnd(3)
gd=flr(gd*be)
ge=flr(ge*be)
if(not bd) be=be>0.05 and be*0.90 or 0
end
function _draw()
cls()
camera(cam_x+gd,0+ge)
clip(
0+dp-gd,
stage_top+dp-ge,
128-dp*2-gd,
64-dp*2)
gf()
camera(0,0)
clip()
if show_debuginfo then
print("cpu: "..flr(100*stat(1)).."%",0,stage_top-16,8)
print("mem: "..flr(stat(0)/1024*100).."%",0,stage_top-8,8)
print("x: "..flr(fl+cam_x).." y:"..fm-stage_top,80,stage_top-8,8)
end
gg()
if cf
and cf.co then
gh()
gi()
return
end
if(fy>0) fy-=1 return
if(not cd) gj()
if(not cd
or cd.by==2)
and fy==0 then
gk()
end
if(not cd) gi()
end
function gl()
gm=stat(34)>0
end
function gb()
if ed and not gm and(btnp(4) or stat(34)==1) then
ed.er,gm=0,true
return
end
if cd then
if(btnp(5) or stat(34)==2) and cd.ca then
cd.bz=cocreate(cd.ca)
cd.ca=nil
return
end
gl()
return
end
if btn(0) then fl-=1 end
if btn(1) then fl+=1 end
if btn(2) then fm-=1 end
if btn(3) then fm+=1 end
if btnp(4) then gn(1) end
if btnp(5) then gn(2) end
go,gp=stat(32)-1,stat(33)-1
if go!=gq then fl=go end
if gp!=gr then fm=gp end
if stat(34)>0 and not gm then
gn(stat(34))
end
gq,gr=go,gp
gl()
end
fl,fm=mid(0,fl,127),mid(0,fm,127)
function gn(gs)
if(not selected_actor) return
if cf and cf.co then
if(gt) selected_sentence=gt
return
end
if(ft) ds()
if gu then
fs,fv,fw=get_verb(gu)
elseif gv then
if gs==1 then
if fv and not ft then
fw=gv
else
fv=gv
end
if(fs[2]==get_verb(verb_default)[2]
and gv.owner) then
fs=get_verb(verbs[verb_default_inventory_index])
end
elseif gw then
fs,fv=get_verb(gw),gv
gj()
end
elseif gx then
if gx==fp[1] then
if(selected_actor.gy>0) selected_actor.gy-=1
else
if selected_actor.gy+2<flr(#selected_actor.du/4) then
selected_actor.gy+=1
end
end
return
end
local gz=fs[2]
if fv then
if gz=="use"or gz=="give"then
if fw then
elseif fv.use_with and fv.owner==selected_actor then
return
end
end
ft=true
selected_actor.bz=cocreate(function()
if(not fv.owner
and(not has_flag(fv.classes,"class_actor")
or gz!="use"))
or fw
then
ha=fw or fv
hb=get_use_pos(ha)
walk_to(selected_actor,hb.x,hb.y)
if selected_actor.eu!=2 then return end
use_dir=ha
if ha.use_dir then use_dir=ha.use_dir end
do_anim(selected_actor,"face_towards",use_dir)
end
if valid_verb(fs,fv) then
start_script(fv.verbs[fs[1]],false,fv,fw)
else
if has_flag(fv.classes,"class_door") then
local dv=dl[gz]
if(dv) dv(fv,fv.target_door)
else
bk(gz,fv,fw)
end
end
ds()
end)
coresume(selected_actor.bz)
elseif fm>stage_top and fm<stage_top+64 then
ft=true
selected_actor.bz=cocreate(function()
walk_to(selected_actor,fl+cam_x,fm-stage_top)
ds()
end)
coresume(selected_actor.bz)
end
end
function gc()
if(not room_curr) return
gu,gw,gv,gt,gx=nil
if cf and cf.co then
for dz in all(cf.cg) do
if(hc(dz)) gt=dz
end
return
end
hd()
for bg in all(room_curr.objects) do
if(not bg.classes
or(bg.classes and not has_flag(bg.classes,"class_untouchable")))
and(not bg.dependent_on
or bg.dependent_on.state==bg.dependent_on_state)
then
he(bg,bg.w*8,bg.h*8,cam_x,hf)
else
bg.hg=nil
end
if hc(bg) then
if not gv
or max(bg.z,gv.z)==bg.z
then
gv=bg
end
end
hh(bg)
end
for ea,bt in pairs(actors) do
if bt.in_room==room_curr then
he(bt,bt.w*8,bt.h*8,cam_x,hf)
hh(bt)
if(hc(bt) and bt!=selected_actor) gv=bt
end
end
if selected_actor then
for bi in all(verbs) do
if(hc(bi)) gu=bi
end
for hi in all(fp) do
if(hc(hi)) gx=hi
end
for ea,bg in pairs(selected_actor.du) do
if hc(bg) then
gv=bg
if(fs[2]=="pickup"and gv.owner) fs=nil
end
if(bg.owner!=selected_actor) del(selected_actor.du,bg)
end
fs=fs or get_verb(verb_default)
gw=gv and bf(gv) or gw
end
end
function hd()
for x=-64,64 do
fx[x]={}
end
end
function hh(bg)
add(fx[bg.z and bg.z or flr(bg.y+(bg.hj and 0 or bg.h*8))],bg)
end
function gf()
if not room_curr then
print("-error- no current room set",5+cam_x,5+stage_top,8,0)
return
end
rectfill(0,stage_top,127,stage_top+64,room_curr.hk or 0)
for z=-64,64 do
if z==0 then
hl(room_curr)
if room_curr.trans_col then
palt(0,false)
palt(room_curr.trans_col,true)
end
map(room_curr.map[1],room_curr.map[2],0,stage_top,room_curr.hm,room_curr.hn)
pal()
else
ho=fx[z]
for bg in all(ho) do
if not has_flag(bg.classes,"class_actor") then
if bg.states
or(bg.state
and bg[bg.state]
and bg[bg.state]>0)
and(not bg.dependent_on
or bg.dependent_on.state==bg.dependent_on_state)
and not bg.owner
or bg.draw
or bg.curr_anim
then
hp(bg)
end
else
if(bg.in_room==room_curr) hq(bg)
end
end
end
end
end
function hl(bg)
if bg.col_replace then
fc=bg.col_replace
pal(fc[1],fc[2])
end
if bg.lighting then
hr(bg.lighting)
elseif bg.in_room and bg.in_room.lighting then
hr(bg.in_room.lighting)
end
end
function hp(bg)
local hs=0
hl(bg)
if bg.draw then
bg.draw(bg)
else
if bg.curr_anim then
ht(bg)
hs=bg.curr_anim[bg.da]
end
for h=0,bg.repeat_x and bg.repeat_x-1 or 0 do
if bg.states then
hs=bg.states[bg.state]
elseif hs==0 then
hs=bg[bg.state]
end
hu(hs,bg.x+(h*(bg.w*8)),bg.y,bg.w,bg.h,bg.trans_col,bg.flip_x,bg.scale)
end
end
pal()
end
function hq(bt)
local hv,hs=cz[bt.face_dir]
if bt.curr_anim
and(bt.eu==1 or cq(bt.curr_anim))
then
ht(bt)
hs=bt.curr_anim[bt.da]
else
hs=bt.idle[hv]
end
hl(bt)
local hw=(bt.y-room_curr.autodepth_pos[1])/(room_curr.autodepth_pos[2]-room_curr.autodepth_pos[1])
hw=room_curr.autodepth_scale[1]+(room_curr.autodepth_scale[2]-room_curr.autodepth_scale[1])*hw
bt.ff=mid(room_curr.autodepth_scale[1],hw,room_curr.autodepth_scale[2])
local scale=bt.scale or bt.ff
local hx,hy=(8*bt.h),(8*bt.w)
local hz=hx-(hx*scale)
local ia=hy-(hy*scale)
local ib=bt.cs+flr(ia/2)
local ic=bt.hj+hz
hu(hs,
ib,
ic,
bt.w,
bt.h,
bt.trans_col,
bt.flip,
false,
scale)
if eg
and eg==bt
and eg.talk
then
if bt.id<7 then
hu(bt.talk[hv],
ib+(bt.talk[5] or 0),
ic+flr((bt.talk[6] or 8)*scale),
(bt.talk[7] or 1),
(bt.talk[8] or 1),
bt.trans_col,
bt.flip,
false,
scale)
end
bt.id=bt.id%14+1
end
pal()
end
function gj()
local ie,ig,ih=verb_maincol,fs[2],fs and fs[3] or""
if fv then
ih=ih.." "..fv.name
if ig=="use"and(not ft or fw) then
ih=ih.." with"
elseif ig=="give"then
ih=ih.." to"
end
end
if fw then
ih=ih.." "..fw.name
elseif gv
and gv.name!=""
and(not fv or(fv!=gv))
and not ft
then
if gv.owner
and ig==get_verb(verb_default)[2] then
ih="look-at"
end
ih=ih.." "..gv.name
end
fu=ih
if ft then
ih=fu
ie=verb_hovcol
end
print(ii(ih),63.5-flr(#ih*2),stage_top+66,ie)
end
function gg()
if ed then
local ij=0
for ik in all(ed.eq) do
local il=0
if ed.eh==1 then
il=((ed.cm*4)-(#ik*4))/2
end
outline_text(
ik,
ed.x+il,
ed.y+ij,
ed.col,
0,
ed.ee,
ed.ei)
ij+=ed.ei and 12 or 6
end
ed.er-=1
if(ed.er<=0) stop_talking()
end
end
function gk()
local eo,ep,im=0,75,0
for bi in all(verbs) do
local io=bi==gu and verb_hovcol or
(gw and bi==gw and verb_defcol or
verb_maincol)
local bj=get_verb(bi)
print(bj[3],eo,ep+stage_top+1,verb_shadcol)
print(bj[3],eo,ep+stage_top,io)
bi.x=eo
bi.y=ep
he(bi,#bj[3]*4,5,0,0)
if(#bj[3]>im) im=#bj[3]
ep+=8
if ep>=95 then
ep=75
eo+=(im+1.0)*4
im=0
end
end
if selected_actor then
eo,ep=86,76
local ip=selected_actor.gy*4
local iq=min(ip+8,#selected_actor.du)
for ir=1,8 do
rectfill(eo-1,stage_top+ep-1,eo+8,stage_top+ep+8,verb_shadcol)
bg=selected_actor.du[ip+ir]
if bg then
bg.x,bg.y=eo,ep
hp(bg)
he(bg,bg.w*8,bg.h*8,0,0)
end
eo+=11
if eo>=125 then
ep+=12
eo=86
end
ir+=1
end
for em=1,2 do
is=fp[em]
pal(7,gx==is and verb_hovcol or verb_maincol)
pal(5,verb_shadcol)
hu(is.spr,is.x,is.y,1,1,0)
he(is,8,7,0,0)
pal()
end
end
end
function gh()
local eo,ep=0,70
for dz in all(cf.cg) do
if dz.cm>0 then
dz.x,dz.y=eo,ep
he(dz,dz.cm*4,#dz.ch*5,0,0)
local io=dz==gt and cf.cn or cf.col
for ik in all(dz.ch) do
print(ii(ik),eo,ep+stage_top,io)
ep+=5
end
ep+=2
end
end
end
function gi()
col=ui_cursor_cols[fo]
pal(7,col)
spr(ui_cursorspr,fl-4,fm-3,1,1,0)
pal()
fn+=1
if fn>7 then
fn=1
fo=fo%#ui_cursor_cols+1
end
end
function hu(it,x,y,w,h,iu,flip_x,iv,scale)
set_trans_col(iu)
it=it or 0
local iw,ix=8*(it%16),8*flr(it/16)
local iy,iz=8*w,8*h
local ja=scale or 1
local jb,jc=iy*ja,iz*ja
sspr(iw,ix,iy,iz,x,stage_top+y,jb,jc,flip_x,iv)
end
function set_trans_col(iu)
palt(0,false)
palt(iu,true)
end
function fz()
for et in all(rooms) do
jd(et)
et.hm=#et.map>2 and et.map[3]-et.map[1]+1 or 16
et.hn=#et.map>2 and et.map[4]-et.map[2]+1 or 8
et.autodepth_pos=et.autodepth_pos or{9,50}
et.autodepth_scale=et.autodepth_scale or{0.25,1}
for bg in all(et.objects) do
jd(bg)
bg.in_room,bg.h=et,bg.h or 0
if(bg.init) bg.init(bg)
end
end
for je,bt in pairs(actors) do
jd(bt)
bt.eu=2
bt.db=1
bt.id=1
bt.da=1
bt.du={
}
bt.gy=0
end
end
function ga(scripts)
for eb in all(scripts) do
if eb[2] and not coresume(eb[2],eb[3],eb[4]) then
del(scripts,eb)
end
end
end
function hr(jf)
if(jf) jf=1-jf
local fd=flr(mid(0,jf,1)*100)
local jg={0,1,1,2,1,13,6,
4,4,9,3,13,1,13,14}
for jh=1,15 do
col=jh
ji=(fd+(jh*1.46))/22
for ea=1,ji do
col=jg[col]
end
pal(jh,col)
end
end
function cq(t)
return type(t)=="table"
end
function bs(bp)
return mid(0,(cq(bp) and bp.x or bp)-64,(room_curr.hm*8)-128)
end
function ew(bg)
return{flr(bg.x/8)+room_curr.map[1],flr(bg.y/8)+room_curr.map[2]}
end
function jj(ex,ey)
return fget(mget(ex,ey),0)
end
function ci(msg,ek)
local ch,jk,jl,en={},"","",""
local function jm(jn)
if#jl+#jk>jn then
add(ch,jk)
jk=""
end
jk=jk..jl
jl=""
end
for em=1,#msg do
en=sub(msg,em,em)
jl=jl..en
if en==" "or#jl>ek-1 then
jm(ek)
elseif#jl>ek-1 then
jl=jl.."-"
jm(ek)
elseif en==";"then
jk=jk..sub(jl,1,#jl-1)
jl=""
jm(0)
end
end
jm(ek)
if(jk!="") add(ch,jk)
return ch
end
function ck(ch)
local cj=0
for ik in all(ch) do
if(#ik>cj) cj=#ik
end
return cj
end
function has_flag(bg,jo)
for jp in all(bg) do
if(jp==jo) return true
end
end
function he(bg,w,h,jq,jr)
local x,y=bg.x,bg.y
if has_flag(bg.classes,"class_actor") then
bg.cs=x-(bg.w*8)/2
bg.hj=y-(bg.h*8)+1
x=bg.cs
y=bg.hj
end
bg.hg={
x=x,
y=y+stage_top,
js=x+w-1,
jt=y+h+stage_top-1,
jq=jq,
jr=jr
}
end
function fb(ju,jv)
local jw,jx,jy,jz,ka,kb={},{},{}
kc(jw,ju,0)
jy[kd(ju)]=0
while#jw>0 and#jw<1000 do
kb=jw[#jw][1]
del(jw,jw[#jw])
if(kd(kb)==kd(jv)) break
local ke={}
for x=-1,1 do
for y=-1,1,x==0 and 2 or 1 do
local kf,kg=kb[1]+x,kb[2]+y
if kf>=room_curr.map[1] and kf<=room_curr.map[1]+room_curr.hm
and kg>=room_curr.map[2] and kg<=room_curr.map[2]+room_curr.hn
and jj(kf,kg)
and((abs(x)!=abs(y))
or jj(kf,kb[2])
or jj(kf-x,kg)
or enable_diag_squeeze)
then
local kh={kf,kg}
local ki=kd(kh)
local kj=jy[kd(kb)]+(x*y==0 and 1 or 1.414)
if not jy[ki] or kj<jy[ki] then
jy[ki]=kj
local h=max(abs(jv[1]-kf),abs(jv[2]-kg))+min(abs(jv[1]-kf),abs(jv[2]-kg))*.414
kc(jw,kh,kj+h)
jx[ki]=kb
if not jz or h<jz then
jz=h
ka=ki
kk=kh
end
end
end
end
end
end
local fa={}
kb=jx[kd(jv)]
if kb then
add(fa,jv)
elseif ka then
kb=jx[ka]
add(fa,kk)
end
if kb then
local kl,km=kd(kb),kd(ju)
while kl!=km do
add(fa,kb)
kb=jx[kl]
kl=kd(kb)
end
for em=1,#fa/2 do
local kn=fa[em]
local ko=#fa-(em-1)
fa[em]=fa[ko]
fa[ko]=kn
end
end
return fa
end
function kc(t,bp,fd)
local kp={bp,fd}
if#t>=1 then
for em=#t+1,2,-1 do
local kh=t[em-1]
if fd<kh[2] then
t[em]=kp
return
else
t[em]=kh
end
end
end
t[1]=kp
end
function kd(kq)
return((kq[1]+1)*16)+kq[2]
end
function ht(bg)
bg.db+=1
if bg.db>bg.frame_delay then
bg.db=1
bg.da=bg.da%#bg.curr_anim+1
end
end
function dh(msg)
print_line("-error-;"..msg,5+cam_x,5,8,0)
end
function jd(bg)
for ik in all(split(bg.data,"\n")) do
local pairs=split(ik,"=")
if#pairs==2 then
bg[pairs[1]]=kr(pairs[2])
else
printh(" > invalid data: ["..pairs[1].."]")
end
end
end
function split(dz,ks)
local kt,ip,ku={},0,0
for em=1,#dz do
local kv=sub(dz,em,em)
if kv==ks then
add(kt,sub(dz,ip,ku))
ip,ku=0,0
elseif kv!=" "
and kv!="\t"then
ku,ip=em,ip==0 and em or ip
end
end
if ip+ku>0 then
add(kt,sub(dz,ip,ku))
end
return kt
end
function kr(kw)
local kx=sub(kw,1,1)
if kw=="true"then
return true
elseif kw=="false"then
return false
elseif tonum(kw) then
return tonum(kw)
elseif kx=="{"then
local kn=sub(kw,2,#kw-1)
ky={}
for bp in all(split(kn,",")) do
add(ky,kr(bp))
end
return ky
else
return kw
end
end
function outline_text(kz,x,y,la,lb,ee,ei)
if(not ee) kz=ii(kz)
if(ei) kz="\^w\^t"..kz
for lc=-1,1 do
for ld=-1,1,lc==0 and 2 or 1 do
print(kz,x+lc,y+ld,lb)
end
end
print(kz,x,y,la)
end
function hc(bg)
if(not bg.hg or cd) return false
local hg=bg.hg
return not((fl+hg.jq>hg.js or fl+hg.jq<hg.x)
or(fm>hg.jt or fm<hg.y))
end
function ii(dz)
local t=""
for em=1,#dz do
local fc=ord(dz,em)
t..=chr(fc>96 and fc<123 and fc-32 or fc)
end
return t
end
|
local ffi = require("ffi")
local socket = {}
local e = {}
local errno = {}
do
local C
if ffi.os == "Windows" then
C = assert(ffi.load("ws2_32"))
else
C = ffi.C
end
local M = {}
local function generic_function(C_name, cdef, alias, size_error_handling)
ffi.cdef(cdef)
alias = alias or C_name
local func_name = alias
local func = C[C_name]
if size_error_handling == false then
socket[func_name] = func
elseif size_error_handling then
socket[func_name] = function(...)
local len = func(...)
if len < 0 then
return nil, socket.lasterror()
end
return len
end
else
socket[func_name] = function(...)
local ret = func(...)
if ret == 0 then
return true
end
return nil, socket.lasterror()
end
end
end
ffi.cdef[[
struct in_addr {
uint32_t s_addr;
};
struct in6_addr {
union {
uint8_t u6_addr8[16];
uint16_t u6_addr16[8];
uint32_t u6_addr32[4];
} u6_addr;
};
]]
-- https://www.cs.dartmouth.edu/~sergey/cs60/on-sockaddr-structs.txt
if ffi.os == "OSX" then
ffi.cdef[[
struct sockaddr {
uint8_t sa_len;
uint8_t sa_family;
char sa_data[14];
};
struct sockaddr_in {
uint8_t sin_len;
uint8_t sin_family;
uint16_t sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
struct sockaddr_in6 {
uint8_t sin6_len;
uint8_t sin6_family;
uint16_t sin6_port;
uint32_t sin6_flowinfo;
struct in6_addr sin6_addr;
uint32_t sin6_scope_id;
};
]]
elseif ffi.os == "Windows" then
ffi.cdef[[
struct sockaddr {
uint16_t sa_family;
char sa_data[14];
};
struct sockaddr_in {
int16_t sin_family;
uint16_t sin_port;
struct in_addr sin_addr;
uint8_t sin_zero[8];
};
struct sockaddr_in6 {
int16_t sin6_family;
uint16_t sin6_port;
uint32_t sin6_flowinfo;
struct in6_addr sin6_addr;
uint32_t sin6_scope_id;
};
]]
else -- posix
ffi.cdef[[
struct sockaddr {
uint16_t sa_family;
char sa_data[14];
};
struct sockaddr_in {
uint16_t sin_family;
uint16_t sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
struct sockaddr_in6 {
uint16_t sin6_family;
uint16_t sin6_port;
uint32_t sin6_flowinfo;
struct in6_addr sin6_addr;
uint32_t sin6_scope_id;
};
]]
end
if ffi.os == "Windows" then
ffi.cdef[[
typedef size_t SOCKET;
struct addrinfo {
int ai_flags;
int ai_family;
int ai_socktype;
int ai_protocol;
size_t ai_addrlen;
char *ai_canonname;
struct sockaddr *ai_addr;
struct addrinfo *ai_next;
};
]]
socket.INVALID_SOCKET = ffi.new("SOCKET", -1)
elseif ffi.os == "OSX" then
ffi.cdef[[
typedef int32_t SOCKET;
struct addrinfo {
int ai_flags;
int ai_family;
int ai_socktype;
int ai_protocol;
uint32_t ai_addrlen;
char *ai_canonname;
struct sockaddr *ai_addr;
struct addrinfo *ai_next;
};
]]
socket.INVALID_SOCKET = -1
else
ffi.cdef[[
typedef int32_t SOCKET;
struct addrinfo {
int ai_flags;
int ai_family;
int ai_socktype;
int ai_protocol;
uint32_t ai_addrlen;
struct sockaddr *ai_addr;
char *ai_canonname;
struct addrinfo *ai_next;
};
]]
socket.INVALID_SOCKET = -1
end
assert(ffi.sizeof("struct sockaddr") == 16)
assert(ffi.sizeof("struct sockaddr_in") == 16)
if ffi.os == "Windows" then
ffi.cdef[[
struct pollfd {
SOCKET fd;
short events;
short revents;
};
int WSAPoll(struct pollfd *fds, unsigned long int nfds, int timeout);
uint32_t GetLastError();
uint32_t FormatMessageA(
uint32_t dwFlags,
const void* lpSource,
uint32_t dwMessageId,
uint32_t dwLanguageId,
char* lpBuffer,
uint32_t nSize,
va_list *Arguments
);
]]
local function WORD(low, high)
return bit.bor(low , bit.lshift(high , 8))
end
do
ffi.cdef[[int GetLastError();]]
local FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000
local FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200
local flags = bit.bor(FORMAT_MESSAGE_IGNORE_INSERTS, FORMAT_MESSAGE_FROM_SYSTEM)
local cache = {}
function socket.lasterror(num)
num = num or ffi.C.GetLastError()
if not cache[num] then
local buffer = ffi.new("char[512]")
local len = ffi.C.FormatMessageA(flags, nil, num, 0, buffer, ffi.sizeof(buffer), nil)
cache[num] = ffi.string(buffer, len - 2)
end
return cache[num], num
end
end
do
ffi.cdef[[int WSAStartup(uint16_t version, void *wsa_data);]]
local wsa_data
if jit.arch == "x64" then
wsa_data = ffi.typeof([[struct {
uint16_t wVersion;
uint16_t wHighVersion;
unsigned short iMax_M;
unsigned short iMaxUdpDg;
char * lpVendorInfo;
char szDescription[257];
char szSystemStatus[129];
}]])
else
wsa_data = ffi.typeof([[struct {
uint16_t wVersion;
uint16_t wHighVersion;
char szDescription[257];
char szSystemStatus[129];
unsigned short iMax_M;
unsigned short iMaxUdpDg;
char * lpVendorInfo;
}]])
end
function socket.initialize()
local data = wsa_data()
if C.WSAStartup(WORD(2, 2), data) == 0 then
return data
end
return nil, socket.lasterror()
end
end
do
ffi.cdef[[int WSACleanup();]]
function socket.shutdown()
if C.WSACleanup() == 0 then
return true
end
return nil, socket.lasterror()
end
end
if jit.arch ~= "x64" then -- xp or something
ffi.cdef[[int WSAAddressToStringA(struct sockaddr *, unsigned long, void *, char *, unsigned long *);]]
function socket.inet_ntop(family, pAddr, strptr, strlen)
-- win XP: http://memset.wordpress.com/2010/10/09/inet_ntop-for-win32/
local srcaddr = ffi.new("struct sockaddr_in")
ffi.copy(srcaddr.sin_addr, pAddr, ffi.sizeof(srcaddr.sin_addr))
srcaddr.sin_family = family
local len = ffi.new("unsigned long[1]", strlen)
C.WSAAddressToStringA(ffi.cast("struct sockaddr *", srcaddr), ffi.sizeof(srcaddr), nil, strptr, len)
return strptr
end
end
generic_function("closesocket", "int closesocket(SOCKET s);", "close")
do
ffi.cdef[[int ioctlsocket(SOCKET s, long cmd, unsigned long* argp);]]
local IOCPARM_MASK = 0x7
local IOC_IN = 0x80000000
local function _IOW(x,y,t)
return bit.bor(IOC_IN, bit.lshift(bit.band(ffi.sizeof(t),IOCPARM_MASK),16), bit.lshift(x,8), y)
end
local FIONBIO = _IOW(string.byte'f', 126, "uint32_t") -- -2147195266 -- 2147772030ULL
function socket.blocking(fd, b)
local ret = C.ioctlsocket(fd, FIONBIO, ffi.new("int[1]", b and 0 or 1))
if ret == 0 then
return true
end
return nil, socket.lasterror()
end
end
function socket.poll(fds, ndfs, timeout)
local ret = C.WSAPoll(fds, ndfs, timeout)
if ret < 0 then
return nil, socket.lasterror()
end
return ret
end
else
ffi.cdef[[
struct pollfd {
SOCKET fd;
short events;
short revents;
};
int poll(struct pollfd *fds, unsigned long nfds, int timeout);
]]
do
local cache = {}
function socket.lasterror(num)
num = num or ffi.errno()
if not cache[num] then
local err = ffi.string(ffi.C.strerror(num))
cache[num] = err == "" and tostring(num) or err
end
return cache[num], num
end
end
generic_function("close", "int close(SOCKET s);")
do
ffi.cdef[[int fcntl(int, int, ...);]]
local F_GETFL = 3
local F_SETFL = 4
local O_NONBLOCK = 04000
if ffi.os == "OSX" then
O_NONBLOCK = 0x0004
end
function socket.blocking(fd, b)
local flags = ffi.C.fcntl(fd, F_GETFL, 0)
if flags < 0 then
-- error
return nil, socket.lasterror()
end
if b then
flags = bit.band(flags, bit.bnot(O_NONBLOCK))
else
flags = bit.bor(flags, O_NONBLOCK)
end
local ret = ffi.C.fcntl(fd, F_SETFL, ffi.new("int", flags))
if ret < 0 then
return nil, socket.lasterror()
end
return true
end
end
function socket.poll(fds, ndfs, timeout)
local ret = C.poll(fds, ndfs, timeout)
if ret < 0 then
return nil, socket.lasterror()
end
return ret
end
end
ffi.cdef[[
char *strerror(int errnum);
int getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res);
int getnameinfo(const struct sockaddr* sa, uint32_t salen, char* host, size_t hostlen, char* serv, size_t servlen, int flags);
void freeaddrinfo(struct addrinfo *ai);
const char *gai_strerror(int errcode);
char *inet_ntoa(struct in_addr in);
uint16_t ntohs(uint16_t netshort);
]]
function socket.getaddrinfo(node_name, service_name, hints, result)
local ret = C.getaddrinfo(node_name, service_name, hints, result)
if ret == 0 then
return true
end
return nil, ffi.string(socket.lasterror(ret))
end
function socket.getnameinfo(address, length, host, hostlen, serv, servlen, flags)
local ret = C.getnameinfo(address, length, host, hostlen, serv, servlen, flags)
if ret == 0 then
return true
end
return nil, ffi.string(socket.lasterror(ret))
end
do
ffi.cdef[[const char *inet_ntop(int __af, const void *__cp, char *__buf, unsigned int __len);]]
function socket.inet_ntop(family, addrinfo, strptr, strlen)
if C.inet_ntop(family, addrinfo, strptr, strlen) == nil then
return nil, socket.lasterror()
end
return strptr
end
end
do
ffi.cdef[[SOCKET socket(int af, int type, int protocol);]]
function socket.create(af, type, protocol)
local fd = C.socket(af, type, protocol)
if fd <= 0 then
return nil, socket.lasterror()
end
return fd
end
end
generic_function("shutdown", "int shutdown(SOCKET s, int how);")
generic_function("setsockopt", "int setsockopt(SOCKET s, int level, int optname, const void* optval, uint32_t optlen);")
generic_function("getsockopt", "int getsockopt(SOCKET s, int level, int optname, void *optval, uint32_t *optlen);")
generic_function("accept", "SOCKET accept(SOCKET s, struct sockaddr *, int *);", nil, false)
generic_function("bind", "int bind(SOCKET s, const struct sockaddr* name, int namelen);")
generic_function("connect", "int connect(SOCKET s, const struct sockaddr * name, int namelen);")
generic_function("listen", "int listen(SOCKET s, int backlog);")
generic_function("recv", "int recv(SOCKET s, char* buf, int len, int flags);", nil, true)
generic_function("recvfrom", "int recvfrom(SOCKET s, char* buf, int len, int flags, struct sockaddr *src_addr, unsigned int *addrlen);", nil, true)
generic_function("send", "int send(SOCKET s, const char* buf, int len, int flags);", nil, true)
generic_function("sendto", "int sendto(SOCKET s, const char* buf, int len, int flags, const struct sockaddr* to, int tolen);", nil, true)
generic_function("getpeername", "int getpeername(SOCKET s, struct sockaddr *, unsigned int *);")
generic_function("getsockname", "int getsockname(SOCKET s, struct sockaddr *, unsigned int *);")
socket.inet_ntoa = C.inet_ntoa
socket.ntohs = C.ntohs
function socket.poll(fd, events, revents)
end
e = {
TCP_NODELAY = 1,
TCP_MAXSEG = 2,
TCP_CORK = 3,
TCP_KEEPIDLE = 4,
TCP_KEEPINTVL = 5,
TCP_KEEPCNT = 6,
TCP_SYNCNT = 7,
TCP_LINGER2 = 8,
TCP_DEFER_ACCEPT = 9,
TCP_WINDOW_CLAMP = 10,
TCP_INFO = 11,
TCP_QUICKACK = 12,
TCP_CONGESTION = 13,
TCP_MD5SIG = 14,
TCP_THIN_LINEAR_TIMEOUTS = 16,
TCP_THIN_DUPACK = 17,
TCP_USER_TIMEOUT = 18,
TCP_REPAIR = 19,
TCP_REPAIR_QUEUE = 20,
TCP_QUEUE_SEQ = 21,
TCP_REPAIR_OPTIONS = 22,
TCP_FASTOPEN = 23,
TCP_TIMESTAMP = 24,
TCP_NOTSENT_LOWAT = 25,
TCP_CC_INFO = 26,
TCP_SAVE_SYN = 27,
TCP_SAVED_SYN = 28,
TCP_REPAIR_WINDOW = 29,
TCP_FASTOPEN_CONNECT = 30,
TCP_ULP = 31,
TCP_MD5SIG_EXT = 32,
TCP_FASTOPEN_KEY = 33,
TCP_FASTOPEN_NO_COOKIE = 34,
TCP_ZEROCOPY_RECEIVE = 35,
TCP_INQ = 36,
AF_INET = 2,
AF_INET6 = 10,
AF_UNSPEC = 0,
AF_UNIX = 1,
AF_AX25 = 3,
AF_IPX = 4,
AF_APPLETALK = 5,
AF_NETROM = 6,
AF_BRIDGE = 7,
AF_AAL5 = 8,
AF_X25 = 9,
INET6_ADDRSTRLEN = 46,
INET_ADDRSTRLEN = 16,
SO_DEBUG = 1,
SO_REUSEADDR = 2,
SO_TYPE = 3,
SO_ERROR = 4,
SO_DONTROUTE = 5,
SO_BROADCAST = 6,
SO_SNDBUF = 7,
SO_RCVBUF = 8,
SO_SNDBUFFORCE = 32,
SO_RCVBUFFORCE = 33,
SO_KEEPALIVE = 9,
SO_OOBINLINE = 10,
SO_NO_CHECK = 11,
SO_PRIORITY = 12,
SO_LINGER = 13,
SO_BSDCOMPAT = 14,
SO_REUSEPORT = 15,
SO_PASSCRED = 16,
SO_PEERCRED = 17,
SO_RCVLOWAT = 18,
SO_SNDLOWAT = 19,
SO_RCVTIMEO = 20,
SO_SNDTIMEO = 21,
SO_SECURITY_AUTHENTICATION = 22,
SO_SECURITY_ENCRYPTION_TRANSPORT = 23,
SO_SECURITY_ENCRYPTION_NETWORK = 24,
SO_BINDTODEVICE = 25,
SO_ATTACH_FILTER = 26,
SO_DETACH_FILTER = 27,
SO_GET_FILTER = 26,
SO_PEERNAME = 28,
SO_TIMESTAMP = 29,
SO_ACCEPTCONN = 30,
SO_PEERSEC = 31,
SO_PASSSEC = 34,
SO_TIMESTAMPNS = 35,
SO_MARK = 36,
SO_TIMESTAMPING = 37,
SO_PROTOCOL = 38,
SO_DOMAIN = 39,
SO_RXQ_OVFL = 40,
SO_WIFI_STATUS = 41,
SO_PEEK_OFF = 42,
SO_NOFCS = 43,
SO_LOCK_FILTER = 44,
SO_SELECT_ERR_QUEUE = 45,
SO_BUSY_POLL = 46,
SO_MAX_PACING_RATE = 47,
SO_BPF_EXTENSIONS = 48,
SO_INCOMING_CPU = 49,
SO_ATTACH_BPF = 50,
SO_DETACH_BPF = 27,
SO_ATTACH_REUSEPORT_CBPF = 51,
SO_ATTACH_REUSEPORT_EBPF = 52,
SO_CNX_ADVICE = 53,
SO_MEMINFO = 55,
SO_INCOMING_NAPI_ID = 56,
SO_COOKIE = 57,
SO_PEERGROUPS = 59,
SO_ZEROCOPY = 60,
SO_TXTIME = 61,
SOL_SOCKET = 1,
SOL_TCP = 6,
SOMAXCONN = 128,
IPPROTO_IP = 0,
IPPROTO_HOPOPTS = 0,
IPPROTO_ICMP = 1,
IPPROTO_IGMP = 2,
IPPROTO_IPIP = 4,
IPPROTO_TCP = 6,
IPPROTO_EGP = 8,
IPPROTO_PUP = 12,
IPPROTO_UDP = 17,
IPPROTO_IDP = 22,
IPPROTO_TP = 29,
IPPROTO_DCCP = 33,
IPPROTO_IPV6 = 41,
IPPROTO_ROUTING = 43,
IPPROTO_FRAGMENT = 44,
IPPROTO_RSVP = 46,
IPPROTO_GRE = 47,
IPPROTO_ESP = 50,
IPPROTO_AH = 51,
IPPROTO_ICMPV6 = 58,
IPPROTO_NONE = 59,
IPPROTO_DSTOPTS = 60,
IPPROTO_MTP = 92,
IPPROTO_ENCAP = 98,
IPPROTO_PIM = 103,
IPPROTO_COMP = 108,
IPPROTO_SCTP = 132,
IPPROTO_UDPLITE = 136,
IPPROTO_RAW = 255,
SOCK_STREAM = 1,
SOCK_DGRAM = 2,
SOCK_RAW = 3,
SOCK_RDM = 4,
SOCK_SEQPACKET = 5,
SOCK_DCCP = 6,
SOCK_PACKET = 10,
SOCK_CLOEXEC = 02000000,
SOCK_NONBLOCK = 04000,
AI_PASSIVE = 0x00000001,
AI_CANONNAME = 0x00000002,
AI_NUMERICHOST = 0x00000004,
AI_NUMERICSERV = 0x00000008,
AI_ALL = 0x00000100,
AI_ADDRCONFIG = 0x00000400,
AI_V4MAPPED = 0x00000800,
AI_NON_AUTHORITATIVE = 0x00004000,
AI_SECURE = 0x00008000,
AI_RETURN_PREFERRED_NAMES = 0x00010000,
AI_FQDN = 0x00020000,
AI_FILESERVER = 0x00040000,
POLLIN = 0x0001,
POLLPRI = 0x0002,
POLLOUT = 0x0004,
POLLRDNORM = 0x0040,
POLLWRNORM = 0x0004,
POLLRDBAND = 0x0080,
POLLWRBAND = 0x0100,
POLLEXTEND = 0x0200,
POLLATTRIB = 0x0400,
POLLNLINK = 0x0800,
POLLWRITE = 0x1000,
POLLERR = 0x0008,
POLLHUP = 0x0010,
POLLNVAL = 0x0020,
MSG_OOB = 0x01,
MSG_PEEK = 0x02,
MSG_DONTROUTE = 0x04,
MSG_CTRUNC = 0x08,
MSG_PROXY = 0x10,
MSG_TRUNC = 0x20,
MSG_DONTWAIT = 0x40,
MSG_EOR = 0x80,
MSG_WAITALL = 0x100,
MSG_FIN = 0x200,
MSG_SYN = 0x400,
MSG_CONFIRM = 0x800,
MSG_RST = 0x1000,
MSG_ERRQUEUE = 0x2000,
MSG_NOSIGNAL = 0x4000,
MSG_MORE = 0x8000,
MSG_WAITFORONE = 0x10000,
MSG_CMSG_CLOEXEC = 0x40000000,
}
errno = {
EAGAIN = 11,
EWOULDBLOCK = 11, -- is errno.EAGAIN
ENOTSOCK = 88,
ECONNRESET = 104,
EINPROGRESS = 115,
}
if ffi.os == "Windows" then
e.SO_SNDLOWAT = 4099
e.SO_REUSEADDR = 4
e.SO_KEEPALIVE = 8
e.SOMAXCONN = 2147483647
e.AF_INET6 = 23
e.SO_RCVTIMEO = 4102
e.SOL_SOCKET = 65535
e.SO_LINGER = 128
e.SO_OOBINLINE = 256
e.POLLWRNORM = 16
e.SO_ERROR = 4103
e.SO_BROADCAST = 32
e.SO_ACCEPTCONN = 2
e.SO_RCVBUF = 4098
e.SO_SNDTIMEO = 4101
e.POLLIN = 768
e.POLLPRI = 1024
e.SO_TYPE = 4104
e.POLLRDBAND = 512
e.POLLWRBAND = 32
e.SO_SNDBUF = 4097
e.POLLNVAL = 4
e.POLLHUP = 2
e.POLLERR = 1
e.POLLRDNORM = 256
e.SO_DONTROUTE = 16
e.SO_RCVLOWAT = 4100
errno.EAGAIN = 10035 -- Note: Does not exist on Windows
errno.EWOULDBLOCK = 10035
errno.EINPROGRESS = 10036
errno.ENOTSOCK = 10038
errno.ECONNRESET = 10054
end
if ffi.os == "OSX" then
e.SOL_SOCKET = 0xffff
e.SO_DEBUG = 0x0001
e.SO_ACCEPTCONN = 0x0002
e.SO_REUSEADDR = 0x0004
e.SO_KEEPALIVE = 0x0008
e.SO_DONTROUTE = 0x0010
e.SO_BROADCAST = 0x0020
errno.EAGAIN = 35
errno.EWOULDBLOCK = errno.EAGAIN
errno.EINPROGRESS = 36
errno.ENOTSOCK = 38
errno.ECONNRESET = 54
end
if socket.initialize then
assert(socket.initialize())
end
end
local function capture_flags(what)
local flags = {}
local reverse = {}
for k, v in pairs(e) do
if k:sub(0, #what) == what then
k = k:sub(#what + 1):lower()
reverse[v] = k
flags[k] = v
end
end
return {
lookup = flags,
reverse = reverse,
strict_reverse = function(key)
if not key then
error("invalid " .. what:sub(0, -2) .. " flag: nil")
end
if not reverse[key] then
error("invalid "..what:sub(0, -2).." flag: " .. key, 2)
end
return reverse[key]
end,
strict_lookup = function(key)
if not key then
error("invalid " .. what:sub(0, -2) .. " flag: nil")
end
if not flags[key] then
error("invalid "..what:sub(0, -2).." flag: " .. key, 2)
end
return flags[key]
end
}
end
local SOCK = capture_flags("SOCK_")
local AF = capture_flags("AF_")
local IPPROTO = capture_flags("IPPROTO_")
local AI = capture_flags("AI_")
local SOL = capture_flags("SOL_")
local SO = capture_flags("SO_")
local TCP = capture_flags("TCP_")
local POLL = capture_flags("POLL")
local function table_to_flags(flags, valid_flags, operation)
if type(flags) == "string" then
flags = {flags}
end
operation = operation or bit.band
local out = 0
for k, v in pairs(flags) do
local flag = valid_flags[v] or valid_flags[k]
if not flag then
error("invalid flag " .. tostring(v), 2)
end
out = operation(out, tonumber(flag))
end
return out
end
local function flags_to_table(flags, valid_flags, operation)
if not flags then return valid_flags.default_valid_flag end
operation = operation or bit.band
local out = {}
for k, v in pairs(valid_flags) do
if operation(flags, v) > 0 then
out[k] = true
end
end
return out
end
local M = {}
local timeout_messages = {}
timeout_messages[errno.EINPROGRESS] = true
timeout_messages[errno.EAGAIN] = true
timeout_messages[errno.EWOULDBLOCK] = true
function M.poll(socket, flags, timeout)
local pfd = ffi.new("struct pollfd[1]", {{
fd = socket.fd,
events = table_to_flags(flags, POLL.lookup, bit.bor),
revents = 0,
}})
local ok, err = socket.poll(pfd, 1, timeout or 0)
if not ok then return ok, err end
return flags_to_table(pfd[0].revents, POLL.lookup, bit.bor), ok
end
local function addrinfo_get_ip(self)
if self.addrinfo.ai_addr == nil then
return nil
end
local str = ffi.new("char[256]")
local addr = assert(socket.inet_ntop(AF.lookup[self.family], self.addrinfo.ai_addr.sa_data, str, ffi.sizeof(str)))
return ffi.string(addr)
end
local function addrinfo_get_port(self)
if self.addrinfo.ai_addr == nil then
return nil
end
if self.family == "inet" then
return ffi.cast("struct sockaddr_in*", self.addrinfo.ai_addr).sin_port
elseif self.family == "inet6" then
return ffi.cast("struct sockaddr_in6*", self.addrinfo.ai_addr).sin6_port
end
return nil, "unknown family " .. tostring(self.family)
end
local function addrinfo_to_table(res, host, service)
local info = {}
if res.ai_canonname ~= nil then
info.canonical_name = ffi.string(res.ai_canonname)
end
info.host = host ~= "*" and host or nil
info.service = service
info.family = AF.reverse[res.ai_family]
info.socket_type = SOCK.reverse[res.ai_socktype]
info.protocol = IPPROTO.reverse[res.ai_protocol]
info.flags = flags_to_table(res.ai_flags, AI.lookup, bit.band)
info.addrinfo = res
info.get_ip = addrinfo_get_ip
info.get_port = addrinfo_get_port
return info
end
function M.get_address_info(data)
local hints
if data.socket_type or data.protocol or data.flags or data.family then
hints = ffi.new("struct addrinfo", {
ai_family = data.family and AF.strict_lookup(data.family) or nil,
ai_socktype = data.socket_type and SOCK.strict_lookup(data.socket_type) or nil,
ai_protocol = data.protocol and IPPROTO.strict_lookup(data.protocol) or nil,
ai_flags = data.flags and table_to_flags(data.flags, AI.lookup, bit.bor) or nil,
})
end
local out = ffi.new("struct addrinfo*[1]")
local ok, err = socket.getaddrinfo(
data.host ~= "*" and data.host or nil,
data.service and tostring(data.service) or nil,
hints,
out
)
if not ok then return ok, err end
local tbl = {}
local res = out[0]
while res ~= nil do
table.insert(tbl, addrinfo_to_table(res, data.host, data.service))
res = res.ai_next
end
--ffi.C.freeaddrinfo(out[0])
return tbl
end
function M.find_first_address(host, service, options)
options = options or {}
local info = {}
info.host = host
info.service = service
info.family = options.family or "inet"
info.socket_type = options.socket_type or "stream"
info.protocol = options.protocol or "tcp"
info.flags = options.flags
if host == "*" then
info.flags = info.flags or {}
table.insert(info.flags, "passive")
end
local addrinfo, err = M.get_address_info(info)
if not addrinfo then
return nil, err
end
if not addrinfo[1] then
return nil, "no addresses found (empty address info table)"
end
for _, v in ipairs(addrinfo) do
if v.family == info.family and v.socket_type == info.socket_type and v.protocol == info.protocol then
return v
end
end
return addrinfo[1]
end
do
local meta = {}
meta.__index = meta
function meta:__tostring()
return string.format("socket[%s-%s-%s][%s]", self.family, self.socket_type, self.protocol, self.fd)
end
function M.create(family, socket_type, protocol)
local fd, err, num = socket.create(AF.strict_lookup(family), SOCK.strict_lookup(socket_type), IPPROTO.strict_lookup(protocol))
if not fd then return fd, err, num end
return setmetatable({
fd = fd,
family = family,
socket_type = socket_type,
protocol = protocol,
blocking = true,
}, meta)
end
function meta:close()
if self.on_close then
self:on_close()
end
return socket.close(self.fd)
end
function meta:set_blocking(b)
local ok, err, num = socket.blocking(self.fd, b)
if ok then
self.blocking = b
end
return ok, err, num
end
function meta:set_option(key, val, level)
level = level or "socket"
if type(val) == "boolean" then
val = ffi.new("int[1]", val and 1 or 0)
elseif type(val) == "number" then
val = ffi.new("int[1]", val)
elseif type(val) ~= "cdata" then
error("unknown value type: " .. type(val))
end
local env = SO
if level == "tcp" then
env = TCP
end
return socket.setsockopt(self.fd, SOL.strict_lookup(level), env.strict_lookup(key), ffi.cast("void *", val), ffi.sizeof(val))
end
function meta:connect(host, service)
local res
if type(host) == "table" and host.addrinfo then
res = host
else
local res_, err = M.find_first_address(host, service, {
family = self.family,
socket_type = self.socket_type,
protocol = self.protocol
})
if not res_ then
return res_, err
end
res = res_
end
local ok, err, num = socket.connect(self.fd, res.addrinfo.ai_addr, res.addrinfo.ai_addrlen)
if not ok and not self.blocking then
if timeout_messages[num] then
self.timeout_connected = {host, service}
return true
end
elseif self.on_connect then
self:on_connect(host, service)
end
if not ok then
return ok, err, num
end
return true
end
function meta:poll_connect()
if self.on_connect and self.timeout_connected and self:is_connected() then
local ok, err, num = self:on_connect(unpack(self.timeout_connected))
self.timeout_connected = nil
return ok, err, num
end
return nil, "timeout"
end
function meta:bind(host, service)
if host == "*" then
host = nil
end
if type(service) == "number" then
service = tostring(service)
end
local res
if type(host) == "table" and host.addrinfo then
res = host
else
local res_, err = M.find_first_address(host, service, {
family = self.family,
socket_type = self.socket_type,
protocol = self.protocol
})
if not res_ then
return res_, err
end
res = res_
end
return socket.bind(self.fd, res.addrinfo.ai_addr, res.addrinfo.ai_addrlen)
end
function meta:listen(max_connections)
max_connections = max_connections or e.SOMAXCONN
return socket.listen(self.fd, max_connections)
end
function meta:accept()
local address = ffi.new("struct sockaddr_in[1]")
local fd, err = socket.accept(self.fd, ffi.cast("struct sockaddr *", address), ffi.new("unsigned int[1]", ffi.sizeof(address)))
if fd ~= socket.INVALID_SOCKET then
local client = setmetatable({
fd = fd,
family = "unknown",
socket_type = "unknown",
protocol = "unknown",
blocking = true,
}, meta)
if self.debug then
print(tostring(self), ": accept client: ", tostring(client))
end
return client
end
local err, num = socket.lasterror()
if not self.blocking and timeout_messages[num] then
return nil, "timeout", num
end
if self.debug then
print(tostring(self), ": accept error", num, ":", err)
end
return nil, err, num
end
function meta:is_connected()
local ip, service, num = self:get_peer_name()
local ip2, service2, num2 = self:get_name()
if not ip and (num == errno.ECONNRESET or num == errno.ENOTSOCK) then
return false, service, num
end
if ffi.os == "Windows" then
return ip ~= "0.0.0.0" and ip2 ~= "0.0.0.0" and service ~= 0 and service2 ~= 0
else
return ip and ip2 and service ~= 0 and service2 ~= 0
end
end
function meta:get_peer_name()
local data = ffi.new("struct sockaddr_in")
local len = ffi.new("unsigned int[1]", ffi.sizeof(data))
local ok, err, num = socket.getpeername(self.fd, ffi.cast("struct sockaddr *", data), len)
if not ok then return ok, err, num end
return ffi.string(socket.inet_ntoa(data.sin_addr)), socket.ntohs(data.sin_port)
end
function meta:get_name()
local data = ffi.new("struct sockaddr_in")
local len = ffi.new("unsigned int[1]", ffi.sizeof(data))
local ok, err, num = socket.getsockname(self.fd, ffi.cast("struct sockaddr *", data), len)
if not ok then return ok, err, num end
return ffi.string(socket.inet_ntoa(data.sin_addr)), socket.ntohs(data.sin_port)
end
local default_flags = 0
if ffi.os ~= "Windows" then
default_flags = e.MSG_NOSIGNAL
end
function meta:send_to(addr, data, flags)
return self:send(data, flags, addr)
end
function meta:send(data, flags, addr)
flags = flags or default_flags
if self.on_send then
return self:on_send(data, flags)
end
local len, err, num
if addr then
len, err, num = socket.sendto(self.fd, data, #data, flags, addr.addrinfo.ai_addr, addr.addrinfo.ai_addrlen)
else
len, err, num = socket.send(self.fd, data, #data, flags)
end
if not len then
return len, err, num
end
if len > 0 then
return len
end
end
function meta:receive_from(address, size, flags)
local src_addr
local src_addr_size
if not address then
src_addr = ffi.new("struct sockaddr_in[1]")
src_addr_size = ffi.sizeof("struct sockaddr_in")
else
src_addr = address.addrinfo.ai_addr
src_addr_size = address.addrinfo.ai_addrlen
end
return self:receive(size, flags, src_addr, src_addr_size)
end
function meta:receive(size, flags, src_address, address_len)
size = size or 64000
local buff = ffi.new("char[?]", size)
if self.on_receive then
return self:on_receive(buff, size, flags)
end
local len, err, num
local len_res
if src_address then
len_res = ffi.new("int[1]", address_len)
len, err, num = socket.recvfrom(self.fd, buff, ffi.sizeof(buff), flags or 0, ffi.cast("struct sockaddr *", src_address), len_res)
else
len, err, num = socket.recv(self.fd, buff, ffi.sizeof(buff), flags or 0)
end
if num == errno.ECONNRESET then
self:close()
if self.debug then
print(tostring(self), ": closed")
end
return nil, "closed", num
end
if not len then
if not self.blocking and timeout_messages[num] then
return nil, "timeout", num
end
if self.debug then
print(tostring(self), " error", num, ":", err)
end
return len, err, num
end
if len > 0 then
if self.debug then
print(tostring(self), ": received ", len, " bytes")
end
if src_address then
return ffi.string(buff, len), {
addrinfo = {
ai_addr = ffi.cast("struct sockaddr *", src_address),
ai_addrlen = len_res[0],
},
family = self.family,
get_port = addrinfo_get_port,
get_ip = addrinfo_get_ip,
}
end
return ffi.string(buff, len)
end
return nil, err, num
end
end
function M.bind(host, service)
local info, err = M.find_first_address(host, service, {
family = "inet",
socket_type = "stream",
protocol = "tcp",
flags = {"passive"},
})
if not info then
return info, err
end
local server, err, num = M.create(info.family, info.socket_type, info.protocol)
if not server then
return server, err, num
end
server:set_option("reuseaddr", 1)
local ok, err, num = server:bind(info)
if not ok then
return ok, err, num
end
server:set_option("sndbuf", 65536)
server:set_option("rcvbuf", 65536)
return server
end
return M |
local configs = require 'nvim_lsp/configs'
local util = require 'nvim_lsp/util'
configs.terraformls = {
default_config = {
cmd = {"terraform-lsp"};
filetypes = {"terraform"};
root_dir = util.root_pattern(".terraform", ".git");
};
docs = {
package_json = "https://raw.githubusercontent.com/hashicorp/vscode-terraform/master/package.json";
description = [[
https://github.com/juliosueiras/terraform-lsp
Terraform language server
You can use [released binary](https://github.com/juliosueiras/terraform-lsp/releases) or [build](https://github.com/juliosueiras/terraform-lsp#building) your own.
]];
default_config = {
root_dir = [[root_pattern(".terraform", ".git")]];
};
};
}
-- vim:et ts=2 sw=2
|
-- This script parses the request body and assembles a $body_cache_key
-- variable containing the SOAP request body parameters.
local pp = require'pp'
local expat = require'expat'
local pp_format = pp.format
local ngx_req = ngx.req
local ngx_log = ngx.log
local ngx_DEBUG = ngx.DEBUG
local ngx_NOTICE = ngx.NOTICE
local ngx_POST = ngx.HTTP_POST
local ngx_cap = ngx.location.capture
-- GET requests have no body, thus it makes no sense to parse them.
-- These are usually done to get the WSDL.
if ngx.var.request_method == 'GET' then return end
-- Assemble a serialized Lua table from the xmlelem children
local function serializetbl(xmlelem)
local params = {}
for i,e in ipairs(xmlelem.children) do
local val
if #e.children == 0 then
val = pp_format(e.cdata)
else
val = serializetbl(e)
end
params[#params+1] = '['..pp_format(e.tag)..']='..val
end
table.sort(params) -- Normalize, as param order in the XML does not matter
return '{'..table.concat(params, ',')..'}'
end
-- Return the SOAP Body given the root XML object
local function soapenvbody(xmlsoap)
return (xmlsoap
.tags['http://schemas.xmlsoap.org/soap/envelope/:Envelope']
.tags['http://schemas.xmlsoap.org/soap/envelope/:Body'])
end
-- Hook into a WSCall to insert a fake parameter containing the CV modification time
local function mtimehook(wscall)
local id = wscall.tags.id and wscall.tags.id.cdata or
wscall.tags.request.tags.parametros.tags.idCNPq.cdata
ngx_log(ngx_DEBUG, "id = ", id)
-- Request modification time back from the webservice
local res = ngx_cap('/srvcurriculo/WSCurriculo', {
method = ngx_POST,
body = [[<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns1:getDataAtualizacaoCV xmlns:ns1="http://ws.servico.repositorio.cnpq.br/">
<id>]]..id..[[</id>
</ns1:getDataAtualizacaoCV>
</soap:Body>
</soap:Envelope>]],
vars = {
-- access phase is not run in subrequest, so precompute the cache key
body_cache_key = [[http://ws.servico.repositorio.cnpq.br/:getDataAtualizacaoCV|{['id']=']]..id..[['}]],
}
})
if res.status ~= 200 then error(pp_format(res)) end
-- Parse response
local xmlres = expat.treeparse({string=res.body, namespacesep=':'})
local mtime = (
soapenvbody(xmlres)
.tags['http://ws.servico.repositorio.cnpq.br/:getDataAtualizacaoCVResponse']
.tags['return']
.cdata)
ngx_log(ngx_DEBUG, "mtime = ", mtime)
-- Add a fake parameter to the original request
local children = wscall.children
children[#children+1] = {tag = "_mtime", children = {}, cdata = mtime}
end
-- Special hooks for certain webservice calls
local wscallhooks = {
['http://ws.servico.repositorio.cnpq.br/:getCurriculoCompactado'] = mtimehook,
['http://ws.servico.repositorio.cnpq.br/:getCurriculoCompactadoPorUsuario'] = mtimehook,
['http://br.cnpq.cvlattes.extracaocv/wsdl:extrairItens'] = mtimehook,
}
local headers = ngx_req.get_headers()
local contenttype = headers['content-type']
-- Try to get the charset from the Content-Type header. If not specified, the
-- variable will be nil, and thus ignored by expat, which will use the default
-- charset (utf-8), or the one specified in the <?xml ?> tag, if present.
local charset = contenttype:match(';%s*charset=([^;]+)')
-- Read the request body
ngx_req.read_body()
local request_body = ngx_req.get_body_data()
-- As far as we know, the server only accepts POST requests containing XML data.
-- Anyway, if it is not the case, fallback to use the request body as a cache key.
if not contenttype or not contenttype:match('^text/xml') then
ngx_log(ngx_NOTICE, 'Unsupported content-type: ', pp_format(contenttype))
ngx.var.body_cache_key = request_body
return
end
-- Parse the request body
local xmlsoap = expat.treeparse({
string=ngx_req.get_body_data(),
namespacesep=':',
encoding=charset})
-- Get the tag contained inside the SOAP Body
local wscall = soapenvbody(xmlsoap).children[1]
-- Check if any hook exists for this WSCall
local hook = wscallhooks[wscall.tag]
if hook then
local ok, err = pcall(hook, wscall)
if not ok then ngx_log(ngx_NOTICE, err) end
end
-- The cache key is formed by the tag name, that indicates which
-- webservice call is being made, and by a serialized Lua table
-- containing the parameters.
local cachekey = wscall.tag..'|'..serializetbl(wscall)
ngx_log(ngx_DEBUG, "cachekey: ", cachekey)
ngx.var.body_cache_key = cachekey
|
if (true) then return end
local irisPairs = {
1020,
1021,
}
local vaultDoor = 1029
hook.Add("InitPostEntity", "mapmodded", function()
for k, v in ipairs(ents.GetAll()) do
local hammerID = v:GetMapID()
if (table.hasValue(irisPairs, hammerID)) then
-- for shortage of the time
v:SetKeyValue("waitingtime", 0.5);
end
end
end) |
-- Internal register
local _class={}
function class(base)
local class_type={}
class_type.__type = 'class'
class_type.ctor = false
local vtbl = {}
_class[class_type] = vtbl
setmetatable(class_type,{__newindex = vtbl, __index = vtbl})
if base then
setmetatable(vtbl,{__index=
function(t,k)
local ret=_class[base][k]
vtbl[k]=ret
return ret
end
})
end
class_type.__base = base
class_type.new = function(...)
--create a object, dependent on .__createFunc
local obj= {}
obj.__base = class_type
obj.__type = 'object'
do
local create
create = function(c, ...)
if c.__base then
create(c.__base, ...)
end
if c.ctor then
c.ctor(obj, ...)
end
end
create(class_type,...)
end
setmetatable(obj,{ __index = _class[class_type] })
return obj
end
class_type.super = function(self, f, ...)
assert(self and self.__type == 'object', string.format("'self' must be a object when call super(self, '%s', ...)", tostring(f)))
local originBase = self.__base
--find the first f function that differ from self[f] in the inheritance chain
local s = originBase
local base = s.__base
while base and s[f] == base[f] do
s = base
base = base.__base
end
assert(base and base[f], string.format("base class or function cannot be found when call .super(self, '%s', ...)", tostring(f)))
--now base[f] is differ from self[f], but f in base also maybe inherited from base's baseClass
while base.__base and base[f] == base.__base[f] do
base = base.__base
end
-- If the base also has a baseclass, temporarily set :super to call that baseClass' methods
-- this is to avoid stack overflow
if base.__base then
self.__base = base
end
--now, call the super function
local result = base[f](self, ...)
--set back
if base.__base then
self.__base = originBase
end
return result
end
return class_type
end
|
--Minetest
--Copyright (C) 2016 T4im
--
--This program is free software; you can redistribute it and/or modify
--it under the terms of the GNU Lesser General Public License as published by
--the Free Software Foundation; either version 2.1 of the License, or
--(at your option) any later version.
--
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
--GNU Lesser General Public License for more details.
--
--You should have received a copy of the GNU Lesser General Public License along
--with this program; if not, write to the Free Software Foundation, Inc.,
--51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
local function get_bool_default(name, default)
local val = core.settings:get_bool(name)
if val == nil then
return default
end
return val
end
local profiler_path = core.get_builtin_path().."profiler"..DIR_DELIM
local profiler = {}
local sampler = assert(loadfile(profiler_path .. "sampling.lua"))(profiler)
local instrumentation = assert(loadfile(profiler_path .. "instrumentation.lua"))(profiler, sampler, get_bool_default)
local reporter = dofile(profiler_path .. "reporter.lua")
profiler.instrument = instrumentation.instrument
---
-- Delayed registration of the /profiler chat command
-- Is called later, after `core.register_chatcommand` was set up.
--
function profiler.init_chatcommand()
local instrument_profiler = get_bool_default("instrument.profiler", false)
if instrument_profiler then
instrumentation.init_chatcommand()
end
local param_usage = "print [filter] | dump [filter] | save [format [filter]] | reset"
core.register_chatcommand("profiler", {
description = "handle the profiler and profiling data",
params = param_usage,
privs = { server=true },
func = function(name, param)
local command, arg0 = string.match(param, "([^ ]+) ?(.*)")
local args = arg0 and string.split(arg0, " ")
if command == "dump" then
core.log("action", reporter.print(sampler.profile, arg0))
return true, "Statistics written to action log"
elseif command == "print" then
return true, reporter.print(sampler.profile, arg0)
elseif command == "save" then
return reporter.save(sampler.profile, args[1] or "txt", args[2])
elseif command == "reset" then
sampler.reset()
return true, "Statistics were reset"
end
return false, string.format(
"Usage: %s\n" ..
"Format can be one of txt, csv, lua, json, json_pretty (structures may be subject to change).",
param_usage
)
end
})
if not instrument_profiler then
instrumentation.init_chatcommand()
end
end
sampler.init()
instrumentation.init()
return profiler
|
local addonName, addon = ...
local module = addon:CreateModule("Unit Frames")
module.defaultSettings = {
x = 350,
y = 100,
scale = 1,
frameSpacing = 20,
statusTextScale = 1,
classColors = true,
hideNames = false,
}
module.optionsTable = {
scale = {
order = 1,
type = "range",
name = "Scale",
min = 0.1,
max = 5.0,
step = 0.1,
set = module.UpdateSettings,
},
frameSpacing = {
order = 2,
type = "range",
name = "Spacing",
min = -100,
max = 100,
softMin = -20,
softMax = 40,
step = 1,
set = module.UpdateSettings,
},
hideNames = {
order = 5,
type = "toggle",
name = "Hide names",
set = module.UpdateSettings,
},
classColors = {
order = 6,
type = "toggle",
name = "Class-colored health bars",
width = "full",
},
}
local hiddenFrame = CreateFrame("Frame", nil, UIParent)
hiddenFrame:Hide()
local dummyFrame = CreateFrame("Frame", nil, UIParent)
local sArenaEnemyFrames = ArenaEnemyFrames
sArenaEnemyFrames:Hide()
sArenaEnemyFrames:SetMovable(true)
ArenaEnemyFrames = dummyFrame
local firstPlayerEnteringWorld = false
function module:OnEvent(event, ...)
if event == "ADDON_LOADED" then
for i = 1, MAX_ARENA_ENEMIES do
local arenaFrame = _G["ArenaEnemyFrame"..i]
addon:SetupDrag(module, false, arenaFrame, sArenaEnemyFrames)
addon:SetupDrag(module, false, arenaFrame.healthbar, sArenaEnemyFrames)
addon:SetupDrag(module, false, arenaFrame.manabar, sArenaEnemyFrames)
end
--ArenaEnemyBackground:SetParent(hiddenFrame)
self:OnEvent("UPDATE_SETTINGS")
elseif event == "PLAYER_ENTERING_WORLD" then
if not firstPlayerEnteringWorld then
sArenaEnemyFrames:Show()
firstPlayerEnteringWorld = true
end
elseif event == "TEST_MODE" then
for i = 1, MAX_ARENA_ENEMIES do
local arenaFrame = _G["ArenaEnemyFrame"..i]
if addon.testMode then
arenaFrame.healthbar:SetMinMaxValues(0,100)
arenaFrame.healthbar:SetValue(100)
arenaFrame.healthbar.forceHideText = false
arenaFrame.manabar:SetMinMaxValues(0,100)
arenaFrame.manabar:SetValue(100)
arenaFrame.manabar:SetStatusBarColor(0, 0, 1)
arenaFrame.manabar.forceHideText = false
ArenaEnemyFrame_SetMysteryPlayer(arenaFrame)
arenaFrame.name:SetText("arena"..i)
arenaFrame:Show()
else
arenaFrame:Hide()
end
end
elseif event == "UPDATE_SETTINGS" then
sArenaEnemyFrames:ClearAllPoints()
sArenaEnemyFrames:SetPoint("CENTER", self.db.x, self.db.y)
sArenaEnemyFrames:SetScale(self.db.scale)
for i = 1, MAX_ARENA_ENEMIES do
local arenaFrame = _G["ArenaEnemyFrame"..i]
arenaFrame.name:SetShown(not self.db.hideNames)
if i > 1 then
arenaFrame:SetPoint("TOP", _G["ArenaEnemyFrame"..i-1], "BOTTOM", 0, self.db.frameSpacing * -1)
end
end
end
end
-- Class colored health bars
local healthBars = {
ArenaEnemyFrame1HealthBar = 1,
ArenaEnemyFrame2HealthBar = 1,
ArenaEnemyFrame3HealthBar = 1,
ArenaEnemyFrame4HealthBar = 1,
ArenaEnemyFrame5HealthBar = 1
}
local UnitClass = UnitClass
local RAID_CLASS_COLORS = RAID_CLASS_COLORS
local function colorStatusBar(statusbar)
if module.db.classColors and healthBars[statusbar:GetName()] then
local _, class = UnitClass(statusbar.unit)
if class then
local c = RAID_CLASS_COLORS[class]
if not statusbar.lockColor then statusbar:SetStatusBarColor(c.r, c.g, c.b) end
end
end
end
hooksecurefunc("UnitFrameHealthBar_Update", colorStatusBar)
hooksecurefunc("HealthBar_OnValueChanged", colorStatusBar)
|
local ADDON, Addon = ...
local Util = Addon.Util
local function eventHandlerWhisper(self, event, msg, from)
Addon:AddAllItems(msg, from, from)
end
local function eventHandlerBNChat(self, event, msg, sender, languageName, channelName, playerName2, specialFlags, zoneChannelID, channelIndex, channelBaseName, unused, lineID, guid, bnSenderID, isMobile, isSubtitle)
local accountInfo = C_BattleNet.GetAccountInfoByID(bnSenderID);
local gameAccountInfo = accountInfo.gameAccountInfo
if gameAccountInfo then
local name, realm = gameAccountInfo.characterName, gameAccountInfo.realmName
Util.dbgprint("BN: " .. sender .. " " .. name .. "-" .. realm)
if name and realm then
local from = name .. "-" .. realm
Addon:AddAllItems(msg, from, from)
end
end
end
local function eventHandlerEncounterEnd(self, event, encounterID, encounterName, difficultyID, raidSize, endStatus)
Addon:OnEncounterEnd(event, encounterID, encounterName, difficultyID, raidSize, endStatus)
end
local function eventHandlerLoot(self, event, message, sender)
local LOOT_SELF_REGEX = gsub(LOOT_ITEM_SELF, "%%s", "(.+)")
local LOOT_REGEX = gsub(LOOT_ITEM, "%%s", "(.+)")
local _, _, sPlayer, itemlink = string.find(message, LOOT_REGEX)
if not sPlayer then
_, _, itemlink = string.find(message, LOOT_SELF_REGEX)
sPlayer = Util.GetFullUnitName("player")
else
sPlayer = Util.CompleteUnitName(sPlayer)
end
if itemlink then
local _, _, itemId = string.find(itemlink, "item:(%d+):")
Util.dbgprint(sPlayer .. " got " .. itemlink)
end
end
local function eventHandlerLogout(self, event)
Addon:Serialize()
end
local function eventHandlerAddonLoaded(self, event, addonName)
if (addonName == ADDON) then
Addon:OnAddonLoaded()
end
end
local function eventHandlerAddonMessage(self, event, prefix, message, channel, sender)
if (prefix ~= Addon.MSG_PREFIX) then return end
local type, msg = message:match("^%s*([^ ]+)(.*)$")
if (type == nil) then return end
Util.dbgprint ("Received: " .. type)
if (type == Addon.MSG_CLAIM_MASTER) then
Addon:ProcessClaimMaster(sender)
elseif (type == Addon.MSG_RENOUNCE_MASTER) then
Addon:ProcessRenounceMaster(sender)
elseif (type == Addon.MSG_ANNOUNCE_LOOT) then
if not msg then return end
local from, itemString = msg:match(Addon.MSG_ANNOUNCE_LOOT_PATTERN)
Util.dbgprint ("Announcement: " .. from .. " " .. itemString)
if (sender == Addon.master and not Addon:IsMaster()) then
Addon:AddItem(itemString, from, sender)
end
elseif (type == Addon.MSG_DELETE_LOOT) then
if not msg then return end
local donator, itemString = msg:match(Addon.MSG_DELETE_LOOT_PATTERN)
Util.dbgprint ("Deletion: " .. donator .. " " .. itemString)
if (sender == Addon.master and not Addon:IsMaster()) then
local index = Addon.itemList:GetEntryId(itemString, donator, sender)
if (index) then Addon:DeleteItem(index) end
end
elseif (type == Addon.MSG_ANNOUNCE_WINNER) then
if not msg then return end
local from, itemString, winnerName, roll, rollMax = msg:match(Addon.MSG_ANNOUNCE_WINNER_PATTERN)
Util.dbgprint ("Winner: " .. from .. " " .. itemString .. " "
.. winnerName .. " " .. roll .. " " .. rollMax)
if (sender == Addon.master and not Addon:IsMaster()) then
Addon:SetWinner(itemString, from, sender, winnerName, roll, rollMax)
end
elseif (type == Addon.MSG_CHECK_MASTER) then
C_ChatInfo.SendAddonMessage(Addon.MSG_PREFIX, Addon.MSG_CLAIM_MASTER, "WHISPER", sender)
end
end
local function eventHandlerRaidRosterUpdate(self, event, arg)
HereticRaidInfo:Update()
if Addon:IsMaster() then
if Addon:IsAuthorizedToClaimMaster("player") then
for i,v in pairs(HereticRaidInfo:GetNewPlayers()) do
C_ChatInfo.SendAddonMessage(Addon.MSG_PREFIX, Addon.MSG_CLAIM_MASTER, "WHISPER", v)
end
else
Addon:RenounceMaster()
end
end
end
local function eventHandler(self, event, ...)
if event == "CHAT_MSG_WHISPER" then
eventHandlerWhisper(self, event, ...)
elseif event == "CHAT_MSG_BN_WHISPER" then
eventHandlerBNChat(self, event, ...)
elseif (event == "ENCOUNTER_END") then
eventHandlerEncounterEnd(self, event, ...)
elseif (event == "CHAT_MSG_LOOT") then
eventHandlerLoot(self, event, ...)
elseif (event == "PLAYER_LOGOUT") then
eventHandlerLogout(self, event, ...)
elseif (event == "ADDON_LOADED") then
eventHandlerAddonLoaded(self, event, ...)
elseif (event == "CHAT_MSG_ADDON") then
eventHandlerAddonMessage(self, event, ...)
elseif (event == "GROUP_ROSTER_UPDATE") then
eventHandlerRaidRosterUpdate(self, event, ...)
elseif (event == "GET_ITEM_INFO_RECEIVED") then
Addon:update("ItemInfoReceived")
elseif (event == "RAID_INSTANCE_WELCOME") then
Util.dbgprint("RaidInstanceWelcome: " .. (select(1, ...) .. " " .. select(2, ...)))
elseif (event == "UPDATE_INSTANCE_INFO") then
Util.dbgprint("UpdateInstanceInfo")
end
end
function Addon:InitializeEventHandlers(frame)
frame:SetScript("OnEvent", eventHandler);
frame:RegisterEvent("CHAT_MSG_WHISPER");
frame:RegisterEvent("CHAT_MSG_BN_WHISPER");
frame:RegisterEvent("CHAT_MSG_LOOT");
frame:RegisterEvent("ENCOUNTER_END");
frame:RegisterEvent("ADDON_LOADED");
frame:RegisterEvent("PLAYER_LOGOUT");
frame:RegisterEvent("CHAT_MSG_ADDON");
frame:RegisterEvent("RAID_ROSTER_UPDATE");
frame:RegisterEvent("GROUP_ROSTER_UPDATE");
frame:RegisterEvent("GET_ITEM_INFO_RECEIVED");
end
|
require'visimp'{
defaults = {
foldmethod = 'marker'
},
diagnostics = {},
gitsigns = {},
latex = {
tectonic = true
},
languages = {
'bash',
'c',
'latex',
'python'
},
lspsignature = {},
outline = {},
snippet = {},
theme = {'haishanh/night-owl.vim', 'night-owl', 'dark'}
}
-- diagnostics
vim.api.nvim_set_keymap('n', '<leader>xx', '<cmd>TroubleToggle<cr>',
{silent = true, noremap = true}
)
vim.api.nvim_set_keymap('n', '<leader>xw', '<cmd>Trouble workspace_diagnostics<cr>',
{silent = true, noremap = true}
)
vim.api.nvim_set_keymap('n', '<leader>xd', '<cmd>Trouble document_diagnostics<cr>',
{silent = true, noremap = true}
)
vim.api.nvim_set_keymap('n', '<leader>xl', '<cmd>Trouble loclist<cr>',
{silent = true, noremap = true}
)
vim.api.nvim_set_keymap('n', '<leader>xq', '<cmd>Trouble quickfix<cr>',
{silent = true, noremap = true}
)
vim.api.nvim_set_keymap('n', 'gR', '<cmd>Trouble lsp_references<cr>',
{silent = true, noremap = true}
)
|
local versionNumber = "1.2"
function widget:GetInfo()
return {
name = "Ghost Site",
desc = "[v" .. string.format("%s", versionNumber ) .. "] Displays ghosted buildings in progress and features",
author = "very_bad_soldier",
date = "April 7, 2009",
license = "GNU GPL v2",
layer = 0,
enabled = true
}
end
--[[changelog:
1.1: removes itself when old defense range found (thx to TFC)
1.2: fixed buildframes not showing up, now uses correct rotation, tracks enemy wrecks when necessary.
--]]
-- CONFIGURATION
local debug = false --generates debug message
local updateInt = 1 --seconds for the ::update loop
-- END OF CONFIG
local lastTime
local ghostSites = {}
local ghostFeatures = {}
local ignoreFeature = {}
local floor = math.floor
local udefTab = UnitDefs
local glColor = gl.Color
local glDepthTest = gl.DepthTest
local glTexture = gl.Texture
local glTexEnv = gl.TexEnv
local glLineWidth = gl.LineWidth
local glPopMatrix = gl.PopMatrix
local glPushMatrix = gl.PushMatrix
local glTranslate = gl.Translate
local glFeatureShape = gl.FeatureShape
local glRotate = gl.Rotate
local spGetGameSeconds = Spring.GetGameSeconds
local spGetMyPlayerID = Spring.GetMyPlayerID
local spGetPlayerInfo = Spring.GetPlayerInfo
local spGetAllFeatures = Spring.GetAllFeatures
local spGetFeaturePosition = Spring.GetFeaturePosition
local spGetFeatureDefID = Spring.GetFeatureDefID
local spGetMyAllyTeamID = Spring.GetMyAllyTeamID
local spGetFeatureAllyTeam = Spring.GetFeatureAllyTeam
local spGetFeatureTeam = Spring.GetFeatureTeam
local spGetUnitHealth = Spring.GetUnitHealth
local spGetFeatureHealth = Spring.GetFeatureHealth
local spGetFeatureResurrect = Spring.GetFeatureResurrect
local spGetPositionLosState = Spring.GetPositionLosState
local spIsUnitAllied = Spring.IsUnitAllied
local spGetUnitDirection = Spring.GetUnitDirection
local spGetFeatureDirection = Spring.GetFeatureDirection
local spGetUnitBasePosition = Spring.GetUnitBasePosition
local spGetUnitHealth = Spring.GetUnitHealth
local spValidFeatureID = Spring.ValidFeatureID
local spEcho = Spring.Echo
local spGetUnitDefID = Spring.GetUnitDefID
local spGetUnitRulesParam = Spring.GetUnitRulesParam
local mdeg = math.deg
local matan2 = math.atan2
local DrawGhostFeatures
local DrawGhostSites
local ScanFeatures
local DeleteGhostFeatures
local DeleteGhostSites
local ResetGl
local CheckSpecState
local firstScan = true
local TooHigh = true
local HighPing = false
local FPSCount = Spring.GetFPS()
local FPSLimit = 8
local dontTrackEnemyWrecks = tonumber(Spring.GetModOptions().mo_enemywrecks) or 0
function widget:Initialize()
if Spring.IsReplay() or Spring.GetGameFrame() > 0 then
widget:PlayerChanged()
end
widgetHandler:RegisterGlobal('DrawManager_ghostsite', DrawStatus)
end
function widget:ShutDown()
widgetHandler:DeregisterGlobal('DrawManager_ghostsite', DrawStatus)
end
function widget:Update()
local timef = spGetGameSeconds()
local time = floor(timef)
-- update timers once every <updateInt> seconds
if (time % updateInt == 0 and time ~= lastTime) then
lastTime = time
--do update stuff:
ScanFeatures()
DeleteGhostSites()
DeleteGhostFeatures()
end
end
function widget:DrawWorld()
if ( TooHigh == true ) or ( FPSCount < FPSLimit ) or ( HighPing == true ) then
return
end
DrawGhostSites()
DrawGhostFeatures()
ResetGl()
end
function widget:UnitEnteredLos(unitID, allyTeam)
if ( spIsUnitAllied( unitID ) ) then
return
end
local udef = udefTab[spGetUnitDefID(unitID)]
if ( udef ~= nil and (udef.isBuilding == true or udef.isFactory == true) and (spGetUnitRulesParam(unitID, "under_construction") == 1)) then
local x, y, z = spGetUnitBasePosition(unitID)
local dx,_,dz = spGetUnitDirection(unitID)
local angle = mdeg(matan2(dx,dz))
ghostSites[unitID] = { unitDefId = spGetUnitDefID(unitID), x=x, y=y, z=z, teamId = allyTeam, angle = angle }
end
end
function DrawStatus(toohigh,fps,ping)
TooHigh = toohigh
FPSCount = fps
HighPing = ping
end
function DrawGhostFeatures()
glColor(1.0, 1.0, 1.0, 0.35 )
glTexture(0,"$units1")
--glTexture(1,"$units1")
glTexEnv( GL.TEXTURE_ENV, GL.TEXTURE_ENV_MODE, 34160 ) --GL_COMBINE_RGB_ARB
--use the alpha given by glColor for the outgoing alpha.
glTexEnv( GL.TEXTURE_ENV, 34162, GL.REPLACE ) --GL_COMBINE_ALPHA
glTexEnv( GL.TEXTURE_ENV, 34184, 34167 ) --GL_SOURCE0_ALPHA_ARB GL_PRIMARY_COLOR_ARB
--------------------------Draw-------------------------------------------------------------
for unitID, ghost in pairs( ghostFeatures ) do
local x, y, z = ghost.x, ghost.y, ghost.z
local _, b, _ = spGetPositionLosState(x, y, z)
local losState = b
if ( losState == false ) then
--glow effect?
--gl.Blending(GL.SRC_ALPHA, GL.ONE)
glPushMatrix()
glTranslate(x, y, z)
glRotate(ghost.angle,0,y,0)
glFeatureShape(ghost["featDefId"], ghost["teamId"] )
glPopMatrix()
end
end
--------------------------Clean up-------------------------------------------------------------
glTexEnv( GL.TEXTURE_ENV, GL.TEXTURE_ENV_MODE, 8448 ) --GL_MODULATE
--use the alpha given by glColor for the outgoing alpha.
glTexEnv( GL.TEXTURE_ENV, 34162, 8448 ) --GL_MODULATE
----gl.TexEnv( GL.TEXTURE_ENV, 34184, 5890 ) --GL_SOURCE0_ALPHA_ARB GL_TEXTURE
end
function DrawGhostSites()
glColor(0.3, 1.0, 0.3, 0.25)
glDepthTest(true)
for unitID, ghost in pairs( ghostSites ) do
local x, y, z = ghost.x, ghost.y, ghost.z
local a, b, c = spGetPositionLosState(x, y, z)
local losState = b
if ( losState == false ) then
--glow effect?
--gl.Blending(GL.SRC_ALPHA, GL.ONE)
glPushMatrix()
glTranslate( x, y, z)
glRotate(ghost.angle,0,y,0)
gl.UnitShape(ghost["unitDefId"], ghost["teamId"], false, true, false)
glPopMatrix()
end
end
end
function ScanFeatures()
local features = spGetAllFeatures()
if firstScan then
if (Spring.GetGameFrame() == 0) then
-- Ignore all the map features we can see before game start
for _, fID in ipairs(features) do
local fDefId = spGetFeatureDefID(fID)
if not ignoreFeature[fDefId] then
local x, y, z = spGetFeaturePosition(fID)
local LosOrRadar, inLos, inRadar = spGetPositionLosState(x, y, z)
if not inLos then
ignoreFeature[fDefId] = true
end
end
end
else
-- Widget loaded mid game, just use original 'ignore trees and rocks' logic
local sfind = string.find
for _, fID in ipairs(features) do
if not ignoreFeature[fDefId] then
local fDefId = spGetFeatureDefID(fID)
local fText = string.lower(FeatureDefs[fDefId].name .. " " .. (FeatureDefs[fDefId].tooltip or ""))
if sfind(fText, 'tree') or sfind(fText, 'rock') then
ignoreFeature[fDefId] = true
end
end
end
end
firstScan = false
return
end
local myAllyID = spGetMyAllyTeamID()
for _, fID in ipairs(features) do
local fDefId = spGetFeatureDefID(fID)
if not ignoreFeature[fDefId] then
local fAllyID = spGetFeatureAllyTeam(fID)
local fTeamID = spGetFeatureTeam( fID )
local resName, _ = spGetFeatureResurrect(fID)
if ( (resName == "" or dontTrackEnemyWrecks == 0) and fAllyID ~= nil and fAllyID >= 0 and myAllyID ~= fAllyID and ghostFeatures[fID] == nil ) then
local x, y, z = spGetFeaturePosition(fID)
local dx,_,dz = spGetFeatureDirection(fID)
local angle = mdeg(matan2(dx,dz))
ghostFeatures[fID] = { featDefId = fDefId, x=x, y=y, z=z, teamId = fTeamID, angle=angle }
end
end
end
end
function DeleteGhostFeatures()
for featureID, ghost in pairs(ghostFeatures) do
local a, b, c = spGetPositionLosState(ghost.x, ghost.y, ghost.z)
local losState = b
local featDefID = spGetFeatureDefID(featureID)
if ( featDefID == nil and losState) then
ghostFeatures[featureID] = nil
end
end
end
function DeleteGhostSites()
for unitID, ghost in pairs(ghostSites) do
local a, b, c = spGetPositionLosState(ghost.x, ghost.y, ghost.z)
local losState = b
local udefID = spGetUnitDefID(unitID)
if ( ( udefID == nil or (spGetUnitRulesParam(unitID, "under_construction") ~= 1) ) and losState) then
ghostSites[unitID] = nil
end
end
end
function widget:GameStart()
if widgetHandler.widgets then
for i, widget in ipairs(widgetHandler.widgets) do
if (widget:GetInfo().name == 'Defense Range') then
local version = tonumber(string.match(widget:GetInfo().desc,'%d+%.%d+'))
if version and (version < tonumber("6")) then
spEcho("<Ghost Site> Old DefenseRange found! Widget removed.")
widgetHandler:RemoveWidget(self)
end
end
end
end
end
--Commons
function ResetGl()
glColor( { 1.0, 1.0, 1.0, 1.0 } )
glLineWidth( 1.0 )
glDepthTest(false)
glTexture(false)
end
function widget:PlayerChanged(playerID)
if Spring.GetSpectatingState() and Spring.GetGameFrame() > 0 then
widgetHandler:RemoveWidget(self)
end
end
function widget:GameStart()
widget:PlayerChanged()
end
|
--[[
Copyright (c) 2015 深圳市辉游科技有限公司.
--]]
local UpdateManager = class('UpdateManager')
local utils = require('utils.utils')
function UpdateManager:ctor(...)
end
function UpdateManager:startCheckUpdate(callback)
local this = self
print('storagePath: ', cc.FileUtils:getInstance():getWritablePath() )
local am = cc.AssetsManagerEx:create('project.manifest', cc.FileUtils:getInstance():getWritablePath())
am:retain()
self.am = am
if _updateManifestUrl then
print('set am remote urls:', _updateManifestUrl, _updateVersionUrl, _updatePackageUrl)
am:setRemoteUrls(_updateManifestUrl, _updateVersionUrl, _updatePackageUrl)
end
if not am:getLocalManifest():isLoaded() then
print("Fail to update assets, step skipped.")
else
local function onUpdateEvent(event)
local eventCode = event:getEventCode()
if eventCode == cc.EventAssetsManagerEx.EventCode.ERROR_NO_LOCAL_MANIFEST then
print("No local manifest file found, skip assets update.")
elseif eventCode == cc.EventAssetsManagerEx.EventCode.UPDATE_PROGRESSION then
local assetId = event:getAssetId()
local percent = event:getPercent()
local strInfo = ""
if assetId == cc.AssetsManagerExStatic.VERSION_ID then
strInfo = string.format("Version file: %d%%", percent)
elseif assetId == cc.AssetsManagerExStatic.MANIFEST_ID then
strInfo = string.format("Manifest file: %d%%", percent)
else
strInfo = string.format("%d%%", percent)
end
print('UPDATE_PROGRESSION: ', strInfo)
elseif eventCode == cc.EventAssetsManagerEx.EventCode.ERROR_DOWNLOAD_MANIFEST or
eventCode == cc.EventAssetsManagerEx.EventCode.ERROR_PARSE_MANIFEST then
print("Fail to download manifest file, update skipped.")
elseif eventCode == cc.EventAssetsManagerEx.EventCode.ASSET_UPDATED then
print("ASSET_UPDATED: ", event:getAssetId())
elseif eventCode == cc.EventAssetsManagerEx.EventCode.NEW_VERSION_FOUND then
print("NEW_VERSION_FOUND.")
elseif eventCode == cc.EventAssetsManagerEx.EventCode.ALREADY_UP_TO_DATE then
print("ALREADY_UP_TO_DATE.")
elseif eventCode == cc.EventAssetsManagerEx.EventCode.UPDATE_FINISHED then
print("Update finished.")
elseif eventCode == cc.EventAssetsManagerEx.EventCode.ERROR_UPDATING then
print("Asset ", event:getAssetId(), ", ", event:getMessage())
end
utils.invokeCallback(callback, event)
end
local listener = cc.EventListenerAssetsManagerEx:create(am,onUpdateEvent)
cc.Director:getInstance():getEventDispatcher():addEventListenerWithFixedPriority(listener, 1)
am:update()
end
end
function UpdateManager:close()
if self.am ~= nil then
self.am:release()
self.am = nil
end
end
return UpdateManager |
pagenumber = 0
local file = io.open(tex.jobname..".fht", "r")
io.input(file)
local pages_ftn_ht = {}
local has_pages_ftn_ht = false
for line in file:lines() do
local line_arr = {}
for i in string.gmatch(line, "%S+") do
table.insert(line_arr, tonumber(i))
end
table.insert(pages_ftn_ht, line_arr)
has_pages_ftn_ht = true
end
io.close(file)
local file = io.open(tex.jobname..".fht", "w")
io.close(file)
if pages_ftn_ht[1] and pages_ftn_ht[1][1] == 0
then
tex.setdimen("global", "my@tcb@ftn@height", pages_ftn_ht[1][2])
end
push_footnotes_below_lines = function (head, group)
for item in node.traverse_id(node.id("whatsit"), head) do
local is_footnote = node.has_attribute(item, 100)
if is_footnote
then
local footnote = node.copy(tex.box[is_footnote])
head, new = node.insert_after(head, item, footnote)
node.set_attribute(new, 200, is_footnote)
item = item.next
new.width = 0
end
end
return head
end
-- crush vlist under hlist
crush_height_of_vlist = function (head, group, size)
for list in node.traverse(head) do
if list.id == node.id("hlist")
then
for item in node.traverse(list) do
local f = node.has_attribute(item, 200)
if f
then
if not node.has_attribute(item, 300)
then
node.set_attribute(item, 300, item.height+item.depth)
item.height = 0
item.depth = 0
else
end
end
end
end
end
return head
end
move_footnote_bottom = function (page_head, group, s)
local yaftnins = node.new("vlist")
local n_head = node.copy_list(page_head)
recur = function (n)
for list in node.traverse(n) do
local footnotebox = node.has_attribute(list, 200)
if footnotebox
then
footnote = node.copy(tex.box[footnotebox])
n_head = node.remove(n_head, list)
if yaftnins
then
yaftnins.list, new = node.insert_after(
yaftnins.list, yaftnins.tail, footnote)
end
elseif list.head
then
n_head = recur(list.head)
end
end
return n_head
end
page_head = recur(n_head)
local split_top
if yaftnins.list
then
tex.box.footins = node.copy(node.vpack(yaftnins.list))
end
return page_head
end
-- called after the page was built (or tried to build)
function page_ftn_height(groupcode)
if groupcode == "after_output"
then
pagenumber = pagenumber+1
if has_pages_ftn_ht
then
for _,l in ipairs(pages_ftn_ht) do
if l[1] == pagenumber
then
tex.setdimen("global", "my@tcb@ftn@height", l[2])
end
end
end
elseif groupcode == "vmode_par" or groupcode == "hmode_par"
then
ftn_ht = get_ftnheight(tex.lists.contrib_head)
if ftn_ht > 0
then
local new_ftn_ht = ftn_ht
file = io.open(tex.jobname..".fht", "r")
io.input(file)
curr_page_ftn_arr = {}
for line in file:lines() do
local curr_line_arr = {}
for i in string.gmatch(line, "%S+") do
table.insert(curr_line_arr, tonumber(i))
end
if curr_line_arr[1] == pagenumber
then
new_ftn_ht = new_ftn_ht + curr_line_arr[2]
else
table.insert(curr_page_ftn_arr, line)
end
end
io.close(file)
table.insert(curr_page_ftn_arr, pagenumber.." "..new_ftn_ht)
local table_string = table.concat(curr_page_ftn_arr, "\n")
file = io.open(tex.jobname..".fht", "w")
io.output(file)
io.write(table_string)
io.close(file)
end
end
end
get_ftnheight = function (n)
local ftnheight = 0
for list in node.traverse(n) do
if node.has_attribute(list, 300)
then
ftnheight = ftnheight + node.get_attribute(list, 300)
node.unset_attribute(list, 300)
elseif node.has_attribute(list, 200)
then
-- ftnheight = ftnheight + list.height + list.depth
elseif list.head
then
ftnheight = ftnheight + get_ftnheight (list.head)
end
end
return ftnheight
end
|
local Registry = {}
local self = Registry
Registry.new_objects = {}
Registry.last_objects = {}
function Registry.initialize(preload)
if not self.preload then
self.base_scripts = {}
local chapter = Kristal.getModOption("chapter") or 2
Game.chapter = chapter
for _,path in ipairs(Utils.getFilesRecursive("data/common", ".lua")) do
local chunk = love.filesystem.load("data/common/"..path..".lua")
self.base_scripts["data/"..path] = chunk
end
for _,path in ipairs(Utils.getFilesRecursive("data/chapter_"..tostring(chapter), ".lua")) do
local chunk = love.filesystem.load("data/chapter_"..tostring(chapter).."/"..path..".lua")
self.base_scripts["data/"..path] = chunk
end
for _,path in ipairs(Utils.getFilesRecursive("datamod/chapter_"..tostring(chapter), ".lua")) do
local chunk = love.filesystem.load("datamod/chapter_"..tostring(chapter).."/"..path..".lua")
self.base_scripts["datamod/"..path] = chunk
end
Registry.initActors()
end
if not preload then
Registry.initObjects()
Registry.initItems()
Registry.initSpells()
Registry.initPartyMembers()
Registry.initEncounters()
Registry.initEnemies()
Registry.initWaves()
Registry.initBullets()
Registry.initCutscenes()
Registry.initTilesets()
Registry.initMaps()
Kristal.modCall("onRegistered")
end
self.preload = preload
end
function Registry.restoreOverridenObjects()
for id,_ in pairs(self.new_objects) do
_G[id] = self.last_objects[id]
end
self.new_objects = {}
self.last_objects = {}
end
-- Getter Functions --
function Registry.getActor(id)
return self.actors[id]
end
function Registry.getItem(id)
return self.items[id]
end
function Registry.getSpell(id)
return self.spells[id]
end
function Registry.getPartyMember(id)
return self.party_members[id]
end
function Registry.getPartyMemberFromActor(id)
return self.party_from_actor[id]
end
function Registry.getEncounter(id)
return self.encounters[id]
end
function Registry.createEncounter(id, ...)
if self.encounters[id] then
return self.encounters[id](...)
else
error("Attempt to create non existent encounter \"" .. id .. "\"")
end
end
function Registry.getEnemy(id)
return self.enemies[id]
end
function Registry.createEnemy(id, ...)
if self.enemies[id] then
return self.enemies[id](...)
else
error("Attempt to create non existent enemy \"" .. id .. "\"")
end
end
function Registry.getWave(id)
return self.waves[id]
end
function Registry.createWave(id, ...)
if self.waves[id] then
return self.waves[id](...)
else
error("Attempt to create non existent wave \"" .. id .. "\"")
end
end
function Registry.getBullet(id)
return self.bullets[id]
end
function Registry.createBullet(id, ...)
if self.bullets[id] then
return self.bullets[id](...)
else
error("Attempt to create non existent bullet \"" .. id .. "\"")
end
end
function Registry.getWorldBullet(id)
return self.world_bullets[id]
end
function Registry.createWorldBullet(id, ...)
if self.world_bullets[id] then
return self.world_bullets[id](...)
else
error("Attempt to create non existent world bullet \"" .. id .. "\"")
end
end
function Registry.getWorldCutscene(group, id)
local cutscene = self.world_cutscenes[group]
if type(cutscene) == "table" then
return cutscene[id], true
elseif type(cutscene) == "function" then
return cutscene, false
end
end
function Registry.getBattleCutscene(group, id)
local cutscene = self.battle_cutscenes[group]
if type(cutscene) == "table" then
return cutscene[id], true
elseif type(cutscene) == "function" then
return cutscene, false
end
end
function Registry.getTileset(id)
return self.tilesets[id]
end
function Registry.getMap(id)
return self.maps[id]
end
function Registry.createMap(id, world, ...)
if self.maps[id] then
local map = self.maps[id](world, self.map_data[id], ...)
map.id = id
return map
elseif self.map_data[id] then
local map = Map(world, self.map_data[id], ...)
map.id = id
return map
else
error("Attempt to create non existent map \"" .. id .. "\"")
end
end
function Registry.getMapData(id)
return self.map_data[id]
end
-- Register Functions --
function Registry.registerActor(id, tbl)
self.actors[id] = tbl
tbl.animations = tbl.animations or {}
tbl.offsets = tbl.offsets or {}
end
function Registry.registerPartyMember(id, tbl)
self.party_members[id] = tbl
if tbl.actor then
self.party_from_actor[tbl.actor] = tbl
end
end
function Registry.registerItem(id, tbl)
self.items[id] = tbl
end
function Registry.registerSpell(id, tbl)
self.spells[id] = tbl
end
function Registry.registerEncounter(id, class)
self.encounters[id] = class
end
function Registry.registerEnemy(id, class)
self.enemies[id] = class
end
function Registry.registerWave(id, class)
self.waves[id] = class
end
function Registry.registerBullet(id, class)
self.bullets[id] = class
end
function Registry.registerWorldBullet(id, class)
self.world_bullets[id] = class
end
function Registry.registerWorldCutscene(id, cutscene)
self.world_cutscenes[id] = cutscene
end
function Registry.registerBattleCutscene(id, cutscene)
self.battle_cutscenes[id] = cutscene
end
function Registry.registerTileset(id, class)
self.tilesets[id] = class
end
function Registry.registerMapData(id, data)
self.map_data[id] = data
end
function Registry.registerMap(id, class)
self.maps[id] = class
end
-- Internal Functions --
function Registry.initObjects()
for _,path,object in self.iterScripts("objects") do
local path_tbl = Utils.split(path, "/")
local new_path = path_tbl[#path_tbl]
local id = object.id or new_path
if id:lower() == id then
print("WARNING: Object '"..id.."' registered in lowercase!")
end
if _G[id] then
print("WARNING: Object '"..id.."' already exists, replacing")
if not self.last_objects[id] then
self.last_objects[id] = _G[id]
end
end
self.new_objects[id] = object
_G[id] = object
end
Kristal.modCall("onRegisterObjects")
end
function Registry.initActors()
self.actors = {}
for _,path,actor in self.iterScripts("data/actors") do
actor.id = actor.id or path
self.registerActor(actor.id, actor)
end
for id,mod in self.iterMods("datamod/actors") do
mod(self.actors[id])
end
Kristal.modCall("onRegisterActors")
end
function Registry.initPartyMembers()
self.party_members = {}
self.party_from_actor = {}
local chars = {}
for _,path,char in self.iterScripts("data/party") do
char.id = char.id or path
chars[char.id] = char
end
for id,mod in self.iterMods("datamod/party") do
mod(chars[id])
end
for id,char in pairs(chars) do
self.registerPartyMember(id, char)
end
end
function Registry.initItems()
self.items = {}
for _,path,item in self.iterScripts("data/items") do
item.id = item.id or path
self.registerItem(item.id, item)
end
for id,mod in self.iterMods("datamod/items") do
mod(self.items[id])
end
Kristal.modCall("onRegisterItems")
end
function Registry.initSpells()
self.spells = {}
for _,path,spell in self.iterScripts("data/spells") do
spell.id = spell.id or path
self.registerSpell(spell.id, spell)
end
for id,mod in self.iterMods("datamod/spells") do
mod(self.spells[id])
end
Kristal.modCall("onRegisterSpells")
end
function Registry.initEncounters()
self.encounters = {}
for _,path,encounter in self.iterScripts("battle/encounters") do
encounter.id = encounter.id or path
self.registerEncounter(encounter.id, encounter)
end
Kristal.modCall("onRegisterEncounters")
end
function Registry.initEnemies()
self.enemies = {}
for _,path,enemy in self.iterScripts("battle/enemies") do
enemy.id = enemy.id or path
self.registerEnemy(enemy.id, enemy)
end
Kristal.modCall("onRegisterEnemies")
end
function Registry.initWaves()
self.waves = {}
for _,path,wave in self.iterScripts("battle/waves") do
wave.id = wave.id or path
self.registerWave(wave.id, wave)
end
Kristal.modCall("onRegisterWaves")
end
function Registry.initBullets()
self.bullets = {}
self.world_bullets = {}
for _,path,bullet in self.iterScripts("battle/bullets") do
bullet.id = bullet.id or path
self.registerBullet(bullet.id, bullet)
end
for _,path,bullet in self.iterScripts("world/bullets") do
bullet.id = bullet.id or path
self.registerWorldBullet(bullet.id, bullet)
end
Kristal.modCall("onRegisterBullets")
end
function Registry.initCutscenes()
self.world_cutscenes = {}
self.battle_cutscenes = {}
for _,path,cutscene in self.iterScripts("world/cutscenes") do
self.registerWorldCutscene(path, cutscene)
end
for _,path,cutscene in self.iterScripts("battle/cutscenes") do
self.registerBattleCutscene(path, cutscene)
end
Kristal.modCall("onRegisterCutscenes")
end
function Registry.initTilesets()
self.tilesets = {}
for full_path,path,data in self.iterScripts("world/tilesets") do
data.full_path = full_path
data.id = path
self.registerTileset(path, Tileset(data, full_path))
end
Kristal.modCall("onRegisterTilesets")
end
function Registry.initMaps()
self.maps = {}
self.map_data = {}
for full_path,path,data in self.iterScripts("world/maps") do
local split_path = Utils.split(path, "/", true)
if isClass(data) then
if split_path[#split_path] == "map" then
self.registerMap(table.concat(split_path, "/", 1, #split_path-1), data)
else
self.registerMap(path, data)
end
else
data.full_path = full_path
if split_path[#split_path] == "data" then
data.id = table.concat(split_path, "/", 1, #split_path-1)
self.registerMapData(data.id, data)
else
data.id = path
self.registerMapData(path, data)
end
end
end
Kristal.modCall("onRegisterMaps")
end
function Registry.iterScripts(base_path)
local result = {}
CLASS_NAME_GETTER = function(k)
for _,v in ipairs(result) do
if v.path == k then
return v.out[1]
end
end
return DEFAULT_CLASS_NAME_GETTER(k)
end
local chunks = nil
local parsed = {}
local addChunk, requireChunk, parse
addChunk = function(path, chunk, id, full_path)
local success,a,b,c,d,e,f = pcall(chunk)
if not success then
if type(a) == "table" and a.included then
requireChunk(path, a.included)
success,a,b,c,d,e,f = pcall(chunk)
if not success then
error(type(a) == "table" and a.msg or a)
end
table.insert(result, {out = {a,b,c,d,e,f}, path = id, full_path = full_path})
else
error(a)
end
else
table.insert(result, {out = {a,b,c,d,e,f}, path = id, full_path = full_path})
return a
end
end
requireChunk = function(path, req_id)
for full_path,chunk in pairs(chunks) do
if not parsed[full_path] and full_path:sub(1, #path) == path then
local id = full_path:sub(#path + 1)
if id:sub(1, 1) == "/" then
id = id:sub(2)
end
if id == req_id then
parsed[full_path] = true
addChunk(path, chunk, id, full_path)
end
end
end
end
parse = function(path, _chunks)
chunks = _chunks
parsed = {}
for full_path,chunk in pairs(chunks) do
if not parsed[full_path] and full_path:sub(1, #path) == path then
local id = full_path:sub(#path + 1)
if id:sub(1, 1) == "/" then
id = id:sub(2)
end
parsed[full_path] = true
addChunk(path, chunk, id, full_path)
end
end
end
parse(base_path, self.base_scripts)
if Mod then
parse("scripts/"..base_path, Mod.info.script_chunks)
end
CLASS_NAME_GETTER = DEFAULT_CLASS_NAME_GETTER
local i = 0
---@diagnostic disable-next-line: undefined-field
local n = table.getn(result)
return function()
i = i + 1
if i <= n then
local full_path = result[i].full_path
if Mod then
full_path = Mod.info.path.."/"..full_path
end
return full_path, result[i].path, unpack(result[i].out)
end
end
end
function Registry.iterMods(base_path)
local result = {}
local function parse(path, chunks)
for full_path,chunk in pairs(chunks) do
if full_path:sub(1, #path) == path then
local id = full_path:sub(#path + 1)
if id:sub(1, 1) == "/" then
id = id:sub(2)
end
local a, b = chunk()
local func = a
if type(a) == "string" then
id = a
func = b
end
table.insert(result, {id = id, func = func})
end
end
end
parse(base_path, self.base_scripts)
if Mod then
parse("scripts/"..base_path, Mod.info.script_chunks)
end
local i = 0
---@diagnostic disable-next-line: undefined-field
local n = table.getn(result)
return function()
i = i + 1
if i <= n then
return result[i].id, result[i].func
end
end
end
return Registry |
somatorio=function(month)
local result = 0
for val = 1,month do
if month <= month then
local p = 1
month = month - 1
p = p + month
result = result + p
end
end
return result
end
wesley_safadao=function(birthday)
if type(birthday)=="string" then
local day,month,year = birthday:match('(%d*)/(%d+)/*(%d+)');
day,month,year = tonumber(day),tonumber(month),tonumber(year);
if day < 32 and day > 0 and month < 13 and month > 0 and year <= tonumber(os.date('%Y')) then
day,month,year = not day and 1 or day,not month and 1 or month,not year and 2000 or tonumber(tostring(year):sub(3));
local safadeza,anjo = 0,0
if day==6 and mes==9 and year==96 then
anjo = "99"
safadeza = "1"
else
safadeza = somatorio(month)+(year/100)*(50-day)
anjo = 100-safadeza
end
local w,x = math.modf(safadeza)
local y,z = math.modf(anjo)
if x == 0 then safadeza = math.floor(safadeza) end
if z == 0 then anjo = math.floor(anjo) end
if safadeza < 100 and safadeza > 0 then
if anjo < 100 and anjo > 0 then
if safadeza + anjo == 100 then
print("\nSafadeza: "..safadeza.."%\nAnjo: "..anjo.."%\n\n\"[...]"..string.char(84,195,180,32,110,97,109,111,114,97,110,100,111,32,116,111,100,111,32,109,117,110,100,111,10)..anjo..string.char(37,32,97,110,106,111,44,32,112,101,114,102,101,105,116,111,10,77,97,115,32,97,113,117,101,108,101,32)..safadeza..string.char(37,32,195,169,32,118,97,103,97,98,117,110,100,111,10,77,97,115,32,97,113,117,101,108,101,32)..safadeza..string.char(37,32,195,169,32,118,97,103,97,98,117,110,100,111,10,83,97,102,97,100,111,32,101,32,101,108,97,115,32,103,111,115,116,97,109).."[...]\"")
else
error("Bug !3. Reporte ao criador")
end
else
error("Bug !2. Reporte ao criador")
end
else
error("Bug !1. Reporte ao criador")
end
else
error("Ninguém pode ter nascido em "..birthday.." ainda. Desculpe, mas você não pode enganar um algoritmo.")
end
end
end
wesley_safadao("01/01/1995") --Sua data de nascimento.
|
LinkLuaModifier('modifier_abaddon_borrowed_time_lua_active', 'heroes/abaddon/borrowed_time', LUA_MODIFIER_MOTION_NONE)
ability_borrowed_time = class({})
function ability_borrowed_time:OnSpellStart()
self:GetCaster():AddNewModifier(self:GetCaster(), self, 'modifier_abaddon_borrowed_time_lua_active', {
duration = self:GetSpecialValueFor('duration')
})
self:GetCaster():EmitSound('Hero_Abaddon.BorrowedTime')
end
--
-- Absorb damage logic in filters.lua [L45 - L56]
--
modifier_abaddon_borrowed_time_lua_active = class({
IsHidden = function(self) return false end,
IsPurgable = function(self) return false end,
IsDebuff = function(self) return false end,
IsBuff = function(self) return true end,
RemoveOnDeath = function(self) return true end,
GetStatusEffectName = function(self) return 'particles/status_fx/status_effect_abaddon_borrowed_time.vpcf' end,
GetEffectName = function(self) return 'particles/units/heroes/hero_abaddon/abaddon_borrowed_time.vpcf' end,
GetEffectAttachType = function(self) return PATTACH_ABSORIGIN_FOLLOW end,
StatusEffectPriority = function(self) return MODIFIER_PRIORITY_HIGH end,
})
function modifier_abaddon_borrowed_time_lua_active:OnCreated()
if IsClient() then return end
self.caster = self:GetCaster()
self.parent = self:GetParent()
self.caster:Purge(false, true, true, true, false)
end
|
object_tangible_holiday_love_day_rewards_11_shared_love_day_2011_painting = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/holiday/love_day/rewards_11/shared_love_day_2011_painting.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_holiday_love_day_rewards_11_shared_love_day_2011_painting, "object/tangible/holiday/love_day/rewards_11/shared_love_day_2011_painting.iff")
|
--------------------------------------
-- LootManager
--------------------------------------
-- Datastructure used by master looter to manage loot items and to determine winners
--------------------------------------
-- DEFINITION + CONSTRUCTOR
--------------------------------------
LootManager = {
master_looter = nil, -- name of the master looter
current_loot = nil, -- Loot object of loot that is being decided on
current_loot_timer = nil, -- timer used to track when decision time has expired for ALL players (each player also has separate timer associated w/ loot gui)
loot_target = nil, -- name of current target for loot distribution
loot_dist_confirm_timer = nil, -- ticker used to check if loot has been successfully sent
CONFIRM_DELAY = nil, -- number of seconds waited after loot distribution to confirm that loot was sent
confirmed_dist = nil, -- boolean used to confirm that loot has been looted
};
LootManager.__index = LootManager;
function LootManager:new(loot_manager)
if loot_manager == nil then
-- initalize fresh
local obj = {};
obj.master_looter = nil;
obj.current_loot = Loot:new(nil);
obj.current_loot_timer = nil;
obj.loot_target = nil;
obj.loot_dist_confirm_timer = nil;
obj.CONFIRM_DELAY = 2.0;
obj.confirmed_dist = false;
setmetatable(obj,LootManager);
return obj;
else
-- reset timer
loot_manager.current_loot_timer = nil;
-- set metatable of existing table
loot_manager.current_loot = Loot:new(loot_manager.current_loot);
setmetatable(loot_manager,LootManager);
return loot_manager;
end
end
--------------------------------------
-- METHODS
--------------------------------------
function LootManager:Reset()
-- reset loot manager
self.master_looter = nil;
self.current_loot = nil;
if self.current_loot_timer ~= nil then self.current_loot_timer:Cancel() end
self.current_loot_timer = nil;
self.loot_target = nil;
if self.loot_dist_confirm_timer ~= nil then self.loot_dist_confirm_timer:Cancel() end
self.loot_dist_confirm_timer = nil;
self.confirmed_dist = false;
return;
end
function LootManager:ForceClose()
-- called when loot manager is forced to close (from player closing loot for example)
-- cancel timers
if self.current_loot_timer ~= nil and not self.current_loot_timer:IsCancelled() then self.current_loot_timer:Cancel() end
if self.loot_dist_confirm_timer ~= nil and not self.loot_dist_confirm_timer:IsCancelled() then
self.loot_dist_confirm_timer:Cancel();
self:LogDist(false);
end
-- hide GUI
SKC:ForceCloseLootDecisionGUI();
-- reset self
self:Reset();
return;
end
function LootManager:GetCurrentLootID()
if self.current_loot == nil then
SKC:Error("Current loot not set");
return nil;
end
return self.current_loot.lootID;
end
function LootManager:GetCurrentLootName()
if self.current_loot == nil then
SKC:Error("Current loot not set");
return nil;
end
return self.current_loot.lootName;
end
function LootManager:GetCurrentLootIndex()
if self.current_loot == nil then
SKC:Error("Current loot not set");
return nil;
end
return self.current_loot.lootIndex;
end
function LootManager:GetCurrentLootLink()
if self.current_loot == nil then
SKC:Error("Current loot not set");
return nil;
end
return self.current_loot.lootLink;
end
function LootManager:GetCurrentOpenRoll()
if self.current_loot == nil then
SKC:Error("Current loot not set");
return nil;
end
return self.current_loot.open_roll;
end
function LootManager:GetCurrentLootSKList()
if self.current_loot == nil then
SKC:Error("Current loot not set");
return nil;
end
return self.current_loot.sk_list;
end
function LootManager:AddLoot(item_id,item_name,loot_index,item_link)
-- add loot as new current_loot
-- check if current loot is not empty
-- MASTER LOOTER ONLY
if not SKC:isML() then
SKC:Error("Cannot AddLoot, not master looter");
return;
end
if self.current_loot ~= nil then
SKC:Error("Current loot is not empty");
end
local open_roll =SKC.db.char.LP:GetOpenRoll(item_name);
local sk_list =SKC.db.char.LP:GetSKList(item_name);
self.current_loot = Loot:new(nil,item_id,item_name,loot_index,item_link,open_roll,sk_list);
self.master_looter = UnitName("player");
-- default, give loot to ML
self.loot_target = self.master_looter;
return;
end
function LootManager:AddCharacter(char_name)
-- add given character as pending loot decision for current_loot
-- MASTER LOOTER ONLY
if not SKC:isML() then
SKC:Error("Cannot AddCharacter, not master looter");
return;
end
-- set player decision to pending
self.current_loot.decisions[char_name] = SKC.LOOT_DECISION.PENDING;
-- save player position
local sk_list = self:GetCurrentLootSKList();
if sk_list == "MSK" or sk_list == "TSK" then
self.current_loot.sk_pos[char_name] = SKC.db.char[sk_list]:GetPos(char_name);
end
-- roll for character
self.current_loot.rolls[char_name] = math.random(100); -- random number between 1 and 100
return;
end
function LootManager:ForceDistribution()
-- forces loot distribution due to timeout
SKC:Warn("Time expired for players to decide on "..self:GetCurrentLootLink());
-- set all currently pending players to pass
for char_name, decision in pairs(self.current_loot.decisions) do
if decision == SKC.LOOT_DECISION.PENDING then
SKC:Warn(char_name.." never responded, automoatically passing");
self.current_loot.decisions[char_name] = SKC.LOOT_DECISION.PASS;
end
end
self:DetermineWinner();
return;
end
local function ForceDistributionWrapper()
-- wrapper because i cant figure out how to call object method from NewTimer()
SKC:Debug("ForceDistributionWrapper",SKC.DEV.VERBOSE.LOOT);
SKC.db.char.LM:ForceDistribution();
return;
end
function ForceDistributionWithDelay()
-- calls kick off function after configurable amount of delay
SKC.db.char.LM.current_loot_timer = C_Timer.NewTimer(SKC.db.char.GLP:GetLootDecisionTime() + 5, ForceDistributionWrapper);
SKC:Debug("Starting current loot timer",SKC.DEV.VERBOSE.LOOT);
return;
end
function LootManager:KickOff()
-- initiates loot decision
-- MASTER LOOTER ONLY
if not SKC:isML() then
SKC:Error("Cannot KickOff, not master looter");
return;
end
-- check that item exists
if self.current_loot == nil then
SKC:Error("Cannot KickOff, current_loot does not exist");
return;
end
local msg = "Loot Decision: "..self:GetCurrentLootLink();
if UnitIsGroupLeader("player") or UnitIsGroupAssistant("player") then
SendChatMessage(msg,"RAID_WARNING");
else
SendChatMessage(msg,"RAID");
end
-- sends loot messages to all elligible players
SKC:Debug("KickOff",SKC.DEV.VERBOSE.LOOT);
self:SendLootMsgs();
-- Start timer for when loot is automatically passed on by players that never responded
-- Put blank message in queue so that timer starts after last message has been sent
SKC:Send("BLANK",SKC.CHANNELS.LOOT,"WHISPER",UnitName("player"),ForceDistributionWithDelay);
return;
end
function LootManager:SendLootMsgs()
-- send loot message to all elligible characters on LOOT
-- construct message
local loot_msg = {
lootID = self.current_loot.lootID,
open_roll = self.current_loot.open_roll,
sk_list = self.current_loot.sk_list,
}
-- scan elligible players and send message
for char_name,_ in pairs(self.current_loot.decisions) do
SKC:Send(loot_msg,SKC.CHANNELS.LOOT,"WHISPER",char_name);
end
return;
end
function LootManager:SendLootDecision(loot_decision)
-- send decision to master looter
local msg = {
lootID = self:GetCurrentLootID(),
lootDecision = loot_decision,
};
SKC:Send(msg,SKC.CHANNELS.LOOT_DECISION,"WHISPER",self.master_looter);
return;
end
function LootManager:LootDecisionPending(verbose)
-- returns true if there is still loot currently being decided on
if (self.current_loot_timer ~= nil and not self.current_loot_timer:IsCancelled()) or
(self.loot_dist_confirm_timer ~= nil and not self.loot_dist_confirm_timer:IsCancelled()) then
-- pending loot decision or confirmation timers
if verbose then SKC:Error("Still waiting on loot distribution for "..self:GetCurrentLootLink()) end
return true;
else
-- no pending loot decision or confirmation timers
return false;
end
end
function LootManager:ReadLootMsg(msg,sender)
-- reads loot message on LOOT (not necessarily ML)
-- saves item as current_loot
if msg == "BLANK" then return end
-- parse data
local item_id = msg.lootID;
local open_roll = msg.open_roll;
local sk_list = msg.sk_list;
local item = Item:CreateFromItemID(item_id)
item:ContinueOnItemLoad(function()
-- fetch data
local item_name = item:GetItemName();
local item_link = item:GetItemLink();
-- check if data is valid
if item_id == nil or type(item_id) ~= "number"
or item_name == nil or type(item_name) ~= "string"
or item_link == nil or type(item_link) ~= "string"
or open_roll == nil or type(open_roll) ~= "boolean"
or sk_list == nil or type(sk_list) ~= "string" then
SKC:Error("Received malformed loot message");
return;
end
-- store data
if not SKC:isML() then
-- reset loot and add item
self:Reset();
self.current_loot = Loot:new(nil,item_id,item_name,nil,item_link,open_roll,sk_list);
else
-- current loot already exists, just check that item matches
if item_id ~= self.current_loot.lootID then
SKC:Error("Received loot message for item that is not current_loot");
end
end
-- save ML
self.master_looter = SKC:StripRealmName(sender);
-- Check that SKC is active for client
if not SKC:CheckActive() then
-- Automatically pass
SKC:Warn("SKC is not active, automatically passing");
self:SendLootDecision(SKC.LOOT_DECISION.PASS);
else
-- start GUI
self:StartPersonalLootDecision();
end
end)
return;
end
function LootManager:StartPersonalLootDecision()
-- initiates a personal loot decision for an elligible player
if self.current_loot == nil then
SKC:Error("No loot to decide on");
return;
end
-- Begins personal loot decision process
local sk_list = self:GetCurrentLootSKList();
local open_roll = self:GetCurrentOpenRoll();
-- Trigger GUI
SKC:DisplayLootDecisionGUI(open_roll,sk_list);
return;
end
function LootManager:ReadLootDecision(msg,sender)
-- read loot decision from loot participant on LOOT_DECISION
-- determines if all decisions received and ready to award loot
-- MASTER LOOTER ONLY
if not SKC:isML() then return end
-- parse data
local char_name = SKC:StripRealmName(sender);
local loot_id = msg.lootID;
local loot_decision = tonumber(msg.lootDecision);
-- check integrity
if char_name == nil or type(char_name) ~= "string"
or loot_id == nil or type(loot_id) ~= "number"
or loot_decision == nil or type(loot_decision) ~= "number" then
local sender_text = sender or "NULL";
SKC:Error("Received malformed decision from "..sender_text);
return;
end
-- confirm that loot decision is for current loot
if self:GetCurrentLootID() ~= loot_id then
-- silently reject if current loot is nil
if self:GetCurrentLootName() ~= nil then
SKC:Error("Received decision for item other than Current Loot ("..self:GetCurrentLootName()..")");
end
return;
end
self.current_loot.decisions[char_name] = loot_decision;
-- calculate / save prio
self:DeterminePrio(char_name);
-- send decision message + write to log
self:LogDecision(char_name);
-- check if still waiting on another player
for char_name_tmp,ld_tmp in pairs(self.current_loot.decisions) do
if ld_tmp == SKC.LOOT_DECISION.PENDING then
SKC:Debug("Waiting on: "..char_name_tmp,SKC.DEV.VERBOSE.LOOT);
return;
end
end
-- Determine winner and award loot
self:DetermineWinner();
return;
end
function LootManager:DeterminePrio(char_name)
-- determines loot prio (SKC.PRIO_TIERS) of given char for current loot
-- get character spec
local spec = SKC.db.char.GD:GetSpecIdx(char_name);
-- start with base prio of item for given spec, then adjust based on character attributes
local loot_name = self.current_loot.lootName;
local prio = SKC.db.char.LP:GetPrio(loot_name,spec);
local sk_res = SKC.db.char.LP:GetSKReserved(loot_name);
local roll_res = SKC.db.char.LP:GetRollReserved(loot_name);
-- get character main / alt status
local status = SKC.db.char.GD:GetData(char_name,"Status"); -- text version (Main or Alt)
local loot_decision = self.current_loot.decisions[char_name];
if loot_decision == SKC.LOOT_DECISION.SK then
if sk_res and status == "Alt" then
prio = prio + SKC.PRIO_TIERS.SK.Main.OS; -- increase prio past that for any main
end
elseif loot_decision == SKC.LOOT_DECISION.ROLL then
if roll_res then
prio = SKC.PRIO_TIERS.ROLL[status];
else
prio = SKC.PRIO_TIERS.ROLL["Main"]; -- default non reserved prio for roll is Main
end
elseif loot_decision == SKC.LOOT_DECISION.PASS then
prio = SKC.PRIO_TIERS.PASS;
end
self.current_loot.prios[char_name] = prio;
return;
end
function LootManager:DetermineWinner()
-- Determines winner for current loot, awards loot to player, and sends alert message to raid
if not SKC:isML() then return end
-- cancel overall timer (which triggers timeout)
if self.current_loot_timer ~= nil then self.current_loot_timer:Cancel() end
-- determine winner
local winner = nil;
local winner_decision = SKC.LOOT_DECISION.PASS;
local winner_prio = SKC.PRIO_TIERS.PASS;
local winner_sk_pos = nil;
local winner_roll = nil; -- random number [0,1)
local sk_list = self.current_loot.sk_list;
-- scan decisions and determine winner
for char_name,loot_decision in pairs(self.current_loot.decisions) do
if loot_decision ~= SKC.LOOT_DECISION.PASS then
local new_winner = false;
local prio_tmp = self.current_loot.prios[char_name];
local sk_pos_tmp = self.current_loot.sk_pos[char_name];
local roll_tmp = self.current_loot.rolls[char_name];
if prio_tmp < winner_prio then
-- higher prio, automatic winner
new_winner = true;
elseif prio_tmp == winner_prio then
-- prio tie
if loot_decision == SKC.LOOT_DECISION.SK then
if sk_pos_tmp < winner_sk_pos then
-- char_name is higher on SK list, new winner
new_winner = true;
end
elseif loot_decision == SKC.LOOT_DECISION.ROLL then
if roll_tmp > winner_roll then
-- char_name won roll (tie goes to previous winner)
new_winner = true;
end
end
end
if new_winner then
-- assign new winner
winner = char_name;
winner_decision = loot_decision;
winner_prio = prio_tmp;
winner_sk_pos = sk_pos_tmp;
winner_roll = roll_tmp;
end
end
end
self.loot_target = winner;
-- determine final outcome
self:DetermineOutcome();
return;
end
function LootManager:DetermineOutcome()
-- determines final outcome of loot determination
-- if no winner selected, decides if DE or GB
-- logs appropriately
if not SKC:isML() then return end
-- check outcome of determination
if self.loot_target ~= nil then
-- log winner and send winner message
self:LogWinnerOutcome();
else
-- everyone passed
local DE = SKC.db.char.LP:GetDE(self.current_loot.lootName);
local disenchanter, banker = SKC.db.char.GD:GetFirstGuildRolesInRaid();
local sk_list = self.current_loot.sk_list;
local loot_name = self:GetCurrentLootName();
local loot_link = self:GetCurrentLootLink();
-- check if DE or GB
if DE then
-- disenchant
event_details = SKC.LOG_OPTIONS["Event Details"].Options.DE;
if disenchanter == nil then
self.loot_target = UnitName("player");
else
self.loot_target = disenchanter;
end
else
-- guild bank
event_details = SKC.LOG_OPTIONS["Event Details"].Options.GB;
if banker == nil then
self.loot_target = UnitName("player");
else
self.loot_target = banker;
end
end
-- log and send message
self:LogNonWinnerOutcome(event_details,self.loot_target,loot_name,loot_link);
end
-- attempt to give loot to loot_target
self:GiveLoot();
return;
end
local function ConfirmLootDistributed()
-- checks if current_loot has been confirmed to have been distributed and write to log / chat accordingly
-- If loot confirmed to have been distributed, perform Live SK if SK decision
if not SKC:isML() then return end
-- check if loot is gone
if SKC.db.char.LM.confirmed_dist or SKC.DEV.LOOT_DIST_DISABLE then
-- confirmed
-- log
SKC.db.char.LM:LogDist(true);
-- perform SK (if necessary)
local loot_target = SKC.db.char.LM.loot_target;
local loot_target_decision = SKC.db.char.LM.current_loot.decisions[loot_target];
if loot_target_decision == SKC.LOOT_DECISION.SK then
-- perform SK on winner (below current live bottom)
local sk_list = SKC.db.char.LM:GetCurrentLootSKList();
local sk_success = SKC.db.char[sk_list]:LiveSK(loot_target);
if not sk_success then
SKC:Error(sk_list.." for "..loot_target.." failed");
end
-- log SK
SKC.db.char.LM:LogWinnerSK();
-- populate data
SKC:PopulateData();
end
else
-- failed
SKC.db.char.LM:LogDist(false);
end
-- reset (also resets confirm timer)
SKC.db.char.LM:Reset();
return;
end
function LootManager:ManageOnLootSlotClear()
-- manages the LOOT_SLOT_CLEARED event
-- checks if current loot was item cleared
if (self.loot_dist_confirm_timer == nil or self.loot_dist_confirm_timer:IsCancelled()) then return end
local current_loot_index = self:GetCurrentLootIndex();
local _, lootName, _, _, _, _, _, _, _ = GetLootSlotInfo(current_loot_index);
self.confirmed_dist = lootName == nil; -- loot is gone
if self.confirmed_dist then
-- loot item cleared, early call to confirmation function
ConfirmLootDistributed();
end
return;
end
function LootManager:StartDistConfirmTimer()
self.loot_dist_confirm_timer = C_Timer.NewTimer(self.CONFIRM_DELAY,ConfirmLootDistributed);
return;
end
function LootManager:GiveLoot()
-- sends current loot to current target
if not SKC:isML() then
SKC:Error("GiveLoot failed. Current player is not Master Looter.");
LootManager:LogDist(false);
return;
end
if self.loot_target == nil then
SKC:Error("GiveLoot failed. loot_target is nil.");
LootManager:LogDist(false);
return;
end
if self.current_loot == nil then
SKC:Error("GiveLoot failed. current_loot is nil.");
LootManager:LogDist(false);
return;
end
-- confirm item is at given index
local lootIndex = self:GetCurrentLootIndex();
if lootIndex == nil then
SKC:Error("GiveLoot failed. LootIndex is nil.");
LootManager:LogDist(false);
return;
end
local _, lootName, _, _, _, _, _, _, _ = GetLootSlotInfo(lootIndex);
if lootName ~= self:GetCurrentLootName() then
local loot_name_str = lootName or "NULL";
local curr_loot_name_str = self:GetCurrentLootName() or "NULL";
SKC:Error("GiveLoot failed. Current loot index ("..lootIndex..") is "..loot_name_str.." which is not current loot ("..curr_loot_name_str..").");
LootManager:LogDist(false);
return;
end
-- find character in raid and give loot
local success = false;
for i_char = 1,40 do
if GetMasterLootCandidate(lootIndex, i_char) == self.loot_target then
if SKC.DEV.LOOT_DIST_DISABLE or SKC.DEV.LOOT_SAFE_MODE then
SKC:Alert("GiveLoot success! (FAKE)");
else
GiveMasterLoot(lootIndex,i_char);
end
success = true;
end
end
if not success then
SKC:Error("GiveLoot failed. "..self.loot_target.." not found in possible master looter candidates.");
LootManager:LogDist(false);
return;
end
-- after delay, check if item is still there, failure if not confirmed in this time (confirmed by loot slot cleared event)
self:StartDistConfirmTimer();
return;
end
function LootManager:LogDecision(char_name)
-- writes player loot decision to log and sends message to raid
--fetch data
local loot_decision = self.current_loot.decisions[char_name];
local loot_name = self:GetCurrentLootName();
local sk_list = self:GetCurrentLootSKList();
local prio = self.current_loot.prios[char_name];
local curr_pos = self.current_loot.sk_pos[char_name];
local roll = self.current_loot.rolls[char_name];
-- Write to log
SKC:WriteToLog(
SKC.LOG_OPTIONS["Event Type"].Options.Decision, --event_type,
SKC.LOOT_DECISION.TEXT_MAP[loot_decision], --event_details,
char_name, --subject
loot_name, --item
sk_list, --sk_list
prio, --prio
curr_pos, --current_sk_pos
"", --new_sk_pos
roll --roll
);
-- send message (if not pass)
if loot_decision ~= SKC.LOOT_DECISION.PASS then
local decision_msg = SKC:FormatWithClassColor(char_name).." [p"..prio.."] wants to ";
if loot_decision == SKC.LOOT_DECISION.ROLL then
decision_msg = decision_msg.."ROLL ("..roll..")";
elseif loot_decision == SKC.LOOT_DECISION.SK then
decision_msg = decision_msg..sk_list.." ("..curr_pos..")";
end
decision_msg = decision_msg.." for "..loot_name;
SKC:Send(decision_msg,SKC.CHANNELS.LOOT_DECISION_PRINT,"RAID");
end
end
function LootManager:LogWinnerOutcome()
-- writes winner outcome to log and sends message to raid
-- fetch data
local winner = self.loot_target;
local winner_decision = self.current_loot.decisions[winner];
local event_details = SKC.LOG_OPTIONS["Event Details"].Options.WSK;
if winner_decision == SKC.LOOT_DECISION.ROLL then
event_details = SKC.LOG_OPTIONS["Event Details"].Options.WR;
end
local loot_name = self:GetCurrentLootName();
local sk_list = self:GetCurrentLootSKList();
local prio = self.current_loot.prios[winner];
local curr_pos = self.current_loot.sk_pos[winner];
local roll = self.current_loot.rolls[winner];
-- write to log
SKC:WriteToLog(
SKC.LOG_OPTIONS["Event Type"].Options.Outcome, --event_type,
event_details, --event_details,
winner, --subject
loot_name, --item
sk_list, --sk_list
prio, --prio
curr_pos, --current_sk_pos
"", --new_sk_pos
roll --roll
);
-- construct message
local loot_link = self:GetCurrentLootLink();
local msg = SKC:FormatWithClassColor(winner).." [p"..prio.."] won "..loot_link.." by ";
if winner_decision == SKC.LOOT_DECISION.SK then
-- sk
msg = msg..sk_list.." ("..curr_pos..")!";
else
-- roll
msg = msg.."ROLL ("..roll..")!";
end
-- send message
SKC:Send(msg,SKC.CHANNELS.LOOT_OUTCOME_PRINT,"RAID");
return;
end
function LootManager:LogWinnerSK()
-- writes winner SK to log and sends message to raid
-- fetch data
local winner = self.loot_target;
local loot_name = self:GetCurrentLootName();
local sk_list = self:GetCurrentLootSKList();
local prio = self.current_loot.prios[winner];
local curr_pos = self.current_loot.sk_pos[winner];
local new_pos = SKC.db.char[sk_list]:GetPos(winner);
-- write to log
SKC:WriteToLog(
SKC.LOG_OPTIONS["Event Type"].Options.SK_Change, --event_type,
SKC.LOG_OPTIONS["Event Details"].Options.AutoSK, --event_details,
winner, --subject
loot_name, --item
sk_list, --sk_list
prio, --prio
curr_pos, --current_sk_pos
new_pos, --new_sk_pos
"" --roll
);
-- construct message
local loot_link = self:GetCurrentLootLink();
local msg = SKC:FormatWithClassColor(winner).." was SK'd for "..loot_link.." on "..sk_list.." ("..curr_pos.." => "..new_pos..")";
-- send message
SKC:Send(msg,SKC.CHANNELS.LOOT_OUTCOME_PRINT,"RAID");
return;
end
function LootManager:LogNonWinnerOutcome(event_details,loot_target,loot_name,loot_link)
-- writes non winner outcome to log and sends message to raid
-- fetch data
-- write to log
SKC:WriteToLog(
SKC.LOG_OPTIONS["Event Type"].Options.Outcome, --event_type,
event_details, --event_details,
loot_target, --subject
loot_name, --item
"", --sk_list
"", --prio
"", --current_sk_pos
"", --new_sk_pos
"" --roll
);
-- construct message
local msg;
local send_msg = false;
if event_details == SKC.LOG_OPTIONS["Event Details"].Options.DE then
-- all pass --> disenchant
msg = "Everyone selected PASS for "..loot_link..", sending to "..SKC:FormatWithClassColor(loot_target).." to be DISENCHANTED.";
send_msg = true;
elseif event_details == SKC.LOG_OPTIONS["Event Details"].Options.GB then
-- all pass --> guild bank
msg = "Everyone selected PASS for "..loot_link..", sending to "..SKC:FormatWithClassColor(loot_target).." for the GUILD BANK.";
send_msg = true;
elseif event_details == SKC.LOG_OPTIONS["Event Details"].Options.NLP then
-- not in loot prio --> give to ML
SKC:Debug("Item not in Loot Prio. Giving directly to ML",self.DEV.VERBOSE.LOOT);
elseif event_details == SKC.LOG_OPTIONS["Event Details"].Options.NE then
-- no elligible players in raid --> give to ML
SKC:Debug("No elligible characters in raid. Giving directly to ML",self.DEV.VERBOSE.LOOT);
end
-- send message
if send_msg then SKC:Send(msg,SKC.CHANNELS.LOOT_OUTCOME_PRINT,"RAID") end
return;
end
function LootManager:LogDist(success)
-- writes distribution event to log and sends message to raid
-- fetch data
local loot_name = self:GetCurrentLootName();
local loot_target = self.loot_target;
local event_details;
if success then
event_details = SKC.LOG_OPTIONS["Event Details"].Options.ALS;
else
event_details = SKC.LOG_OPTIONS["Event Details"].Options.ALF;
end
-- write to log
SKC:WriteToLog(
SKC.LOG_OPTIONS["Event Type"].Options.LD, --event_type,
event_details, --event_details,
loot_target, --subject
loot_name, --item
"", --sk_list
"", --prio
"", --current_sk_pos
"", --new_sk_pos
"" --roll
);
-- construct message
-- send message
local loot_link = self:GetCurrentLootLink() or "NULL";
local loot_target_formatted = "NULL";
if loot_target ~= nil then
loot_target_formatted = SKC:FormatWithClassColor(loot_target);
end
if success then
SKC:Send("Gave "..loot_link.." to "..loot_target_formatted..", loot distribution |cff00ff00SUCCESS|r.",SKC.CHANNELS.LOOT_OUTCOME_PRINT,"RAID");
else
SKC:Send("Could not give "..loot_link.." to "..loot_target_formatted..", loot distribution |cffff0000FAILURE|r.",SKC.CHANNELS.LOOT_OUTCOME_PRINT,"RAID");
end
return;
end |
require("helper")
sta = {}
local sta_tmr
local change = true
function sta.setTimer(input_tmr)
sta_tmr = input_tmr
end
function sta.setChange(val)
change = val
end
function sta.setup()
if change then
wifi.sta.config(helper.getConfig().sta)
change = false
elseif wifi.sta.getip() ~= nil then
if sta_tmr ~= nil then
sta_tmr:stop()
end
helper.log("sta ip :" .. wifi.sta.getip())
end
end
return sta
|
object_ship_twing = object_ship_shared_twing:new {
}
ObjectTemplates:addTemplate(object_ship_twing, "object/ship/twing.iff")
|
-- Deal50: A game inspired by the TV show
-- Developed by Joaquin
-- Final project for GD50 2020
Banker = Class{}
function Banker:init(def)
-- Grab cases
self.cases = def.cases or {}
-- Grab number of cases to open
self.casesToOpen = def.casesToOpen or 6
-- Count the number of unopened cases and store their total,
-- along with storing the maximum case value within the pool
-- of unopened cases.
self.unopenedCount = 0
self.unopenedTotal = 0
self.maxCaseValue = 0
for i = 1, #CASE_VALUES do
if not self.cases[i].isOpened then
self.unopenedCount = self.unopenedCount + 1
self.unopenedTotal = self.unopenedTotal + self.cases[i].pointValue
if self.cases[i].pointValue > self.maxCaseValue then
self.maxCaseValue = self.cases[i].pointValue
end
end
end
--[[
Calculate the banker's offer.
The algorithm implemented here starts with
more stingy values if the casesToOpen rate
is high, as seen in the first rounds, but
makes more refined offers as the player
nears the end of the game.
Get the whole total of unopened case
values, divided by number of cases minus
a random value from 0, to unopened count
minus 1 divided by number of cases left
to open plus 1. Plus a random value from
0, to 1000 divided by number of cases to
open. Use math.ceil to round out value.
Check up to 10 times. If offer is higher
than max case value, divide offer by 1.5
and keep dividing until it is lower than
the max case value amount.
]]
self.offer = math.ceil(
(
self.unopenedTotal/(
self.unopenedCount - math.random(0, (self.unopenedCount-1)/(self.casesToOpen+1))
)
) + math.random(0, 1000/self.casesToOpen)
)
for i = 1, 10 do
if self.offer > self.maxCaseValue then
self.offer = math.ceil(self.offer/1.5)
else
break
end
end
-- Animation frame
self.animFrame = 1
-- X flip that should store either 1 or -1
self.xFlip = 1
-- Boolean toggles for tweens
self.blink = true
self.tail = true
end
function Banker:update()
-- Blink when random value from 1 to 500
-- equals 1 and we're not blinking yet
if (math.random(1, 500) == 1) and self.blink then
self.blink = false
self.animFrame = 2
Timer.after(0.25, function()
self.animFrame = 1
self.blink = true
end)
end
-- Flail tail when random value from 1 to 500
-- equals 1 and we're not blinking yet
if (math.random(1, 500) == 1) and self.tail then
self.tail = false
self.xFlip = -1
Timer.after(0.25, function()
self.xFlip = 1
self.tail = true
end)
end
end
function Banker:render()
-- Local variable to store position multiple
-- when mirroring from X
local xFlipPos = 1
-- If flipping, set flip pos multiple to 4
if self.xFlip == -1 then
xFlipPos = 2.5
end
self:printPrompt("I would like to offer", 0)
self:printOffer(self.offer)
self:printPrompt("points", 70)
-- Render banker graphic
love.graphics.draw(
-- Use cat graphic
gameTex['cat'], gameFrames['cat'][self.animFrame],
-- Position on the top left of the screen
-- Nudge position accordingly if graphic is flipped
(VIRTUAL_WIDTH/6)*xFlipPos, VIRTUAL_HEIGHT/24,
-- No rotate
0,
-- Scale by 4, flip when needed
4*self.xFlip, 4
)
end
function Banker:printPrompt(text, yOffset)
-- Set prompt font
love.graphics.setFont(gameFonts['medium'])
-- Set shadow color
love.graphics.setColor(0, 0, 0, 255 / 2)
-- Print enter prompt shadow
love.graphics.printf(text, 59, (VIRTUAL_HEIGHT / 12 + 1) + 20 + yOffset, VIRTUAL_WIDTH, 'center')
-- Set the color for the prompt
love.graphics.setColor(255, 255, 255, 255)
-- Print the prompt
-- The prompt is shifted by one pixel to the
-- left to avoid nearest neighbor artifacting.
love.graphics.printf(text, 57, (VIRTUAL_HEIGHT / 12 - 1) + 20 + yOffset, VIRTUAL_WIDTH, 'center')
end
function Banker:printOffer(offer)
-- Set offer font
love.graphics.setFont(gameFonts['title'])
-- Set shadow color
love.graphics.setColor(0, 0, 0, 255 / 2)
-- Print enter offer shadow
love.graphics.printf(offer, 60, (VIRTUAL_HEIGHT / 12 + 1) + 20, VIRTUAL_WIDTH, 'center')
-- Set the color for the offer to yellow
love.graphics.setColor(255, 255, 0, 255)
-- Print the offer
-- The offer is shifted by one pixel to the
-- left to avoid nearest neighbor artifacting.
love.graphics.printf(offer, 58, (VIRTUAL_HEIGHT / 12 - 1) + 20, VIRTUAL_WIDTH, 'center')
end |
local PANEL = {}
AccessorFunc( PANEL, "m_pMenu", "Menu" )
AccessorFunc( PANEL, "m_bChecked", "Checked" )
AccessorFunc( PANEL, "m_bCheckable", "IsCheckable" )
function PANEL:Init()
self:SetContentAlignment( 4 )
self:SetTextInset( 30, 0 ) -- Room for icon on left
self:SetTextColor( Color( 10, 10, 10 ) )
self:SetChecked( false )
end
function PANEL:SetSubMenu( menu )
self.SubMenu = menu
if ( !self.SubMenuArrow ) then
self.SubMenuArrow = vgui.Create( "DPanel", self )
self.SubMenuArrow.Paint = function( panel, w, h ) derma.SkinHook( "Paint", "MenuRightArrow", panel, w, h ) end
end
end
function PANEL:AddSubMenu()
local SubMenu = DermaMenu( self )
SubMenu:SetVisible( false )
SubMenu:SetParent( self )
self:SetSubMenu( SubMenu )
return SubMenu
end
function PANEL:OnCursorEntered()
if ( IsValid( self.ParentMenu ) ) then
self.ParentMenu:OpenSubMenu( self, self.SubMenu )
return
end
self:GetParent():OpenSubMenu( self, self.SubMenu )
end
function PANEL:OnCursorExited()
end
function PANEL:Paint( w, h )
derma.SkinHook( "Paint", "MenuOption", self, w, h )
--
-- Draw the button text
--
return false
end
function PANEL:OnMousePressed( mousecode )
self.m_MenuClicking = true
DButton.OnMousePressed( self, mousecode )
end
function PANEL:OnMouseReleased( mousecode )
DButton.OnMouseReleased( self, mousecode )
if ( self.m_MenuClicking && mousecode == MOUSE_LEFT ) then
self.m_MenuClicking = false
CloseDermaMenus()
end
end
function PANEL:DoRightClick()
if ( self:GetIsCheckable() ) then
self:ToggleCheck()
end
end
function PANEL:DoClickInternal()
if ( self:GetIsCheckable() ) then
self:ToggleCheck()
end
if ( self.m_pMenu ) then
self.m_pMenu:OptionSelectedInternal( self )
end
end
function PANEL:ToggleCheck()
self:SetChecked( !self:GetChecked() )
self:OnChecked( self:GetChecked() )
end
function PANEL:OnChecked( b )
end
function PANEL:PerformLayout()
self:SizeToContents()
self:SetWide( self:GetWide() + 30 )
local w = math.max( self:GetParent():GetWide(), self:GetWide() )
self:SetSize( w, 22 )
if ( self.SubMenuArrow ) then
self.SubMenuArrow:SetSize( 15, 15 )
self.SubMenuArrow:CenterVertical()
self.SubMenuArrow:AlignRight( 4 )
end
DButton.PerformLayout( self )
end
function PANEL:GenerateExample()
-- Do nothing!
end
derma.DefineControl( "DMenuOption", "Menu Option Line", PANEL, "DButton" )
|
-- Save Player Data to Saved Variables
--Solvent Proficiency, Metalworking, Tailoring, (Aspect Improvement, Potency Improvement), Recipe Quality, Recipe Improvement, Woodworking
local matchNameList1 = {GetString(ESOA_FULL_SUB_SOLV), GetString(ESOA_FULL_SUB_METAL), GetString(ESOA_FULL_SUB_TAIL), GetString(ESOA_FULL_SUB_ASPIMP), GetString(ESOA_FULL_SUB_RECQUA), GetString(ESOA_FULL_SUB_WOOD), GetString(ESOA_FULL_SUB_ENGRAV) }
local matchNameList2 = {GetString(ESOA_FULL_SUB_POTIMPR), GetString(ESOA_FULL_SUB_RECIMPR) }
local SLOT_TYPE_REV = {
EQUIP_SLOT_HEAD = "Head",
EQUIP_SLOT_NECK = "Neck",
EQUIP_SLOT_SHOULDERS = "Shoulders",
EQUIP_SLOT_CHEST = "Chest",
EQUIP_SLOT_WAIST = "Waist",
EQUIP_SLOT_WRIST = "Wrist",
EQUIP_SLOT_FEET = "Feet", --9
EQUIP_SLOT_HAND = "Hand",
EQUIP_SLOT_LEGS = "Legs",
EQUIP_SLOT_BACKUP_MAIN = "ScndMain",
EQUIP_SLOT_BACKUP_OFF = "ScndOff",
EQUIP_SLOT_BACKUP_POISON = "ScndPoison",
EQUIP_SLOT_OFF_HAND = "OffHand",
EQUIP_SLOT_POISON = "MainPoison",
EQUIP_SLOT_MAIN_HAND = "MainHand",
EQUIP_SLOT_RANGED = "Ranged",
EQUIP_SLOT_CLASS1 = "Class1",
EQUIP_SLOT_CLASS2 = "Class2",
EQUIP_SLOT_CLASS3 = "Class3",
EQUIP_SLOT_COSTUME = "Costume",
EQUIP_SLOT_RING1 = "Ring1",
EQUIP_SLOT_RING2 = "Ring2",
EQUIP_SLOT_NONE = "None",
}
--
function ElderScrollsOfAlts.SavePlayerData( playerLineKey, keyName, elementData )
if( ElderScrollsOfAlts.altData.players[playerLineKey] ~= nil ) then
ElderScrollsOfAlts.altData.players[playerLineKey][keyName] = elementData
ElderScrollsOfAlts.debugMsg("SavePlayerData: player=",playerLineKey," keyName=",keyName," as ", elementData)
end
end
-- Read all data from the game Player Object into this Addon
function ElderScrollsOfAlts:DataSaveLivePlayer()
ElderScrollsOfAlts.debugMsg("DataSaveLivePlayer: called")
--
if(ElderScrollsOfAlts.view.pauseactivesave) then
ElderScrollsOfAlts.debugMsg( GetString(ESOA_MSG_PAUSED) )
return
end
local isInDungeon = IsUnitInDungeon("player")
if(isInDungeon and ElderScrollsOfAlts.savedVariables.dontLoadDataInDungeon ) then
ElderScrollsOfAlts.debugMsg("SavePlayerDataForGui:", " stopping per in instance")
return
end
local isInCombat = IsUnitInCombat("player")
if(isInCombat and ElderScrollsOfAlts.savedVariables.dontLoadDataInCombat ) then
ElderScrollsOfAlts.debugMsg("SavePlayerDataForGui:", " stopping per in combat")
return
end
local isPvPFlagged = IsUnitPvPFlagged("player")
if(isInCombat and ElderScrollsOfAlts.savedVariables.dontLoadDataWhilePvPFlagged ) then
ElderScrollsOfAlts.debugMsg("SavePlayerDataForGui:", " stopping per is PvPFlagged")
return
end
ElderScrollsOfAlts.debugMsg( GetString(ESOA_MSG_ACTIVE) )
--
----Section: Statup section
local pName = GetUnitName("player")
local rName = GetRawUnitName("player")
local pID = GetCurrentCharacterId()
local pServer = GetWorldName()
local playerKey = pID.."_".. pServer:gsub(" ","_")
ElderScrollsOfAlts.view.whoiamplayerKey = tostring(playerKey)
--local timeTotalStart = GetFrameTimeSeconds()
--ElderScrollsOfAlts.debugMsg("timeTotalStart: " .. tostring(timeTotalStart) )
--debugMsg("pName='"..tostring(pName).."'" )
if ElderScrollsOfAlts.altData.players == nil then
ElderScrollsOfAlts.altData.players = {}
end
--[[ not callable here?
ElderScrollsOfAlts.view.playersexisting = {}
local numchars = ZO_AddOnManager:GetNumCharacters()
for characterIndex = 1, numchars do
--local name, _, _, _, _, _, characterId = GetCharacterInfo(i)
local name, gender, level, championPoints, class, race, alliance, id, locationId, order, needsRename = GetCharacterInfo(characterIndex)
ElderScrollsOfAlts.view.playersexisting[name] = {}
ElderScrollsOfAlts.view.playersexisting[name].order = order
ElderScrollsOfAlts.debugMsg("ESOA, playersexisting: '", ElderScrollsOfAlts.view.playersexisting[name] , "'")
end
--]]
local dataToProtect = {
"category", "championpointsactive", "championpoints", "tracking", "note", "companions", "playerscreenorder",
}
ElderScrollsOfAlts.view.tempsave = {}
----Section: Protect section
--Protect data not loaded from player data API
if( ElderScrollsOfAlts.altData.players[playerKey] ~= nil ) then
ElderScrollsOfAlts.debugMsg("Checking preexisting data to preserve")
--Protect note data if not saved to disk in this session
--[[if( ElderScrollsOfAlts.altData.players[playerKey].note ~= nil ) then
ElderScrollsOfAlts.view.currentnote = ElderScrollsOfAlts.altData.players[playerKey].note
ElderScrollsOfAlts.debugMsg("ESOA, saved current note, as '", tostring(ElderScrollsOfAlts.altData.players[playerKey].note) , "'")
end--]]
if( ElderScrollsOfAlts.altData.players[playerKey].playersorder ~= nil ) then
ElderScrollsOfAlts.view.currentorder = ElderScrollsOfAlts.altData.players[playerKey].playersorder
ElderScrollsOfAlts.debugMsg("ESOA, saved current order, as '", tostring(ElderScrollsOfAlts.altData.players[playerKey].playersorder) , "'")
else
ElderScrollsOfAlts.altData.playersorderlast = ElderScrollsOfAlts.altData.playersorderlast + 1
ElderScrollsOfAlts.altData.players[playerKey].playersorder = ElderScrollsOfAlts.altData.playersorderlast
ElderScrollsOfAlts.view.currentorder = ElderScrollsOfAlts.altData.players[playerKey].playersorder
ElderScrollsOfAlts.debugMsg("ESOA, saved current order, as '", tostring(ElderScrollsOfAlts.altData.players[playerKey].playersorder) , "'")
end
--
for key,value in pairs(dataToProtect) do
if( ElderScrollsOfAlts.altData.players[playerKey][value]~=nil ) then
ElderScrollsOfAlts.view.tempsave[value] = ElderScrollsOfAlts.altData.players[playerKey][value]
ElderScrollsOfAlts.debugMsg("ESOA, saved current '" .. value.."', as '", tostring(ElderScrollsOfAlts.altData.players[playerKey][value]) , "'")
end
end
else
ElderScrollsOfAlts.debugMsg("No preexisting data to preserve")
end
--
ElderScrollsOfAlts.view.previousversion = nil
if(ElderScrollsOfAlts.altData.players[playerKey] ~= nil and ElderScrollsOfAlts.altData.players[playerKey].version~=nil)then
ElderScrollsOfAlts.view.previousversion = ElderScrollsOfAlts.altData.players[playerKey].version
end
--- Reset Old Data Format infavor of new format
ElderScrollsOfAlts.altData.players[pName] = nil
--- Initialize New Data Format (to reset all my data to current data)
ElderScrollsOfAlts.altData.players[playerKey] = {}
ElderScrollsOfAlts.altData.players[playerKey].category = "A"
ElderScrollsOfAlts.altData.players[playerKey].version = ElderScrollsOfAlts.version
ElderScrollsOfAlts.altData.players[playerKey].previousversion = ElderScrollsOfAlts.view.previousversion
----Section: BIO section
if ElderScrollsOfAlts.altData.players[playerKey].bio == nil then
ElderScrollsOfAlts.altData.players[playerKey].bio = {}
end
ElderScrollsOfAlts.altData.players[playerKey].bio.server = pServer
ElderScrollsOfAlts.altData.players[playerKey].bio.id = pID
ElderScrollsOfAlts.altData.players[playerKey].bio.name = pName
ElderScrollsOfAlts.altData.players[playerKey].bio.rawname = rName
local pGender = GetUnitGender("player")
ElderScrollsOfAlts.altData.players[playerKey].bio.gender = pGender
local pLvl = GetUnitLevel("player")
ElderScrollsOfAlts.altData.players[playerKey].bio.level = pLvl
local canChampPts = CanUnitGainChampionPoints("player")
ElderScrollsOfAlts.altData.players[playerKey].bio.canchamppts = canChampPts
ElderScrollsOfAlts.altData.players[playerKey].bio.champion = nil
if canChampPts then
--TODO Not sure what effective level means
--ElderScrollsOfAlts.altData.players[playerKey].bio.level = GetUnitEffectiveLevel("player")
ElderScrollsOfAlts.altData.players[playerKey].bio.champion = GetUnitChampionPoints("player")
end
local xpleft = GetNumExperiencePointsInLevel(pLvl)
if not xpleft then
--d("You can't level up any further.")
else
ElderScrollsOfAlts.altData.players[playerKey].bio.xpleft = xpleft
--d("It takes " .. xpleft .. " XP to get from the start of this level to the next level.")
end
ElderScrollsOfAlts.altData.players[playerKey].bio.unitxp = GetUnitXP("player")
ElderScrollsOfAlts.altData.players[playerKey].bio.unitxpmax = GetUnitXPMax("player")
local pRace = GetUnitRace("player")
ElderScrollsOfAlts.altData.players[playerKey].bio.race = pRace
--GetUnitRaceId(string unitTag)
local pClass = GetUnitClass("player")
ElderScrollsOfAlts.altData.players[playerKey].bio.class = pClass
local pClassId = GetUnitClassId("player")
ElderScrollsOfAlts.altData.players[playerKey].bio.classId = pClassId
local pAlliance = GetUnitAlliance("player")
ElderScrollsOfAlts.altData.players[playerKey].bio.alliance = pAlliance
--local value = GetPlayerStat(self.statType, STAT_BONUS_OPTION_APPLY_BONUS)
if ElderScrollsOfAlts.altData.players[playerKey].stats == nil then
ElderScrollsOfAlts.altData.players[playerKey].stats = {}
end
--Werewolf or Vampire
ElderScrollsOfAlts.altData.players[playerKey].bio.Werewolf = false
ElderScrollsOfAlts.altData.players[playerKey].bio.Vampire = false
local current, max, effectiveMax = GetUnitPower("player", POWERTYPE_STAMINA)
ElderScrollsOfAlts.altData.players[playerKey].stats["stamina"] = max
current, max, effectiveMax = GetUnitPower("player", POWERTYPE_HEALTH)
ElderScrollsOfAlts.altData.players[playerKey].stats["health"] = max
current, max, effectiveMax = GetUnitPower("player", POWERTYPE_MAGICKA)
ElderScrollsOfAlts.altData.players[playerKey].stats["magicka"] = max
current, max, effectiveMax = GetUnitPower("player", POWERTYPE_POWER)
ElderScrollsOfAlts.altData.players[playerKey].stats["power"] = max
--POWERTYPE_WEREWOLF
--POWERTYPE_FERVOR
--POWERTYPE_COMBO
--POWERTYPE_CHARGES
--POWERTYPE_MOUNT_STAMINA
----Section: Abilities/Skills section
if ElderScrollsOfAlts.altData.players[playerKey].skills == nil then
ElderScrollsOfAlts.altData.players[playerKey].skills = {}
end
local baseElem = nil
local outputUndiscovered = false
--
skillType = SKILL_TYPE_ARMOR
outputUndiscovered = true
ElderScrollsOfAlts.altData.players[playerKey].skills.armor = {}
ElderScrollsOfAlts.altData.players[playerKey].skills.armor.typelist = {}
baseElem = ElderScrollsOfAlts.altData.players[playerKey].skills.armor.typelist
ElderScrollsOfAlts:SaveDataSkillData(skillType,baseElem,outputUndiscovered)
--
skillType = SKILL_TYPE_WORLD
outputUndiscovered = false
ElderScrollsOfAlts.altData.players[playerKey].skills.world = {}
ElderScrollsOfAlts.altData.players[playerKey].skills.world.typelist = {}
baseElem = ElderScrollsOfAlts.altData.players[playerKey].skills.world.typelist
ElderScrollsOfAlts:SaveDataSkillData(skillType,baseElem)
--
skillType = SKILL_TYPE_CLASS
outputUndiscovered = false
ElderScrollsOfAlts.altData.players[playerKey].skills.class = {}
ElderScrollsOfAlts.altData.players[playerKey].skills.class.typelist = {}
baseElem = ElderScrollsOfAlts.altData.players[playerKey].skills.class.typelist
ElderScrollsOfAlts:SaveDataSkillData(skillType,baseElem)
--
skillType = SKILL_TYPE_GUILD
outputUndiscovered = false
ElderScrollsOfAlts.altData.players[playerKey].skills.guild = {}
ElderScrollsOfAlts.altData.players[playerKey].skills.guild.typelist = {}
baseElem = ElderScrollsOfAlts.altData.players[playerKey].skills.guild.typelist
ElderScrollsOfAlts:SaveDataSkillData(skillType,baseElem)
--
skillType = SKILL_TYPE_RACIAL
outputUndiscovered = false
ElderScrollsOfAlts.altData.players[playerKey].skills.racial = {}
ElderScrollsOfAlts.altData.players[playerKey].skills.racial.typelist = {}
baseElem = ElderScrollsOfAlts.altData.players[playerKey].skills.racial.typelist
ElderScrollsOfAlts:SaveDataSkillData(skillType,baseElem)
--
skillType = SKILL_TYPE_WEAPON
outputUndiscovered = false
ElderScrollsOfAlts.altData.players[playerKey].skills.weapon = {}
ElderScrollsOfAlts.altData.players[playerKey].skills.weapon.typelist = {}
baseElem = ElderScrollsOfAlts.altData.players[playerKey].skills.weapon.typelist
ElderScrollsOfAlts:SaveDataSkillData(skillType,baseElem)
--
skillType = SKILL_TYPE_AVA
outputUndiscovered = false
ElderScrollsOfAlts.altData.players[playerKey].skills.ava = {}
ElderScrollsOfAlts.altData.players[playerKey].skills.ava.typelist = {}
baseElem = ElderScrollsOfAlts.altData.players[playerKey].skills.ava.typelist
ElderScrollsOfAlts:SaveDataSkillData(skillType,baseElem)
--SKILL_TYPE_NONE TODO ?
--
skillType = SKILL_TYPE_TRADESKILL
outputUndiscovered = true
ElderScrollsOfAlts.altData.players[playerKey].skills.trade = {}
local baseTableElem = ElderScrollsOfAlts.altData.players[playerKey].skills.trade
baseTableElem.typelist = {}
baseTableElem.skills = {}
numSkillLines = GetNumSkillLines(skillType)
for ii = 1, numSkillLines do
--name, number rank, boolean discovered, number skillLineId, boolean advised, unlockText
local name, rank, discovered, skillLineId, advised, unlockText = GetSkillLineInfo(skillType,ii)
if name == nil then
name = ii;
end
name = zo_strformat( "<<1>>", name ) -- get rid of links and junk?
baseTableElem.typelist[name] = {}
local selElemTable = baseTableElem.typelist[name]
local numAbilities = GetNumSkillAbilities(skillType, ii)
selElemTable.name = name
selElemTable.idx = ii
selElemTable.rank = rank
selElemTable.numAbilities = numAbilities
selElemTable.skillLineId = skillLineId
local lastRankXP, nextRankXP, currentXP = GetSkillLineXPInfo( skillType, ii )
selElemTable.lastRankXP = lastRankXP
selElemTable.nextRankXP = nextRankXP
selElemTable.currentXP = currentXP
ElderScrollsOfAlts.SaveDataPlayerTradeDetails( name, baseTableElem, selElemTable, skillType, ii, numAbilities )
end
--Check Specific Skilllines
--ElderScrollsOfAlts.altData.players[playerKey].skills.world.typelist = {}
--Werewolf or Vampire
for key,value in pairs(ElderScrollsOfAlts.altData.players[playerKey].skills.world.typelist) do
--print(key,value)
if key == "Werewolf" then
ElderScrollsOfAlts.altData.players[playerKey].bio.Werewolf = true
elseif key == "Vampire" then
ElderScrollsOfAlts.altData.players[playerKey].bio.Vampire = true
end
end
----Section: Misc section
if(ElderScrollsOfAlts.altData.players[playerKey].misc==nil) then
ElderScrollsOfAlts.altData.players[playerKey].misc = {}
end
ElderScrollsOfAlts.altData.players[playerKey].misc.now = GetTimeStamp()--ZO_FormatClockTime()
--Riding
local inventoryBonus, maxInventoryBonus, staminaBonus, maxStaminaBonus, speedBonus, maxSpeedBonus = GetRidingStats()
ElderScrollsOfAlts.altData.players[playerKey].misc.riding = {}
ElderScrollsOfAlts.altData.players[playerKey].misc.riding.inventory = inventoryBonus
ElderScrollsOfAlts.altData.players[playerKey].misc.riding.stamina = staminaBonus
ElderScrollsOfAlts.altData.players[playerKey].misc.riding.speed = speedBonus
local canTrainRiding = false
if(speedBonus < maxSpeedBonus)then
canTrainRiding = true
elseif (staminaBonus < maxStaminaBonus) then
canTrainRiding = true
elseif(inventoryBonus < maxInventoryBonus) then
canTrainRiding = true
end
ElderScrollsOfAlts.altData.players[playerKey].misc.riding.cantrain = canTrainRiding
local timeMs, totalDurationMs = GetTimeUntilCanBeTrained()
ElderScrollsOfAlts.altData.players[playerKey].misc.riding.timeMs = timeMs
ElderScrollsOfAlts.altData.players[playerKey].misc.riding.totalDurationMs = totalDurationMs
ElderScrollsOfAlts.altData.players[playerKey].misc.riding.timeDataTaken = GetTimeStamp()--secconds
if(timeMs<1)then
ElderScrollsOfAlts.altData.players[playerKey].misc.riding.trainingReadyAt = 0
else
--ElderScrollsOfAlts.debugMsg("timeMs="..tostring(timeMs) )
local expiresAt = GetTimeStamp() + ( timeMs/1000 )
--local expiresAt = GetTimeStamp() + timeMs
ElderScrollsOfAlts.altData.players[playerKey].misc.riding.trainingReadyAt = expiresAt
end
-- Bags
local bagSize = GetBagSize(BAG_BACKPACK)
local bagUsed = GetNumBagUsedSlots(BAG_BACKPACK)
ElderScrollsOfAlts.altData.players[playerKey].misc.backpackSize = bagSize
ElderScrollsOfAlts.altData.players[playerKey].misc.backpackUsed = bagUsed
ElderScrollsOfAlts.altData.players[playerKey].misc.backpackFree = tonumber( bagSize-bagUsed )
--
ElderScrollsOfAlts.altData.players[playerKey].misc.skillpoints = GetAvailableSkillPoints()
ElderScrollsOfAlts.altData.players[playerKey].misc.skillpointsfree = GetAvailableSkillPoints()
--ElderScrollsOfAlts.altData.players[playerKey].misc.skillpointstotal = GetAvailableSkillPoints()
ElderScrollsOfAlts.altData.players[playerKey].misc.secondsPlayed = GetSecondsPlayed()
--GetUnitZone("player")
local earnedAchievePts = GetEarnedAchievementPoints()
ElderScrollsOfAlts.altData.players[playerKey].misc.achieve = {}
ElderScrollsOfAlts.altData.players[playerKey].misc.achieve.earned = earnedAchievePts
----Section: Currency section
if(ElderScrollsOfAlts.altData.players[playerKey].currency==nil) then
ElderScrollsOfAlts.altData.players[playerKey].currency = {}
end
local currType = {CURT_ALLIANCE_POINTS, CURT_CHAOTIC_CREATIA,CURT_CROWNS,CURT_CROWN_GEMS,CURT_MONEY,CURT_NONE,CURT_STYLE_STONES,CURT_TELVAR_STONES,CURT_WRIT_VOUCHERS}
local cLoc = CURRENCY_LOCATION_CHARACTER
for ctIdx = 1, #currType do
local cType = currType[ctIdx]
local amount = GetCurrencyAmount( cType, cLoc )
local IS_PLURAL = false
if(amount and amount>1) then IS_PLURAL = true end
local currencyName = GetCurrencyName(cType, IS_PLURAL, false)
ElderScrollsOfAlts.altData.players[playerKey].currency[cType] = {}
ElderScrollsOfAlts.altData.players[playerKey].currency[cType].currencyName = currencyName
ElderScrollsOfAlts.altData.players[playerKey].currency[cType].amount = amount
end
----Section: PVP section
--PVP Ava Campaign Cyrodil PVP (TODO) --
ElderScrollsOfAlts.altData.players[playerKey].alliancewar = {}
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.inCampaign = IsInCampaign()
local currentCampaignId = GetCurrentCampaignId()--this not the best one?
local guestCampaignId = GetGuestCampaignId()
local assignedCampaignId = GetAssignedCampaignId()
local isInCampaign = currentCampaignId ~= 0
if(not isInCampaign) then
isInCampaign = assignedCampaignId ~= 0
end
--GetPreferredCampaign() ??
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.guestCampaignId = guestCampaignId
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.currentCampaignId = currentCampaignId
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.assignedCampaignId = assignedCampaignId
--ElderScrollsOfAlts.debugMsg("currentCampaignId="..tostring(currentCampaignId) )
--ElderScrollsOfAlts.debugMsg("guestCampaignId="..tostring(guestCampaignId) )
--d("(" .. ElderScrollsOfAlts.name .. ") " .. "guestCampaignId: "..guestCampaignId )
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.guestCampaignName = GetCampaignName(guestCampaignId)
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.currentCampaignName = GetCampaignName(currentCampaignId)
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.assignedCampaignName = GetCampaignName(assignedCampaignId)
--ElderScrollsOfAlts.outputMsg("save.currentCampaignId="..tostring(currentCampaignId) )
--ElderScrollsOfAlts.outputMsg("save.currentCampaignName="..tostring( GetCampaignName(currentCampaignId) ) )
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.isInCampaign = isInCampaign
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.unitAlliance = pAlliance
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.allianceName = GetAllianceName(pAlliance)
local avaRank = GetUnitAvARank("player")
local unitAvARankPoints = GetUnitAvARankPoints("player")
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.unitAvARank = avaRank
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.unitAvARankPoints = unitAvARankPoints
-- number subRankStartsAt, number nextSubRankAt, number rankStartsAt, number nextRankAt
local subRankStartsAt, nextSubRankAt, rankStartsAt, nextRankAt = GetAvARankProgress(unitAvARankPoints)
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.AvaSubRankStart = subRankStartsAt
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.AvaNextSubRank = nextSubRankAt
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.AvaRankStarts = rankStartsAt
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.AvaNextRank = nextRankAt
local avaRankName = GetAvARankName( GetUnitGender("player"), avaRank )
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.avaRankName = avaRankName
--Returns: number earnedTier, number nextTierProgress, number nextTierTotal
local earnedTier, nextTierProgress, nextTierTotal = GetPlayerCampaignRewardTierInfo(assignedCampaignId)
ElderScrollsOfAlts.debugMsg(
"earnedTier: '",earnedTier,
"' nextTierProgress: '",nextTierProgress,
"' nextTierTotal: '",nextTierTotal,"'" )
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.AssignedCampaignRewardEarnedTier = tonumber(earnedTier)
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.AssignedCampaignRewardNextProgressTier = tonumber(nextTierProgress)
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.AssignedCampaignRewardNextTotalTier = tonumber(nextTierTotal)
--ElderScrollsOfAlts.altData.players[playerKey].alliancewar.currentCampaignRewardEarnedTier = earnedTier
earnedTier, nextTierProgress, nextTierTotal = GetPlayerCampaignRewardTierInfo(guestCampaignId)
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.guestCampaignRewardEarnedTier = tonumber(earnedTier)
local avaAEnd = GetSecondsUntilCampaignEnd(assignedCampaignId)
ElderScrollsOfAlts.debugMsg("avaAEnd: '", avaAEnd, "'")
if(avaAEnd~=nil and avaAEnd<0) then
ElderScrollsOfAlts.debugMsg("avaAEnded???: '", avaAEnd, "'")
elseif(avaAEnd~=nil and avaAEnd~=0) then
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.AssignedCampaignEndsSeconds = GetSecondsUntilCampaignEnd(assignedCampaignId)
local AC_expiresAt = GetTimeStamp() + ( ElderScrollsOfAlts.altData.players[playerKey].alliancewar.AssignedCampaignEndsSeconds )
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.AssignedCampaignEndsAt = AC_expiresAt
if(ElderScrollsOfAlts.altData.ava==nil) then
ElderScrollsOfAlts.altData.ava = {}
ElderScrollsOfAlts.altData.ava.campaigns = {}
end
ElderScrollsOfAlts.altData.ava.campaigns[assignedCampaignId] = {}
ElderScrollsOfAlts.altData.ava.campaigns[assignedCampaignId].campaignEndsAt = AC_expiresAt
ElderScrollsOfAlts.altData.ava.campaigns[assignedCampaignId].campaignId = assignedCampaignId
ElderScrollsOfAlts.debugMsg("avaAEnd saved to cache '", AC_expiresAt, "'")
else
if(ElderScrollsOfAlts.altData.ava~=nil and ElderScrollsOfAlts.altData.ava.campaigns ~= nil and ElderScrollsOfAlts.altData.ava.campaigns[assignedCampaignId]~=nil and ElderScrollsOfAlts.altData.ava.campaigns[assignedCampaignId].campaignEndsAt~=nil) then
ElderScrollsOfAlts.altData.players[playerKey].alliancewar.AssignedCampaignEndsAt = ElderScrollsOfAlts.altData.ava.campaigns[assignedCampaignId].campaignEndsAt
ElderScrollsOfAlts.debugMsg("avaAEnd loaded from cache '", ElderScrollsOfAlts.altData.players[playerKey].alliancewar.AssignedCampaignEndsAt, "'")
end
end
--GetLargeAvARankIcon(rank))
--GetAllianceColor(alliance):UnpackRGBA())
if not (isInCampaign or assignedCampaignId) then
--no campaign
else
--TODO
--local campaignName = GetCampaignName(campaignId)
end
----Section: Infamy/Bounty section
--infamy = GetInfamy()
--heat, bounty GetPlayerInfamyData()
--infamyThresholdType = getInfamyLevel( infamy )
-- INFMAY_THRESHHOLD_DISREPUTABLE, FUGITIVE, NOTOFIOUS, UPSTANDING
ElderScrollsOfAlts.altData.players[playerKey].infamy = {}
local infamy = GetInfamy()
local bounty = GetBounty()
ElderScrollsOfAlts.debugMsg("infamy="..tostring(infamy) )
local fullBountyPayoffAmount = GetFullBountyPayoffAmount()
local reducedBountyPayoffAmount = GetReducedBountyPayoffAmount()
local infamyLevel = GetInfamyLevel(infamy)
local infamyLevelText = ElderScrollsOfAlts.getInfamyLevelText(infamyLevel)
ElderScrollsOfAlts.altData.players[playerKey].infamy.displayText = infamyLevelText
ElderScrollsOfAlts.altData.players[playerKey].infamy.infamy = infamy
ElderScrollsOfAlts.altData.players[playerKey].infamy.bounty = bounty
ElderScrollsOfAlts.altData.players[playerKey].infamy.fullBounty = fullBountyPayoffAmount
ElderScrollsOfAlts.altData.players[playerKey].infamy.reducedBounty = reducedBountyPayoffAmount
local sBountyDecayZero = GetSecondsUntilBountyDecaysToZero()
local sHeatDecayZero = GetSecondsUntilHeatDecaysToZero()
local now = GetTimeStamp()
--local timeTillReady = GetTimeStamp() + sBountyDecayZero
ElderScrollsOfAlts.altData.players[playerKey].infamy.bountytozero = now + sBountyDecayZero
ElderScrollsOfAlts.altData.players[playerKey].infamy.heattozero = now + sHeatDecayZero
--local thresholdType = getInfamyLevel( infamy )
--local heat, bounty = GetPlayerInfamyData()
--ElderScrollsOfAlts.altData.players[playerKey].infamy.payoffAmount = payoffAmount
--ElderScrollsOfAlts.altData.players[playerKey].infamy.heat = heat
--ElderScrollsOfAlts.altData.players[playerKey].infamy.bounty = bounty
--ElderScrollsOfAlts.altData.players[playerKey].infamy.thresholdType = thresholdType
----Section: Location section
ElderScrollsOfAlts.altData.players[playerKey].location = {}
local subzoneNamePL = zo_strformat("<<1>>", GetPlayerActiveSubzoneName() )
local zoneNamePL = zo_strformat("<<1>>", GetPlayerActiveZoneName() )
local zoneIndex = GetUnitZoneIndex("player")
local zoneId, worldX, worldY, worldZ = GetUnitWorldPosition("player")
--local zDescription = GetZoneDescription(zoneIndex)
--local zoneId = GetZoneId(zoneIndex)
ElderScrollsOfAlts.altData.players[playerKey].location.subzoneName = subzoneNamePL
ElderScrollsOfAlts.altData.players[playerKey].location.zoneName = zoneNamePL
ElderScrollsOfAlts.altData.players[playerKey].location.zoneId = zoneId
--[[
--local currLoc = {CURRENCY_LOCATION_ACCOUNT,CURRENCY_LOCATION_BANK,CURRENCY_LOCATION_CHARACTER,CURRENCY_LOCATION_GUILD_BANK}
for clIdx = 1, #currLoc do
local cL = currLoc[clIdx]
ElderScrollsOfAlts.altData.players[playerKey].currency[cL] = {}
for ctIdx = 1, #currType do
local cT = currType[ctIdx]
local amount = GetCurrencyAmount( cT, cL )
ElderScrollsOfAlts.altData.players[playerKey].currency[cL][cL] = amount
end
end
--]]
----Section: Equipment section
ElderScrollsOfAlts:SavaDataPlayerEquipment(playerKey)
--Research
ElderScrollsOfAlts.altData.players[playerKey].research = {}
ElderScrollsOfAlts.altData.players[playerKey].research.now = GetTimeStamp()
ElderScrollsOfAlts:SaveDataPlayerResearchData(CRAFTING_TYPE_BLACKSMITHING, "blacksmithing",
ElderScrollsOfAlts.altData.players[playerKey].research)
ElderScrollsOfAlts:SaveDataPlayerResearchData(CRAFTING_TYPE_CLOTHIER, "clothier",
ElderScrollsOfAlts.altData.players[playerKey].research)
ElderScrollsOfAlts:SaveDataPlayerResearchData(CRAFTING_TYPE_WOODWORKING, "woodworking",
ElderScrollsOfAlts.altData.players[playerKey].research)
ElderScrollsOfAlts:SaveDataPlayerResearchData(CRAFTING_TYPE_JEWELRYCRAFTING, "jewelcrafting",
ElderScrollsOfAlts.altData.players[playerKey].research)
----Section: Bags/Bank section
ElderScrollsOfAlts.altData.data = {}
ElderScrollsOfAlts.altData.data.server = {}
ElderScrollsOfAlts.altData.data.server[pServer] = {}
local bagSizeB = GetBagSize(BAG_BACKPACK)
local bagUsedB = GetNumBagUsedSlots(BAG_BACKPACK)
ElderScrollsOfAlts.altData.data.server[pServer].bankSize = bagSizeB
ElderScrollsOfAlts.altData.data.server[pServer].bankUsed = bagUsedB
ElderScrollsOfAlts.altData.data.server[pServer].bankFree = tonumber( bagSizeB-bagUsedB )
----Section: Protect section
--Protect data not loaded from player data API
--"category", "championpointsactive", "championpoints", "tracking", "note"
for key,value in pairs(dataToProtect) do
if( ElderScrollsOfAlts.view.tempsave[value] ~= nil ) then
ElderScrollsOfAlts.altData.players[playerKey][value] = ElderScrollsOfAlts.view.tempsave[value]
ElderScrollsOfAlts.debugMsg("ESOA, restored current '"..value.."', as '", tostring(ElderScrollsOfAlts.altData.players[playerKey][value]) ,"'")
end
end
if( ElderScrollsOfAlts.view.currentorder ~= nil) then
ElderScrollsOfAlts.altData.players[playerKey].playersorder = ElderScrollsOfAlts.view.currentorder
ElderScrollsOfAlts.debugMsg("ESOA, restored current order, as '", tostring(ElderScrollsOfAlts.altData.players[playerKey].playersorder) ,"'")
end
--[[
if( ElderScrollsOfAlts.view.currentnote ~= nil) then
ElderScrollsOfAlts.altData.players[playerKey].note = ElderScrollsOfAlts.view.currentnote
ElderScrollsOfAlts.debugMsg("ESOA, restored current note, as '", tostring(ElderScrollsOfAlts.altData.players[playerKey].note) ,"'")
end
if( ElderScrollsOfAlts.view.currentcategory ~= nil) then
ElderScrollsOfAlts.altData.players[playerKey].category = ElderScrollsOfAlts.view.currentcategory
ElderScrollsOfAlts.debugMsg("ESOA, restored current category, as '", tostring(ElderScrollsOfAlts.altData.players[playerKey].category) ,"'")
end
if( ElderScrollsOfAlts.view.championpointsactive ~= nil) then
ElderScrollsOfAlts.altData.players[playerKey].championpointsactive = ElderScrollsOfAlts.view.championpointsactive
ElderScrollsOfAlts.debugMsg("ESOA, restored current cp active, as '", tostring(ElderScrollsOfAlts.altData.players[playerKey].championpointsactive) ,"'")
end
if( ElderScrollsOfAlts.view.championpoints ~= nil) then
ElderScrollsOfAlts.altData.players[playerKey].championpoints = ElderScrollsOfAlts.view.championpoints
ElderScrollsOfAlts.debugMsg("ESOA, restored current cp, as '", tostring(ElderScrollsOfAlts.altData.players[playerKey].championpoints) ,"'")
end
if( ElderScrollsOfAlts.view.tracking ~= nil) then
ElderScrollsOfAlts.altData.players[playerKey].tracking = ElderScrollsOfAlts.view.tracking
ElderScrollsOfAlts.debugMsg("ESOA, restored current tracking, as '", tostring(ElderScrollsOfAlts.altData.players[playerKey].tracking) ,"'")
end
--]]
----Section: Buffs section
--BUFFS
ElderScrollsOfAlts.altData.players[playerKey].buffs = {}
local numBuffs = GetNumBuffs("player")
for buffIndex = 1, numBuffs do
--string buffName, number timeStarted, number timeEnding, number buffSlot, number stackCount, textureName iconFilename, string buffType, number BuffEffectType effectType, number AbilityType abilityType, number StatusEffectType statusEffectType, number abilityId, boolean canClickOff, boolean castByPlayer
local buffName, timeStarted, timeEnding, buffSlot, stackCount, iconFilename, buffType, effectType, abilityType, statusEffectType, abilityId, canClickOff, castByPlayer = GetUnitBuffInfo("player", buffIndex)
ElderScrollsOfAlts.altData.players[playerKey].buffs[buffName] = {}
ElderScrollsOfAlts.altData.players[playerKey].buffs[buffName].timeStarted = timeStarted
ElderScrollsOfAlts.altData.players[playerKey].buffs[buffName].timeEnding = timeEnding
ElderScrollsOfAlts.altData.players[playerKey].buffs[buffName].abilityId = abilityId
ElderScrollsOfAlts.altData.players[playerKey].buffs[buffName].iconFilename = iconFilename
local duration = timeEnding - timeStarted
ElderScrollsOfAlts.altData.players[playerKey].buffs[buffName].duration = duration
if(duration > 0) then
local timeLeftS = (timeEnding) - GetFrameTimeSeconds() -- time end - time in frame is time left
--data:SetCooldown(timeLeft, duration * 1000.0)
ElderScrollsOfAlts.altData.players[playerKey].buffs[buffName].expiresAt = GetTimeStamp() + (timeLeftS)
else
ElderScrollsOfAlts.altData.players[playerKey].buffs[buffName].expiresAt = 0
end
--[[TODO TESTING
if(ElderScrollsOfAlts.altData.players[playerKey].buffs[buffName].expiresAt~=0) then
--Time in seconds left till expires
local timeDiff = GetDiffBetweenTimeStamps( ElderScrollsOfAlts.altData.players[playerKey].buffs[buffName].expiresAt, GetTimeStamp() )
ElderScrollsOfAlts.debugMsg("Buff Data: name: '".. buffName .. "' expires="..tostring(ElderScrollsOfAlts.altData.players[playerKey].buffs[buffName].expiresAt) .. " timeDiff=".. tostring(timeDiff) )
end--]]
--ElderScrollsOfAlts.altData.players[playerKey].buffs[buffName].expiresAt = GetTimeStamp() + ( timeEnding-timeStarted )
--[[
if(buffName=="Major Protection")then
d("Has Major Protection!****")
elseif(buffName=="Minor Protection")then
d("Has Minor Protection!****")
else
d("Has buff "..tostring(buffName))
end
--]]
end--for buffs
--STATS
--ElderScrollsOfAlts:SaveDataPlayerStatsData(ElderScrollsOfAlts.altData.players[playerKey])
----Section: Special section
if( ElderScrollsOfAlts.altData.players[playerKey].bio.Vampire == true) then
ElderScrollsOfAlts.altData.players[playerKey].bio.specialdata = {}
ElderScrollsOfAlts:SaveDataVampire( playerKey, ElderScrollsOfAlts.altData.players[playerKey].bio.specialdata )
end
if( ElderScrollsOfAlts.altData.players[playerKey].bio.Werewolf == true) then
ElderScrollsOfAlts.altData.players[playerKey].bio.specialdata = {}
ElderScrollsOfAlts:SaveDataWerewolf( playerKey, ElderScrollsOfAlts.altData.players[playerKey].bio.specialdata )
end
--local timeTotalEnd = GetFrameTimeSeconds()
--local timeTotalDiff = GetDiffBetweenTimeStamps(timeTotalStart, timeTotalEnd)
--ElderScrollsOfAlts.debugMsg("timeTotalStart: " .. tostring(timeTotalStart) .. " timeTotalEnd:" .. tostring(timeTotalEnd) )
--ElderScrollsOfAlts.debugMsg("ESOA.SAVE timeTotalDiff=".. tostring(timeTotalDiff) )
-- Fetch the saved variables
--Test TRAITS
if(ElderScrollsOfAlts.altData.players[playerKey].researchtraits == nil) then
ElderScrollsOfAlts.altData.players[playerKey].researchtraits = {}
ElderScrollsOfAlts.altData.players[playerKey].researchtraits.unknown = {}
ElderScrollsOfAlts.altData.players[playerKey].researchtraits.blacksmithing = {}
ElderScrollsOfAlts.altData.players[playerKey].researchtraits.clother = {}
ElderScrollsOfAlts.altData.players[playerKey].researchtraits.woodworking = {}
ElderScrollsOfAlts.altData.players[playerKey].researchtraits.jewelrycrafting = {}
end
local baseRTElem = ElderScrollsOfAlts.altData.players[playerKey].researchtraits
for patternIndex = 1, GetNumSmithingPatterns() do
local patternName, baseName, _, numMaterials, numTraitsRequired, numTraitsKnown, resultingItemFilterType = GetSmithingPatternInfo(patternIndex)
local craftingType = GetCraftingInteractionType()-- ONLY valid when crafting table OPEN!
ElderScrollsOfAlts.debugMsg("DataSaveLivePlayer: Trait: patternName: ", patternName , " numMaterials: " , numMaterials, " numTraitsKnown: ", numTraitsKnown, " TYPE=", craftingType )
ElderScrollsOfAlts.debugMsg("DataSaveLivePlayer: TYPElIST: BLACKSMITHING: ", CRAFTING_TYPE_BLACKSMITHING , " CLOTHIER: " , CRAFTING_TYPE_CLOTHIER, " WOODWORKING: ", CRAFTING_TYPE_WOODWORKING)
local baseTTElem = baseRTElem.unknown
if craftingType == CRAFTING_TYPE_BLACKSMITHING then
baseTTElem = baseRTElem.blacksmithing
elseif craftingType == CRAFTING_TYPE_CLOTHIER then
baseTTElem = baseRTElem.clother
elseif craftingType == CRAFTING_TYPE_WOODWORKING then
baseTTElem = baseRTElem.woodworking
elseif craftingType == CRAFTING_TYPE_JEWELRYCRAFTING then
baseTTElem = baseRTElem.jewelrycrafting
end
if(baseTTElem[patternName]==nil) then
baseTTElem[patternName] = {}
end
baseTTElem[patternName].numTraitsKnown = numTraitsKnown
end
--Test TRAITS
--COMPANIONS
-- Cant get list of companions? have to use only active one?
--[[ TODO: So this or events?
if( HasActiveCompanion() ) then
local companionId = GetActiveCompanionDefId()
local level, currentExperience = GetActiveCompanionLevelInfo()
local currentRapport = GetActiveCompanionRapport()
local cname = GetCompanionName(companionId)
ElderScrollsOfAlts:CollectCompanionDataLevel(companionId, cname, level, currentExperience)
ElderScrollsOfAlts:CollectCompanionDataRapport(companionId, cname, currentRapport)
end
--]]
--[[
* HasPendingCompanion()
** _Returns:_ *bool* _hasPendingCompanion_
* GetActiveCompanionRapportLevel()
** _Returns:_ *[CompanionRapportLevel|#CompanionRapportLevel]* _rapportLevel_
* GetPendingCompanionDefId()
** _Returns:_ *integer* _pendingCompanionId_
--activecompanionname
--activecompanionlevel
--activecompanionrapport
--activecompanionskills?
--]]
--COMPANION END
ElderScrollsOfAlts.debugMsg("DataSaveLivePlayer: done")
end
function ElderScrollsOfAlts:SaveDataSpecialBite(playerKey, baseElem,skillineName,specialSkillName,abilityname,buffcooldown)
ElderScrollsOfAlts.debugMsg("SaveDataSpecialBite: playerKey= " .. tostring(playerKey) )
--Has to have this ability to be able to BITE!
local foundItem = ElderScrollsOfAlts:FindAbility( ElderScrollsOfAlts.altData.players[playerKey], skillineName, specialSkillName, abilityname)
ElderScrollsOfAlts.debugMsg("SaveDataSpecialBite: foundItem= " .. tostring(foundItem) )
if(foundItem==nil) then
return
end
baseElem.biteability = abilityname
local buffName = buffcooldown
local fedBuff = ElderScrollsOfAlts.altData.players[playerKey].buffs[buffName]
ElderScrollsOfAlts.debugMsg("SaveDataSpecialBite: fedBuff= " .. tostring(fedBuff) )
baseElem.buffName = buffName
baseElem.fedBuff = fedBuff
baseElem.expiresAt = nil
if(fedBuff==nil) then
return
end
local expiresAt = fedBuff.expiresAt
ElderScrollsOfAlts.debugMsg("SaveDataSpecialBite: expiresAt= " .. tostring(expiresAt) )
baseElem.expiresAt = expiresAt
--Time in seconds left till expires
--local timeDiff = GetDiffBetweenTimeStamps( expiresAt, GetTimeStamp() )
--ElderScrollsOfAlts.debugMsg("Buff timeDiff=".. tostring(timeDiff) )
--local timeTillReady = GetTimeStamp() + timeRemainingSecs
--UUU
end
--
function ElderScrollsOfAlts:InitTrackingData(trackingType,trackingName)
----Section: Statup section
local pID = GetCurrentCharacterId()
local pServer = GetWorldName()
local playerKey = zo_strformat("<<1>>_<<2>>", pID, pServer:gsub(" ","_") )
----Section: Save section
if ElderScrollsOfAlts.altData.players == nil then
ElderScrollsOfAlts.altData.players = {}
end
if( ElderScrollsOfAlts.altData.players[playerKey] == nil ) then
ElderScrollsOfAlts.altData.players[playerKey] = {}
end
if( ElderScrollsOfAlts.altData.players[playerKey].tracking == nil ) then
ElderScrollsOfAlts.altData.players[playerKey].tracking = {}
end
if( ElderScrollsOfAlts.altData.players[playerKey].tracking[trackingType] == nil ) then
ElderScrollsOfAlts.altData.players[playerKey].tracking[trackingType] = {}
end
if( ElderScrollsOfAlts.altData.players[playerKey].tracking[trackingType][trackingName] == nil ) then
ElderScrollsOfAlts.altData.players[playerKey].tracking[trackingType][trackingName] = {}
end
return ElderScrollsOfAlts.altData.players[playerKey].tracking[trackingType][trackingName]
end
--
function ElderScrollsOfAlts:SaveTrackingDataComplete(trackingType,trackingName,isCompleted)
ElderScrollsOfAlts.debugMsg("SaveTrackingDataComplete: called")
ElderScrollsOfAlts.debugMsg("trackingType: "..tostring(trackingType) .. " trackingName: " ..tostring(trackingName) )
local trackElem = ElderScrollsOfAlts:InitTrackingData(trackingType,trackingName)
trackElem.name = trackingName
trackElem.cat = trackingType
trackElem.completed = isCompleted
trackElem.completedtime = GetTimeStamp()
local hour, minute = ElderScrollsOfAlts:dailyReset()
local timeToReset = hour*3600 + minute*60
trackElem.resettime = trackElem.completedtime + timeToReset
--trackElem.resettime = GetTimeStamp() -- today at 2am?
end
--
function ElderScrollsOfAlts:CollectCP()
ElderScrollsOfAlts.debugMsg("CollectCP: called")
----Section: Statup section
local pID = GetCurrentCharacterId()
local pServer = GetWorldName()
local playerKey = pID.."_".. pServer:gsub(" ","_")
--local timeTotalStart = GetFrameTimeSeconds()
--ElderScrollsOfAlts.debugMsg("timeTotalStart: " .. tostring(timeTotalStart) )
--debugMsg("pName='"..tostring(pName).."'" )
if ElderScrollsOfAlts.altData.players == nil then
ElderScrollsOfAlts.altData.players = {}
end
if( ElderScrollsOfAlts.altData.players[playerKey] == nil ) then
ElderScrollsOfAlts.altData.players[playerKey] = {}
end
----Section: Collect section
--if( ElderScrollsOfAlts.altData.players[playerKey] ~= nil ) then
--end
----Section: Save section
if( ElderScrollsOfAlts.altData.players[playerKey] ~= nil ) then
ElderScrollsOfAlts.altData.players[playerKey].championpointsactive = {}
--d("[start] TestCP...")
local CP = CHAMPION_PERKS
local championBar = CHAMPION_PERKS:GetChampionBar()
local CPData = CHAMPION_DATA_MANAGER
for i=1, 12 do
local championSkillData = CHAMPION_PERKS:GetChampionBar():GetSlot(i).championSkillData
if championSkillData then -- If anything is slotted into that index
--d("Slot number "..i.." id: ".. championSkillData:GetId() .. " data: " .. tostring(championSkillData) )
ElderScrollsOfAlts.altData.players[playerKey].championpointsactive[i] = {}
local cpskid = championSkillData:GetId()
ElderScrollsOfAlts.altData.players[playerKey].championpointsactive[i].id = cpskid
ElderScrollsOfAlts.altData.players[playerKey].championpointsactive[i].name = GetChampionSkillName(cpskid)
ElderScrollsOfAlts.altData.players[playerKey].championpointsactive[i].disciplineid = championSkillData:GetChampionDisciplineData():GetId()
ElderScrollsOfAlts.altData.players[playerKey].championpointsactive[i].disciplinetype = championSkillData:GetChampionDisciplineData():GetType()
ElderScrollsOfAlts.altData.players[playerKey].championpointsactive[i].numspentpoints = GetNumPointsSpentOnChampionSkill(cpskid)
--GetNumPendingChampionPoints(*luaindex* _disciplineIndex_, *luaindex* _skillIndex_)
--** _Returns:_ *integer* _numPendingPoints_
--GetChampionSkillCurrentBonusText(cpskid)
--:GetRawName
--GetChampionSkillType
else
end
end -- for
--xxx
ElderScrollsOfAlts.altData.players[playerKey].championpoints = {}
local numDisciplines = GetNumChampionDisciplines()
--d("numDisciplines: " .. tostring(numDisciplines) )
for disciplineIndex = 1, numDisciplines do
ElderScrollsOfAlts.altData.players[playerKey].championpoints[disciplineIndex] = {}
ElderScrollsOfAlts.altData.players[playerKey].championpoints[disciplineIndex].name = GetChampionDisciplineName(disciplineIndex)
--ElderScrollsOfAlts.altData.players[playerKey].championpoints[disciplineIndex].id = disciplineIndex
for championSkillIndex = 1, GetNumChampionDisciplineSkills(disciplineIndex) do
local championSkillId = GetChampionSkillId(disciplineIndex, championSkillIndex)
--local numPendingPoints = GetNumPendingChampionPoints(disciplineIndex, championSkillIndex)
local ptsspent = GetNumPointsSpentOnChampionSkill(championSkillId)
if(ptsspent>0) then
local championSkillType = GetChampionSkillType(championSkillId)
local isSlottable = ElderScrollsOfAlts:CheckIfCpTypeIsSlottable( championSkillType )
if(isSlottable) then
local name = GetChampionSkillName(championSkillId)
local abilityId = GetChampionAbilityId(championSkillId)
ElderScrollsOfAlts.altData.players[playerKey].championpoints[disciplineIndex][championSkillId] = {}
--ElderScrollsOfAlts.altData.players[playerKey].championpoints[disciplineIndex][championSkillId].pts = numPendingPoints
ElderScrollsOfAlts.altData.players[playerKey].championpoints[disciplineIndex][championSkillId].name = name
ElderScrollsOfAlts.altData.players[playerKey].championpoints[disciplineIndex][championSkillId].ptsspent = ptsspent
ElderScrollsOfAlts.altData.players[playerKey].championpoints[disciplineIndex][championSkillId].abilityId = abilityId
--d("championSkillId: " .. tostring(championSkillId) )
--local championSkillData = ZO_ChampionSkillData:New(self, skillIndex)
--d("championSkillData: " .. tostring(championSkillData) )
--if championSkillData:IsClusterRoot() then
-- table.insert(self.championClusterDatas, ZO_ChampionClusterData:New(championSkillData))
--end
--self.championSkillDatas[skillIndex] = championSkillData
end
end--spent points
end
end
--d("TestCP...[end]")
end -- if player line exists
ElderScrollsOfAlts.debugMsg("CollectCP: done")
end
--CollectCP()
function ElderScrollsOfAlts:CheckIfCpTypeIsSlottable(championSkillType)
if(ElderScrollsOfAlts.view.CpTypeIsSlottable==nil) then
ElderScrollsOfAlts.view.CpTypeIsSlottable = {}
end
if(ElderScrollsOfAlts.view.CpTypeIsSlottable[championSkillType]==nil) then
ElderScrollsOfAlts.view.CpTypeIsSlottable[championSkillType] = CanChampionSkillTypeBeSlotted(championSkillType)
end
return ElderScrollsOfAlts.view.CpTypeIsSlottable[championSkillType]
end
--Companions
function ElderScrollsOfAlts:CollectCompanionDataInit(playerKey, companionId, cname)
if ElderScrollsOfAlts.altData.players == nil then
ElderScrollsOfAlts.altData.players = {}
end
if( ElderScrollsOfAlts.altData.players[playerKey] == nil ) then
ElderScrollsOfAlts.altData.players[playerKey] = {}
end
----Section: Save section
if( ElderScrollsOfAlts.altData.players[playerKey].companions == nil ) then
ElderScrollsOfAlts.altData.players[playerKey].companions = {}
ElderScrollsOfAlts.altData.players[playerKey].companions.ids = {}
ElderScrollsOfAlts.altData.players[playerKey].companions.data = {}
end
if( ElderScrollsOfAlts.altData.players[playerKey].companions.ids[companionId] == nil ) then
ElderScrollsOfAlts.altData.players[playerKey].companions.ids[companionId] = companionId
end
if( ElderScrollsOfAlts.altData.players[playerKey].companions.data[companionId] == nil ) then
ElderScrollsOfAlts.altData.players[playerKey].companions.data[companionId] = {}
end
ElderScrollsOfAlts.altData.players[playerKey].companions.data[companionId].id = companionId
ElderScrollsOfAlts.altData.players[playerKey].companions.data[companionId].name = zo_strformat("<<X:1>>", cname )
end
--Companions
function ElderScrollsOfAlts:CollectCompanionDataLevel(companionId, cname, level, currentExperience, experienceForLevel)
ElderScrollsOfAlts.debugMsg("CollectCompanionDataLevel: called")
----Section: Statup section
local pID = GetCurrentCharacterId()
local pServer = GetWorldName()
local playerKey = pID.."_".. pServer:gsub(" ","_")
--
ElderScrollsOfAlts:CollectCompanionDataInit(playerKey, companionId, cname)
ElderScrollsOfAlts.altData.players[playerKey].companions.data[companionId].level = level
ElderScrollsOfAlts.altData.players[playerKey].companions.data[companionId].currentExperience = currentExperience
ElderScrollsOfAlts.altData.players[playerKey].companions.data[companionId].experienceForLevel = experienceForLevel
end
--Companions
function ElderScrollsOfAlts:CollectCompanionDataSkillRank(companionId, cname, skillLineId, slName, rank )
ElderScrollsOfAlts.debugMsg("CollectCompanionDataSkillRank: called")
----Section: Statup section
local pID = GetCurrentCharacterId()
local pServer = GetWorldName()
local playerKey = pID.."_".. pServer:gsub(" ","_")
--
ElderScrollsOfAlts:CollectCompanionDataInit(playerKey, companionId, cname)
ElderScrollsOfAlts:CollectCompanionDataSkillLine(companionId, cname, skillLineId, slName )
ElderScrollsOfAlts.altData.players[playerKey].companions.data[companionId].skillline[skillLineId].rank = rank
end
--Companions
function ElderScrollsOfAlts:CollectCompanionDataSkillLine(companionId, cname, skillLineId, slName )
ElderScrollsOfAlts.debugMsg("CollectCompanionDataSkillLine: called")
----Section: Statup section
local pID = GetCurrentCharacterId()
local pServer = GetWorldName()
local playerKey = pID.."_".. pServer:gsub(" ","_")
--
ElderScrollsOfAlts:CollectCompanionDataInit(playerKey, companionId, cname)
if( ElderScrollsOfAlts.altData.players[playerKey].companions.data[companionId].skillline == nil) then
ElderScrollsOfAlts.altData.players[playerKey].companions.data[companionId].skillline = {}
end
if( ElderScrollsOfAlts.altData.players[playerKey].companions.data[companionId].skillline[skillLineId] == nil ) then
ElderScrollsOfAlts.altData.players[playerKey].companions.data[companionId].skillline[skillLineId] = {}
end
ElderScrollsOfAlts.altData.players[playerKey].companions.data[companionId].skillline[skillLineId].id = skillLineId
ElderScrollsOfAlts.altData.players[playerKey].companions.data[companionId].skillline[skillLineId].name = slName
end
--Companions
function ElderScrollsOfAlts:CollectCompanionDataRapport(companionId, cname, currentRapport)
ElderScrollsOfAlts.debugMsg("CollectCompanionDataRapport: called")
----Section: Statup section
local pID = GetCurrentCharacterId()
local pServer = GetWorldName()
local playerKey = pID.."_".. pServer:gsub(" ","_")
--
ElderScrollsOfAlts:CollectCompanionDataInit(playerKey, companionId, cname)
ElderScrollsOfAlts.altData.players[playerKey].companions.data[companionId].id = companionId
ElderScrollsOfAlts.altData.players[playerKey].companions.data[companionId].name = cname
ElderScrollsOfAlts.altData.players[playerKey].companions.data[companionId].rapport = currentRapport
end
--ElderScrollsOfAlts.altData.players[playerKey].bio.specialdata
function ElderScrollsOfAlts:SaveDataWerewolf(playerKey, baseElem)
ElderScrollsOfAlts.debugMsg("SaveDataWerewolf: playerKey= " .. tostring(playerKey) )
baseElem.werewolf = true
--
ElderScrollsOfAlts:SaveDataSpecialBite(playerKey, baseElem, "world","Werewolf",ElderScrollsOfAlts.BITE_WERE_ABILITY,ElderScrollsOfAlts.BITE_WERE_COOLDOWN)
--
end
--ElderScrollsOfAlts.altData.players[playerKey].bio.specialdata
function ElderScrollsOfAlts:SaveDataVampire(playerKey, baseElem)
ElderScrollsOfAlts.debugMsg("SaveDataVampire: playerKey= " .. tostring(playerKey) )
baseElem.vampire = true
--
ElderScrollsOfAlts:SaveDataSpecialBite(playerKey, baseElem, "world","Vampire",ElderScrollsOfAlts.BITE_VAMP_ABILITY,ElderScrollsOfAlts.BITE_VAMP_COOLDOWN)
--
end
--loadPlayerDataPart
function ElderScrollsOfAlts:SaveDataSkillData(skillType,baseElem,outputUndiscovered)
if skillType == nil then
ElderScrollsOfAlts.debugMsg("SaveDataSkillData: skillType is NIL")
return
end
--ElderScrollsOfAlts.debugMsg("loadPlayerDataPart: skillType="..skillType..".")
local numSkillLines = GetNumSkillLines(skillType)
for ii = 1, numSkillLines do
local name, rank, discovered, skillLineId, advised, unlockText = GetSkillLineInfo(skillType,ii)
--name, number rank, boolean discovered, number skillLineId, boolean advised, unlockText
if name == nil then
name = ii;
end
name = zo_strformat( "<<1>>", name ) -- get rid of links and junk?
if discovered or outputUndiscovered then
--ElderScrollsOfAlts.debugMsg("loadPlayerDataPart: unlockText="..unlockText..".")
baseElem[name] = {}
local baseElemTable = baseElem[name]
local numAbilities = GetNumSkillAbilities(skillType, ii)
baseElemTable.name = name
baseElemTable.idx = ii
baseElemTable.rank = rank
baseElemTable.numAbilities = numAbilities
baseElemTable.skillLineId = skillLineId
local lastRankXP, nextRankXP, currentXP = GetSkillLineXPInfo( skillType, ii )
baseElemTable.lastRankXP = lastRankXP
baseElemTable.nextRankXP = nextRankXP
baseElemTable.currentXP = currentXP
--ElderScrollsOfAlts.loadPlayerDataPartDetails(skillType,skillLineId,ii,name,pName)
--string name, textureName texture, number earnedRank, boolean passive, boolean ultimate, boolean purchased, number:nilable progressionIndex, number:nilable rankIndex
--GetSkillAbilityInfo(number SkillType skillType, number skillIndex, number abilityIndex)
baseElemTable.abilities = {}
local baseAbilityElem = baseElemTable.abilities
for abilityIndex = 1, numAbilities do
local ABname, ABtextureName, ABearnedRank, ABpassive, ABultimate, ABpurchased, ABprogressionIndex, ABrankIndex = GetSkillAbilityInfo(skillType, ii, abilityIndex)
ABname = zo_strformat( "<<1>>", ABname ) -- get rid of links and junk?
baseAbilityElem[ABname] = {}
baseAbilityElem[ABname].name = ABname
baseAbilityElem[ABname].textureName = ABtextureName
baseAbilityElem[ABname].earnedRank = ABearnedRank
baseAbilityElem[ABname].passive = ABpassive
baseAbilityElem[ABname].ultimate = ABultimate
baseAbilityElem[ABname].purchased = ABpurchased
baseAbilityElem[ABname].progressionIndex = ABprogressionIndex
baseAbilityElem[ABname].rankIndex = ABrankIndex
end
else
--debugMsg("loadPlayerDataPart: skillType="..skillType..". name=" ..name)
end
end
end
--
function ElderScrollsOfAlts.SaveDataPlayerTradeDetails(parentName, parentTableElem, tradeTableElem, skillType, ii, numAbilities )
--ElderScrollsOfAlts.debugMsg("parentName='",parentName,"'")
parentTableElem.skills[parentName] = {}
local selElemSubTable = parentTableElem.skills[parentName]
local skillIndex = ii
selElemSubTable.sunk = 0
selElemSubTable.sinkmax = 0
selElemSubTable.sunk2 = 0
selElemSubTable.sinkmax2 = 0
for aj = 1, numAbilities do
local name, icon, earnedRank, passive, ultimate, purchased, progressionIndex = GetSkillAbilityInfo(skillType, ii, aj)
--ElderScrollsOfAlts.debugMsg("TradeSkill Ability: name="..name.. " purchased="..tostring(purchased))
local currentUpgradeLevel, maxUpgradeLevel = GetSkillAbilityUpgradeInfo(skillType, skillIndex, aj)
--name, textureName texture, number:nilable earnedRank
local _, _, nextUpgradeEarnedRank = GetSkillAbilityNextUpgradeInfo(skillType, skillIndex, aj)
local plainName = zo_strformat(SI_ABILITY_NAME, name)
name = ZO_Skills_GenerateAbilityName(SI_ABILITY_NAME_AND_UPGRADE_LEVELS, name, currentUpgradeLevel, maxUpgradeLevel, progressionIndex)
--local name, rank, discovered, skillLineId, advised, unlockText = GetSkillLineInfo(skillType,ii)
--if not (currentUpgradeLevel and maxUpgradeLevel) and progressionIndex then
-- self.displayedAbilityProgressions[progressionIndex] = true
--end
--local isActive = (not passive and not ultimate)
--local isUltimate = (not passive and ultimate)
--ElderScrollsOfAlts.debugMsg("TradeSkill Ability: passive="..tostring(passive))
if purchased then
selElemSubTable[plainName] = {}
local selL = selElemSubTable[plainName]
selL.plainName = plainName
selL.name = name
selL.earnedRank = earnedRank
selL.currentUpgradeLevel = currentUpgradeLevel
selL.maxUpgradeLevel = maxUpgradeLevel
selL.nextUpgradeEarnedRank = nextUpgradeEarnedRank
local match1 = ElderScrollsOfAlts:matchStringList(plainName,matchNameList1)
if match1 then
selElemSubTable.sunk = selElemSubTable.sunk + (currentUpgradeLevel - 1)
selElemSubTable.sinkmax = selElemSubTable.sinkmax + (maxUpgradeLevel - 1)
tradeTableElem.sunk = selElemSubTable.sunk
tradeTableElem.sinkmax = selElemSubTable.sinkmax
end
local match2 = ElderScrollsOfAlts:matchStringList(plainName,matchNameList2)
if match2 then
selElemSubTable.sunk2 = selElemSubTable.sunk2 + (currentUpgradeLevel - 1)
selElemSubTable.sinkmax2 = selElemSubTable.sinkmax2 + (maxUpgradeLevel - 1)
tradeTableElem.sunk2 = selElemSubTable.sunk2
tradeTableElem.sinkmax2 = selElemSubTable.sinkmax2
--ElderScrollsOfAlts.debugMsg("loadPlayerTradeDetails: plainName="..plainName.." sunk2="..selElemSubTable.sunk2)
end
end
end
end
--loadPlayerEquipment
function ElderScrollsOfAlts:SavaDataPlayerEquipment(playerKey)
--local pName = GetUnitName("player")
ElderScrollsOfAlts.altData.players[playerKey].items = {}
ElderScrollsOfAlts.altData.players[playerKey].equip = {}
ElderScrollsOfAlts.altData.players[playerKey].equip.slots = {}
local elemH = ElderScrollsOfAlts.altData.players[playerKey].equip.slots
for slotId = 0, GetBagSize(BAG_WORN) do
local itemName = GetItemName(BAG_WORN, slotId)
--quality is numeric
local icon, stack, sellPrice, meetsUsageRequirement, locked, equipType, itemStyleId, quality = GetItemInfo(BAG_WORN, slotId)
local itemId = GetItemInstanceId(BAG_WORN, slotId)
local itemLink = GetItemLink(BAG_WORN, slotId)--, number LinkStyle linkStyle)
if( equipType ~= nil and equipType > EQUIP_TYPE_MIN_VALUE ) then
--TODO check itemname not nil, and EquipType > 0
elemH[slotId] = {}
elemH[slotId].itemId = itemId
elemH[slotId].itemName = itemName
elemH[slotId].itemLink = itemLink
elemH[slotId].icon = icon
elemH[slotId].quality = quality
elemH[slotId].itemStyleId = itemStyleId
elemH[slotId].slotId = slotId
elemH[slotId].equipType = equipType
elemH[slotId].equipLoc = SLOT_TYPE_REV[slotId]
--equipslot
local itemType, specializedItemType = GetItemLinkItemType(itemLink)
--Returns: number ItemType itemType, number SpecializedItemType specializedItemType
elemH[slotId].itemType = itemType
elemH[slotId].specializedItemType = specializedItemType
elemH[slotId].armorType = nil
elemH[slotId].weaponType = nil
if( itemType == ITEMTYPE_ARMOR ) then
local armorType = GetItemLinkArmorType(itemLink)
--Returns: number ArmorType armorType
elemH[slotId].armorType = armorType
end
if( itemType == ITEMTYPE_WEAPON ) then
local weaponType = GetItemLinkWeaponType(itemLink)
--Returns: number WeaponType weaponType
elemH[slotId].weaponType = weaponType
end
end
end
end
--collectResearchData
function ElderScrollsOfAlts:SaveDataPlayerResearchData(tradeSkillType, keyProfName, dataResearchElem)
dataResearchElem[keyProfName] = {}
local researchMaxSimulSlots = GetMaxSimultaneousSmithingResearch(tradeSkillType)
local researchNumlines = GetNumSmithingResearchLines(tradeSkillType)
dataResearchElem[keyProfName].ongoing = {}
dataResearchElem[keyProfName].lines = {}
dataResearchElem[keyProfName].researchNumlinesDone = 0
dataResearchElem[keyProfName].researchNumlines = researchNumlines
dataResearchElem[keyProfName].researchMS = researchMaxSimulSlots
dataResearchElem[keyProfName].researchMaxSimulSlots = researchMaxSimulSlots
dataResearchElem[keyProfName].researchNumlines = researchNumlines
--
for researchLineIndex = 1, researchNumlines do
local name, icon, numTraits, timeRequiredForNextResearchSecs = GetSmithingResearchLineInfo(tradeSkillType, researchLineIndex)
--
dataResearchElem[keyProfName].lines[name] = {}
dataResearchElem[keyProfName].lines[name].name = name
dataResearchElem[keyProfName].lines[name].numTraits = numTraits
dataResearchElem[keyProfName].lines[name].numTraitsKnown = 0
dataResearchElem[keyProfName].lines[name].researchLineIndex = researchLineIndex
dataResearchElem[keyProfName].lines[name].timeRequiredForNextResearchSecs = timeRequiredForNextResearchSecs
--
for traitIndex = 1, numTraits do
--local traitType, traitDescription, known = GetSmithingResearchLineTraitInfo(tradeSkillType, researchLineIndex, traitIndex)
local durationSecs, timeRemainingSecs = GetSmithingResearchLineTraitTimes(tradeSkillType, researchLineIndex, traitIndex)
local traitType, traitDescription, known = GetSmithingResearchLineTraitInfo(tradeSkillType, researchLineIndex, traitIndex)
if(durationSecs~=nil) then
local timeTillReady = GetTimeStamp() + timeRemainingSecs
dataResearchElem[keyProfName].ongoing[name] = {}
dataResearchElem[keyProfName].ongoing[name].name = name
dataResearchElem[keyProfName].ongoing[name].durationSecs = durationSecs
dataResearchElem[keyProfName].ongoing[name].timeRemainingSecs = timeRemainingSecs
dataResearchElem[keyProfName].ongoing[name].timeTillReady = timeTillReady
dataResearchElem[keyProfName].ongoing[name].traitIndex = traitIndex
dataResearchElem[keyProfName].ongoing[name].researchLineIndex = researchLineIndex
dataResearchElem[keyProfName].ongoing[name].traitType = traitType
dataResearchElem[keyProfName].ongoing[name].traitDescription = traitDescription
dataResearchElem[keyProfName].ongoing[name].known = known
end
if(known) then
dataResearchElem[keyProfName].lines[name].numTraitsKnown = dataResearchElem[keyProfName].lines[name].numTraitsKnown + 1
end
end
if( numTraits == dataResearchElem[keyProfName].lines[name].numTraitsKnown ) then
dataResearchElem[keyProfName].researchNumlinesDone = dataResearchElem[keyProfName].researchNumlinesDone + 1
end
end -- research
--[[ TODO: get num traints known?
for i = 1, GetMaxTraits() do
local known, name = GetItemLinkReagentTraitInfo(itemLink, i)
if known then
d(zo_strformat("Trait <<1>> is known; it's <<2>>.", i, name))
end
boolean known = IsSmithingTraitKnownForResult(number patternIndex, number materialIndex, number materialQuantity, number itemStyleId, number traitIndex)
end
number numTraitItems = GetNumSmithingTraitItems()
Returns: number:nilable ItemTraitType traitType, string itemName, textureName icon, number sellPrice, boolean meetsUsageRequirement, number itemStyleId, number ItemQuality quality
GetSmithingTraitItemInfo(number traitItemIndex)
Returns: string link = GetSmithingTraitItemLink(number traitItemIndex, number LinkStyle linkStyle)
--]]
end
--
function ElderScrollsOfAlts:SaveDataPlayerStatsData(playerElem)
if(playerElem.stats==nil) then
playerElem.stats = {}
end
if(playerElem.stats.derivedStats==nil) then
playerElem.stats.derivedStats = {}
end
--[[
local numStats = GetNumStats()
for ii = 1, numStats do
local value = GetPlayerStat(number DerivedStats derivedStat, number StatBonusOption statBonusOption)
end
-]]
--DerivedStats/StatBonusOption
--ElderScrollsOfAlts:SaveDataPlayerStatsDataSub( playerElem.stats,STAT_ARMOR_RATING, "STAT_ARMOR_RATING" )
--ElderScrollsOfAlts:SaveDataPlayerStatsDataSub( playerElem.stats,STAT_ATTACK_POWER, "STAT_ATTACK_POWER" )
--ElderScrollsOfAlts:SaveDataPlayerStatsDataSub( playerElem.stats,STAT_BLOCK, "STAT_BLOCK" )
--ElderScrollsOfAlts:SaveDataPlayerStatsDataSub( playerElem.stats,STAT_CRITICAL_RESISTANCE, "STAT_CRITICAL_RESISTANCE" )
--ElderScrollsOfAlts:SaveDataPlayerStatsDataSub( playerElem.stats,STAT_CRITICAL_STRIKE, "STAT_CRITICAL_STRIKE" )
--[[
STAT_DAMAGE_RESIST_COLD
STAT_DAMAGE_RESIST_DISEASE
STAT_DAMAGE_RESIST_DROWN
STAT_DAMAGE_RESIST_EARTH
STAT_DAMAGE_RESIST_FIRE
STAT_DAMAGE_RESIST_GENERIC
STAT_DAMAGE_RESIST_MAGIC
STAT_DAMAGE_RESIST_OBLIVION
STAT_DAMAGE_RESIST_PHYSICAL
STAT_DAMAGE_RESIST_POISON
STAT_DAMAGE_RESIST_SHOCK
STAT_DAMAGE_RESIST_START
STAT_DODGE
STAT_HEALING_DONE
STAT_HEALING_TAKEN
ElderScrollsOfAlts:SaveDataPlayerStatsDataSub( playerElem.stats,STAT_HEALTH_MAX, "STAT_HEALTH_MAX" )
STAT_HEALTH_REGEN_COMBAT
STAT_HEALTH_REGEN_IDLE
STAT_MAGICKA_MAX
STAT_MAGICKA_REGEN_COMBAT
STAT_MAGICKA_REGEN_IDLE
STAT_MISS
ElderScrollsOfAlts:SaveDataPlayerStatsDataSub( playerElem.stats,STAT_MITIGATION, "STAT_MITIGATION" )
STAT_MOUNT_STAMINA_MAX
STAT_MOUNT_STAMINA_REGEN_COMBAT
STAT_MOUNT_STAMINA_REGEN_MOVING
STAT_NONE
STAT_PHYSICAL_PENETRATION
STAT_PHYSICAL_RESIST
STAT_POWER
STAT_SPELL_CRITICAL
STAT_SPELL_MITIGATION
STAT_SPELL_PENETRATION
STAT_SPELL_POWER
STAT_SPELL_RESIST
STAT_STAMINA_MAX
STAT_STAMINA_REGEN_COMBAT
STAT_STAMINA_REGEN_IDLE
STAT_WEAPON_AND_SPELL_DAMAGE
-]]
--
end
------------------------------
--
function ElderScrollsOfAlts:SaveDataPlayerStatsDataSub(playerElemS,derivedStat,derivedStatName)
local value1 = GetPlayerStat(derivedStat, STAT_BONUS_OPTION_APPLY_BONUS )
local value2 = GetPlayerStat(derivedStat, STAT_BONUS_OPTION_DONT_APPLY_BONUS)
playerElemS[derivedStat] = {}
playerElemS[derivedStat].derivedStatName = derivedStatName
playerElemS[derivedStat].valueWithBonus = value1
playerElemS[derivedStat].valueWithOutBonus = value2
end
------------------------------
--NEW BETA/ALPHA
function ElderScrollsOfAlts.DataSaveLivePlayerNew()
if (EchoESOADatastore ~= nil) then
EchoESOADatastore.saveCurrentPlayerData()
else
ElderScrollsOfAlts:DataSaveLivePlayer()
end
end
------------------------------
--EOF |
require "torch"
if #arg < 1 then
print[[
Expects at least one package to require.
Use -lclassic to monitor classic classes instead. (see github.com/deepmind/classic)")
Usage:
th [-lclassic] generate.lua output_mode package1 [package2 [package3 ...] ]
where output_mode is htmld3force, htmld3tree. See e.g. htmld3tree.lua.
Output is to stdout; redirect it to a file like output.html.
Example:
th generate.lua htmld3tree nn > output.html
]]
os.exit(1)
end
--[[
All nodes given via node_callback(nodename) first, then
all edges given via edge_callback(childname, parentname).
]]
local function main(require_names, node_callback, edge_callback)
local edges = {}
-- Monkeypatch only needed for torch classes:
if not classic then
local TC = torch.class
torch.class = function(...)
table.insert(edges, {...})
return TC(...)
end
end
for i=1,#require_names do
require(require_names[i])
end
if classic then
-- Classic classes
for _,cls in pairs(classic._registry) do
local clsname = cls._name
node_callback(clsname)
end
for _,cls in pairs(classic._registry) do
local clsname = cls._name
local parent = rawget(cls, '_parent')
if parent then
edge_callback(clsname, parent._name)
end
end
else
-- Torch classes (recorded from monkeypatch)
for _,edge in pairs(edges) do
local clsname, parent = unpack(edge)
node_callback(clsname)
end
for _,edge in pairs(edges) do
local clsname, parent = unpack(edge)
if parent then
edge_callback(clsname, parent)
end
end
end
end
local mode = arg[1]
local arg_list = {}
for i=2,#arg do
table.insert(arg_list, arg[i])
end
local func = require(mode)
func(arg_list, main)
|
if (redis.call('exists', KEYS[1]) == 1) then
local stock = tonumber(redis.call('get', KEYS[1]));
if (stock > 0) then
redis.call('incrby', KEYS[1], -1);
return stock;
end;
return 0;
end; |
require("true-zen").setup {
ui = {
top = {
showtabline = 0,
},
left = {
number = true,
},
},
modes = {
ataraxis = {
left_padding = 3,
right_padding = 3,
top_padding = 1,
bottom_padding = 0,
auto_padding = false,
},
},
}
|
--
-- trigger_mesecons
--
-- A simple Minetest mod that allows the trigger mod to power mesecons machines.
--
-- Most mesecons machines do not require this, they can be used directly with
-- triggers.
--
-- MIT License
--
-- Copyright © 2017 by luk3yx
--
-- 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.
-- Define the emitter node
mesecon.register_node("trigger_mesecons:emitter", {
description = "Trigger: Mesecons Emitter",
sounds = default.node_sound_stone_defaults(),
on_trigger = function(pos, node, value)
if value then
minetest.set_node(pos, {name = "trigger_mesecons:emitter_on"})
mesecon.receptor_on(pos, mesecon.rules.alldirs)
else
minetest.set_node(pos, {name = "trigger_mesecons:emitter_off"})
mesecon.receptor_off(pos, mesecon.rules.alldirs)
end
end,
}, {
groups = {oddly_breakable_by_hand = 1},
tiles = {"trigger_texture.png^[colorize:#cc0a^mesecons_wire_inv.png"},
mesecons = {receptor = {
rules = mesecon.rules.alldirs,
state = mesecon.state.off,
}},
}, {
groups = {oddly_breakable_by_hand = 1, not_in_creative_inventory = 1},
tiles = {"(trigger_texture.png^mesecons_wire_inv.png)^[colorize:#ff0a"},
mesecons = {receptor = {
rules = mesecon.rules.alldirs,
state = mesecon.state.on,
}},
})
-- Define the detector node
minetest.register_node("trigger_mesecons:detector", {
description = "Trigger: Mesecons Detector",
sounds = default.node_sound_stone_defaults(),
on_trigger = function(pos, node, value)
if value then
minetest.set_node(pos, {name = "trigger_mesecons:detector_on"})
mesecon.receptor_on(pos, mesecon.rules.alldirs)
else
minetest.set_node(pos, {name = "trigger_mesecons:detector_off"})
mesecon.receptor_off(pos, mesecon.rules.alldirs)
end
end,
groups = {oddly_breakable_by_hand = 1},
tiles = {"trigger_texture.png^[colorize:#cc06^mesecons_wire_inv.png"},
mesecons = {effector = {
rules = mesecon.rules.alldirs,
action_on = function(pos, node)
trigger.send(pos, true)
end,
action_off = function(pos, node)
trigger.send(pos, false)
end,
}},
})
-- For easier typing
minetest.register_alias("trigger_mesecons:emitter", "trigger_mesecons:emitter_off")
-- For whatever reason, these may become useful in the future.
minetest.register_alias("trigger:mesecons_emitter", "trigger_mesecons:emitter_off")
minetest.register_alias("trigger:mesecons_emitter_off", "trigger_mesecons:emitter_off")
minetest.register_alias("trigger:mesecons_emitter_on", "trigger_mesecons:emitter_on")
minetest.register_alias("trigger:mesecons_detector", "trigger_mesecons:detector")
|
Impound = {}
--[[ Functions: Impound ]]--
function Impound:Update()
if not self:CanImpound() then
if self.target then
self.target:StopImpound()
end
return
end
for entity, marked in pairs(Marking.objects) do
local coords = GetEntityCoords(entity)
local siteId, site = self:GetSite(coords)
if siteId ~= nil and not marked.impound then
marked:StartImpound()
self.target = marked
elseif siteId == nil and marked.impound then
marked:StopImpound()
end
end
end
function Impound:CanImpound()
-- Check job.
if not exports.jobs:IsOnDuty(Config.Marking.Faction) then
return false
end
-- Get coords.
local ped = PlayerPedId()
local coords = GetEntityCoords(ped)
-- No result.
local id, site = self:GetSite(coords)
-- Set site.
self.site = id
-- Check site.
return id ~= nil
end
function Impound:GetSite(coords)
for id, site in pairs(Config.Impounding.Sites) do
if #(site.Coords - coords) < site.Distance then
return id, site
end
end
end
function Impound:Start(entity)
-- Check vehicle.
if entity ~= exports.oldutils:GetFacingVehicle() then
return
end
-- Animation.
if not WaitForAnimWhileFacingVehicle(Config.Impounding.Anim, entity) then return end
-- Get marked.
local marked = Marking.objects[entity or false]
if marked == nil then return end
-- Check site.
if self.site == nil then return end
-- Trigger event.
local netId = VehToNet(entity)
TriggerServerEvent("impound:finish", netId, self.site)
end
--[[ Functions: Marked ]]--
function Marked:StartImpound()
local interactable = "impound-"..self.entity
exports.interact:Register({
id = interactable,
text = "Impound Vehicle",
entity = self.entity,
event = "impound",
})
self.impound = interactable
end
function Marked:StopImpound()
exports.interact:Destroy(self.impound)
end
--[[ Events ]]--
AddEventHandler("interact:on_impound", function(interactable)
Impound:Start(interactable.entity)
end)
--[[ Threads ]]--
Citizen.CreateThread(function()
while true do
Impound:Update()
Citizen.Wait(2000)
end
end) |
fx_version 'bodacious'
game 'gta5'
author 'The Owls - Nosmakos'
description 'Discord Management (Hooking Logs)'
version '1.0.0'
server_script 'server.lua'
|
local _R = debug.getregistry()
function RPGM.Classes.BuyableItemBase(tbl, name, category, command, model, order, extra, functions, price, max, teamsAllowed)
tbl = RPGM.Classes.ItemBase(
tbl or setmetatable({}, _R["RPGMBuyableItemBase"]),
name, category, command, model, order, extra, functions
)
tbl.__type = "base_buyable"
tbl:setPrice(price)
tbl:setMax(max)
tbl:setTeamsAllowed(teamsAllowed)
RPGM.Classes.SetupExtras(tbl)
return tbl
end
if _R["RPGMBuyableItemBase"] then return end
local itemBase = _R["RPGMItemBase"]
local buyableItemBase = {}
_R["RPGMBuyableItemBase"] = buyableItemBase
buyableItemBase.__index = buyableItemBase
setmetatable(buyableItemBase, {
__index = itemBase
})
function buyableItemBase:getPrice(ply) return (isfunction(self._price) and IsValid(ply)) and self._price(ply) or self._price end
function buyableItemBase:getMax(ply) return (isfunction(self._max) and IsValid(ply)) and self._max(ply) or self._max end
function buyableItemBase:getTeamsAllowed() return self._teamsAllowed end
function buyableItemBase:setPrice(val)
if isfunction(val) then self._price = val return end
RPGM.Assert(isnumber(val), "Item price must be a number or function taking a player argument.")
self._price = val
end
function buyableItemBase:setMax(val)
if isfunction(val) then self._max = val return end
RPGM.Assert(isnumber(val), "Item maximum must be a number or function taking a player argument.")
self._max = val
end
function buyableItemBase:setTeamsAllowed(val)
RPGM.Assert(istable(val), "Entity allowed teams must be a table of team command strings.")
for k, v in pairs(val) do
RPGM.Assert(isstring(v), "Entity allowed teams must be a table of team command strings.")
end
self._teamsAllowed = val
end
function buyableItemBase:isTeamAllowed(teamName)
if not self._teamsAllowed or table.Count(self._teamsAllowed) < 1 then return true end
return self._teamsAllowed[teamName]
end
local lang = gmodI18n.getAddon("rpgm")
function buyableItemBase:canBuy(ply)
local teamName = ply:teamName()
if not self:isTeamAllowed(teamName) then return false, lang:getString("cantBuyItemAs", {teamName = teamName}) end
return self:doCustomCheck(ply)
end
function buyableItemBase:getNetworkableTable(useCache)
if useCache and self._netTable then return self._netTable end
itemBase.getNetworkableTable(self, useCache)
self._netTable["price"] = self._price
self._netTable["max"] = self._max
self._netTable["teamsAllowed"] = self._teamsAllowed
return self._netTable
end
|
require 'class'
api = require('api')
-- https://bitbucket.org/AndyZe/pid/src/31105f05b463573c020800d2cef81307d9a98579/src/controller.cpp?at=master&fileviewer=file-view-default
local LowPassFilter = class(function(self, sample_rate, cutoff_frequency)
if(sample_rate == nil) then
sample_rate = 1
end
if(cutoff_frequency == nil) then
cutoff_frequency = -1
end
self.sample_rate = sample_rate
-- Filtering
-- Cutoff frequency for the derivative calculation in Hz.
-- Negative -> Has not been set by the user yet, so use a default.
self.cutoff_frequency = cutoff_frequency
-- Used in filter calculations. Default 1.0 corresponds to a cutoff frequency at
-- 1/4 of the sample rate.
self.c = 1.0
-- Used to check for tan(0)==>NaN in the filter calculation
self.tan_filt = 1.0
-- My filter reference was Julius O. Smith III, Intro. to Digital Filters With Audio Applications.
if (self.cutoff_frequency ~= -1) then
-- Check if tan(_) is really small, could cause c = NaN
self.tan_filt = math.tan( (self.cutoff_frequency*6.2832)*(1/self.sample_rate)/2 );
simAddStatusbarMessage("Filter sample rate = " .. self.sample_rate)
simAddStatusbarMessage("Filter cutoff frequency = " .. self.cutoff_frequency)
simAddStatusbarMessage("Filter tan = " .. self.tan_filt)
-- Avoid tan(0) ==> NaN
if ( (self.tan_filt <= 0.) and (self.tan_filt > -0.01) ) then
self.tan_filt = -0.01;
end
if ( (self.tan_filt >= 0.) and (self.tan_filt < 0.01) ) then
self.tan_filt = 0.01;
end
self.c = 1/self.tan_filt;
simAddStatusbarMessage("Filter c = " .. self.c)
end
self.u = {0.0, 0.0, 0.0}
self.y = {0.0, 0.0, 0.0}
end)
function LowPassFilter:process(u)
self.u[3] = self.u[2];
self.u[2] = self.u[1];
self.u[1] = u;
self.y[3] = self.y[2];
self.y[2] = self.y[1];
self.y[1] = (1/(1+self.c*self.c+1.414*self.c))
*( self.u[3]+2*self.u[2]+self.u[1]
-(self.c*self.c-1.414*self.c+1)*self.y[3]
-(-2*self.c*self.c+2)*self.y[2]
)
return self.y[1]
end
return LowPassFilter
|
---------------------------------------------------------------------
-- PostgreSQL specific tests and configurations.
-- $Id: postgres.lua,v 1.2 2006/01/25 19:15:21 tomas Exp $
---------------------------------------------------------------------
table.insert (CUR_METHODS, "numrows")
table.insert (EXTENSIONS, numrows)
|
---@class GenericInMethod<T>
---@field a T
local GenericInMethod = {}
---@param arg T
function GenericInMethod:colonMethod(arg)
---@type T
local thing
thing = self.a
end
---@param arg T
function GenericInMethod.dotMethod(arg)
---@type T
local thing
thing = self.a
end
---@param arg T
GenericInMethod.lambdaMethod = function(arg)
---@type T
local thing
thing = self.a
end
-- Expect error
---@generic T
---@param arg T
function GenericInMethod:colonMethodShadow(arg)
end
-- Expect error
---@generic T
---@param arg T
function GenericInMethod:dotMethodShadow(arg)
end
-- Expect error
---@generic T
---@param arg T
GenericInMethod.lambdaMethodShadow = function(arg)
end
|
function get()
local data = {}
data.house = db:singleQuery([[
SELECT c.name AS bidname, b.bid, b.bid_end, b.last_bid, a.name AS ownername, b.name, b.rent, b.size, b.beds, b.town_id, b.id FROM houses b
LEFT JOIN players a ON a.id = b.owner
LEFT JOIN players c ON c.id = b.highest_bidder
WHERE b.id = ?
]], http.getValues.id)
if data.house == nil then
http:redirect("/")
return
end
data.town = otbm:townByID(tonumber(data.house.town_id))
data.period = config:get("houseRentPeriod")
data.logged = session:isLogged()
data.error = session:getFlash("error")
data.success = session:getFlash("success")
if data.logged then
data.characters = db:query("SELECT name FROM players WHERE account_id = ?", session:loggedAccount().ID)
end
http:render("viewhouse.html", data)
end
-- last_biD DINERO
-- hihest_bid player_id
-- ofertas deben ser mayores que bid |
local M = {}
local memory = _G.memory
local luap = require 'luap'
local config = require 'config'
local draw = require 'draw'
local smw = require 'game.smw'
local u8 = memory.readbyte
local s16 = memory.readsword
local OPTIONS = config.OPTIONS
local screen_coordinates = smw.screen_coordinates
local WRAM = smw.WRAM
local SMW = smw.constant
-- sprite_table environment
do
local xText, yText, height, xCam, yCam, realFrame, xPos, yPos, number, color
local function draw_near_sprite(slot)
local x, y = screen_coordinates(xPos, yPos, xCam, yCam)
local timer = u8('WRAM', WRAM.shooter_timer + slot)
local realTimer = 2 * timer - (realFrame % 2 == 0 and 1 or 0)
local text = string.format('#%x %s', slot, realTimer)
draw.Font = 'Uzebox6x8'
draw.text(draw.AR_x * x, draw.AR_y * y, text, color, 0x000060)
end
local function sprite_info(slot)
local xLow = u8('WRAM', WRAM.shooter_x_low + slot)
local xHigh = u8('WRAM', WRAM.shooter_x_high + slot)
local yLow = u8('WRAM', WRAM.shooter_y_low + slot)
local yHigh = u8('WRAM', WRAM.shooter_y_high + slot)
xPos = luap.signed16(0x100 * xHigh + xLow)
yPos = luap.signed16(0x100 * yHigh + yLow)
color = number <= 2 and 0x6bf442 or 0xf40842
local text = string.format('#%x: %.2x (%d, %d)', slot, number, xPos, yPos)
draw.Font = 'Uzebox8x12'
draw.text(xText, yText, text, color, 0x000030)
draw_near_sprite(slot)
end
function M.sprite_table()
if not OPTIONS.display_shooter_sprite_info then return end
draw.Font = 'Uzebox8x12'
height = draw.font_height()
xText = draw.AR_x * 160
yText = draw.AR_y * 248
xCam = s16('WRAM', WRAM.camera_x)
yCam = s16('WRAM', WRAM.camera_y)
realFrame = u8('WRAM', WRAM.real_frame)
draw.text(xText, yText, 'Shooters:', 0x6bf442, 0x000030)
yText = yText + height
for slot = 0, SMW.shooter_sprite_max - 1 do
number = u8('WRAM', WRAM.shooter_number + slot)
if number ~= 0 then
sprite_info(slot)
yText = yText + height
end
end
end
end
return M
|
-- We are using PCH, so you must disable PCH on the protobuf files, and enable generation on stdafx.cpp
-- note[0]
-- It appears that by messing with the output directories, VS doesn't start the binary in the right place
-- when debugging. If you simply double click the Driver.exe, for example, it will find the plugins and JSON
-- configs just fine. But if you do it from the IDE, it won't. I copy the required files into ../build to solve this.
-- Better solution: obey, or figure out, the necessary directory structure to make VS happy.
workspace "Driver"
configurations {"Debug", "Release"}
platforms {"Win32", "Win64", "UnitTestWin32"}
language "C++"
project "Serial"
targetdir "bin/%{cfg.buildcfg}/%{cfg.platform}"
targetname "Serial"
boost_incl_dir = "D:/Libraries/boost/boost_1_61_0"
includedirs {
boost_incl_dir,
"../src/Serial"
}
flags {
"MultiProcessorCompile",
"C++11"
}
files {
"../src/Serial/**.cpp",
"../src/Serial/**.h"
}
boost_win32_dir = "D:/Libraries/boost/boost_1_61_0/stage/win32/lib"
boost_win64_dir = "D:/Libraries/boost/boost_1_61_0/stage/x64/lib"
pchheader "stdafx.h"
pchsource "../src/Serial/stdafx.cpp"
defines {"BOOST_THREAD_USE_LIB"}
filter {"platforms:Win32 or platforms:Win64"}
kind "SharedLib"
filter{"platforms:UnitTestWin32"}
kind "ConsoleApp"
filter "platforms:*Win32*"
system "Windows"
architecture "x86"
libdirs {
boost_win32_dir
}
defines {"WIN32", "_WIN32_WINNT=0x0A00"}
filter "configurations:Debug"
defines {"DEBUG", "_DEBUG"}
symbols "On"
optimize "Off"
filter "configurations:Release"
defines {"NDEBUG"}
optimize "On"
filter {"system:Windows"}
defines {"_WINDOWS", "_USRDLL"}
-- not sure if this is actually setting sdl checks. We should be sure to work without them
buildoptions {"-sdl"}
filter {"system:Windows", "configurations:Debug"}
buildoptions {"-D_SCL_SECURE_NO_WARNINGS"}
project "Driver"
targetdir "bin/%{cfg.buildcfg}/%{cfg.platform}"
targetname "HardlightPlatform"
-- dependencies
protobuf_incl_dir = "D:/protobuf-3.0.0/cmake/build/solution/include"
shared_comms_incl_dir = "C:/Users/NullSpace Team/Documents/NS_Unreal_SDK/src/Driver/SharedCommunication"
boost_incl_dir = "D:/Libraries/boost/boost_1_61_0"
protobuf_def_incl_dir = "C:/Users/NullSpace Team/Documents/NS_Unreal_SDK/src/Driver/protobuff_defs"
disablewarnings {"4800"}
includedirs {
protobuf_incl_dir,
shared_comms_incl_dir,
boost_incl_dir,
"../src/Driver/include",
"../src/Driver/events_impl"
}
flags {
"MultiProcessorCompile",
"C++11"
}
--links {"System", "UnityEditor", "UnityEngine", "System.PlatformProcess"}
files {
"../src/Driver/**.cpp",
"../src/Driver/**.h",
"../src/Driver/**.hpp",
"../src/Driver/protobuff_defs/**.pb.cc",
path.join(shared_comms_incl_dir, "ScheduledEvent.cpp")
}
boost_win32_dir = "D:/Libraries/boost/boost_1_61_0/stage/win32/lib"
boost_win64_dir = "D:/Libraries/boost/boost_1_61_0/stage/x64/lib"
protobuf_win32_dir = "D:/protobuf-3.0.0/cmake/build/solution"
protobuf_win64_dir = "D:/protobuf-3.0.0/cmake/build/solution64"
pchheader "stdafx.h"
pchsource "../src/Driver/stdafx.cpp"
defines {"NS_DRIVER_EXPORTS", "NSVR_BUILDING_CORE", "BOOST_THREAD_USE_LIB"}
filter {"files:**.pb.cc or files:**ScheduledEvent.cpp or files:**jsoncpp.cpp"}
flags {'NoPCH'}
filter {"platforms:Win32 or platforms:Win64"}
kind "SharedLib"
postbuildcommands {
"{COPY} %{cfg.targetdir}/%{cfg.targetname}%{cfg.targetextension} bin/%{cfg.buildcfg}/UnitTestWin32"
-- see note at top [0]
--"{COPY} %{cfg.targetdir}/%{cfg.targetname}%{cfg.targetextension} ../build"
}
filter {"platforms:UnitTestWin32"}
kind "ConsoleApp"
debugdir "%{cfg.targetdir}"
postbuildcommands {
-- "{COPY} ../src/Driver/*.json %{cfg.targetdir}",
-- see note at top [0]
-- "{COPY} ../src/Driver/*.json ../build/"
}
filter {"platforms:*Win32*", "configurations:Debug"}
libdirs {
path.join(protobuf_win32_dir, "Debug")
}
filter {"platforms:*Win32*", "configurations:Release"}
libdirs {
path.join(protobuf_win32_dir, "Release")
}
filter "platforms:*Win32*"
system "Windows"
architecture "x86"
libdirs {
boost_win32_dir
}
defines {"WIN32", "_WIN32_WINNT=0x0A00"}
filter "configurations:Debug"
defines {"DEBUG", "_DEBUG"}
symbols "On"
optimize "Off"
links {"libprotobufd"}
filter "configurations:Release"
defines {"NDEBUG"}
optimize "On"
links {"libprotobuf"}
filter {"system:Windows"}
defines {"_WINDOWS", "_USRDLL"}
-- not sure if this is actually setting sdl checks. We should be sure to work without them
buildoptions {"-sdl"}
filter {"system:Windows", "configurations:Debug"}
buildoptions {"-D_SCL_SECURE_NO_WARNINGS"}
project "HardlightMkIII"
targetdir "bin/Plugins/%{cfg.buildcfg}/%{cfg.platform}"
targetname "HardlightPlugin"
--shared_comms_incl_dir = "C:/Users/NullSpace Team/Documents/NS_Unreal_SDK/src/Driver/SharedCommunication"
boost_incl_dir = "D:/Libraries/boost/boost_1_61_0"
--protobuf_def_incl_dir = "C:/Users/NullSpace Team/Documents/NS_Unreal_SDK/src/Driver/protobuff_defs"
disablewarnings {"4800"}
includedirs {
boost_incl_dir,
"../src/plugins/hardlight",
"../src/Driver/include"
}
flags {
"MultiProcessorCompile",
"C++11"
}
files {
"../src/plugins/hardlight/**.cpp",
"../src/plugins/hardlight/**.h",
"../src/plugins/hardlight/**.hpp",
"../src/Driver/include/**.h",
"../src/plugins/hardlight/zone_log/**.cpp",
"../src/plugins/hardlight/zone_log/**.h",
"../src/plugins/hardlight/**.h",
"../src/plugins/hardlight/**.cpp"
}
boost_win32_dir = "D:/Libraries/boost/boost_1_61_0/stage/win32/lib"
boost_win64_dir = "D:/Libraries/boost/boost_1_61_0/stage/x64/lib"
pchheader "stdafx.h"
pchsource "../src/plugins/hardlight/stdafx.cpp"
--nsvr_core_win32_dir_debug = "C:/Users/NullSpace Team/Documents/NS_Unreal_SDK/build/bin/Debug/Win32"
--nsvr_core_win32_dir_release = "C:/Users/NullSpace Team/Documents/NS_Unreal_SDK/build/bin/Release/Win32"
nsvr_core_win32_dir_debug = "../build/bin/Debug/Win32"
nsvr_core_win32_dir_release = "../build/bin/Release/Win32"
nsvr_core_win32_executable_debug = "../build/bin/Debug/UnitTestWin32"
nsvr_core_win32_executable_release = "../build/bin/Release/UnitTestWin32"
defines {"BOOST_THREAD_USE_LIB", "BOOST_INTERPROCESS_SHARED_DIR_FUNC"}
filter {"files:**.pb.cc or files:main.cpp"}
flags {'NoPCH'}
filter {"platforms:Win32 or platforms:Win64"}
kind "SharedLib"
filter {"platforms:UnitTestWin32"}
kind "ConsoleApp"
filter "platforms:*Win32*"
system "Windows"
architecture "x86"
defines {"WIN32", "_WIN32_WINNT=0x0A00"}
libdirs {
boost_win32_dir
}
filter "configurations:Debug"
defines {"DEBUG", "_DEBUG"}
symbols "On"
optimize "Off"
links {"HardlightPlatform"}
libdirs {
nsvr_core_win32_dir_debug
}
postbuildcommands {
"{MKDIR} %{nsvr_core_win32_executable_debug}/plugins/hardlight",
"{COPY} %{cfg.targetdir}/HardlightPlugin.dll %{nsvr_core_win32_executable_debug}/plugins/hardlight",
"{COPY} ../src/Plugins/hardlight/*.json %{nsvr_core_win32_executable_debug}/plugins/hardlight"
}
filter "configurations:Release"
defines {"NDEBUG"}
optimize "On"
links { "HardlightPlatform"}
libdirs {
nsvr_core_win32_dir_release
}
postbuildcommands {
"{MKDIR} %{nsvr_core_win32_executable_release}/plugins/hardlight",
"{COPY} %{cfg.targetdir}/HardlightPlugin.dll %{nsvr_core_win32_executable_release}/plugins/hardlight",
"{COPY} ../src/Plugins/hardlight/*.json %{nsvr_core_win32_executable_release}/plugins/hardlight"
}
filter {"system:Windows"}
defines {"_WINDOWS", "_USRDLL"}
filter {"system:Windows", "configurations:Debug"}
buildoptions {"-D_SCL_SECURE_NO_WARNINGS"}
project "OpenVR"
targetdir "bin/Plugins/%{cfg.buildcfg}/%{cfg.platform}"
targetname "OpenVRPlugin"
disablewarnings {"4800"}
includedirs {
"../src/plugins/openvr",
"C:/Users/NullSpace Team/Documents/openvr/headers",
"../src/Driver/include"
}
flags {
"MultiProcessorCompile",
"C++11"
}
files {
"../src/plugins/openvr/**.cpp",
"../src/plugins/openvr/**.h",
"../src/Driver/include/**.h"
}
nsvr_core_win32_executable_debug = "../build/bin/Debug/UnitTestWin32"
nsvr_core_win32_executable_release = "../build/bin/Release/UnitTestWin32"
pchheader "stdafx.h"
pchsource "../src/plugins/openvr/stdafx.cpp"
--nsvr_core_win32_dir_debug = "C:/Users/NullSpace Team/Documents/NS_Unreal_SDK/build/bin/Debug/Win32"
--nsvr_core_win32_dir_release = "C:/Users/NullSpace Team/Documents/NS_Unreal_SDK/build/bin/Release/Win32"
nsvr_core_win32_dir_debug = "../build/bin/Debug/Win32"
nsvr_core_win32_dir_release = "../build/bin/Release/Win32"
openvr_win32_dir = "C:/Users/NullSpace Team/Documents/openvr/lib/win32"
filter {"files:**.pb.cc"}
flags {'NoPCH'}
filter {"platforms:Win32 or platforms:Win64"}
kind "SharedLib"
filter {"platforms:UnitTestWin32"}
kind "ConsoleApp"
filter "platforms:*Win32*"
system "Windows"
architecture "x86"
defines {"WIN32", "_WIN32_WINNT=0x0A00"}
filter "configurations:Debug"
defines {"DEBUG", "_DEBUG"}
symbols "On"
optimize "Off"
links {"HardlightPlatform", "openvr_api"}
libdirs {
nsvr_core_win32_dir_debug,
openvr_win32_dir
}
postbuildcommands {
"{MKDIR} %{nsvr_core_win32_executable_debug}/plugins/openvr",
"{COPY} %{cfg.targetdir}/OpenVRPlugin.dll %{nsvr_core_win32_executable_debug}/plugins/openvr",
"{COPY} openvr/openvr_api.dll %{nsvr_core_win32_executable_debug}/plugins/openvr",
"{COPY} ../src/Plugins/openvr/*.json %{nsvr_core_win32_executable_debug}/plugins/openvr"
}
filter "configurations:Release"
defines {"NDEBUG"}
optimize "On"
links { "HardlightPlatform", "openvr_api"}
libdirs {
nsvr_core_win32_dir_release,
openvr_win32_dir
}
postbuildcommands {
"{MKDIR} %{nsvr_core_win32_executable_release}/plugins/openvr",
"{COPY} %{cfg.targetdir}/OpenVRPlugin.dll %{nsvr_core_win32_executable_release}/plugins/openvr",
"{COPY} openvr/openvr_api.dll %{nsvr_core_win32_executable_release}/plugins/openvr",
"{COPY} ../src/Plugins/openvr/*.json %{nsvr_core_win32_executable_release}/plugins/openvr"
}
filter {"system:Windows"}
defines {"_WINDOWS", "_USRDLL"}
filter {"system:Windows", "configurations:Debug"}
buildoptions {"-D_SCL_SECURE_NO_WARNINGS"} |
--The MIT License (MIT)
--
--Copyright (c) 2016 Jaap Braam
--
--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.
--
--Author: Jaap Braam
function padBase64(s)
local p=4-(#s % 4)
return s..string.rep("=",p % 4)
end
-- time stamp
local DSEC=24*60*60 -- secs in a day
local YSEC=365*DSEC -- secs in a year
local LSEC=YSEC+DSEC -- secs in a leap year
local FSEC=4*YSEC+DSEC -- secs in a 4-year interval
local BASE_DOW=4 -- 1970-01-01 was a Thursday
local BASE_YEAR=1970 -- 1970 is the base year
local _days={
-1, 30, 58, 89, 119, 150, 180, 211, 242, 272, 303, 333, 364
}
local _lpdays={}
for i=1,2 do _lpdays[i]=_days[i] end
for i=3,13 do _lpdays[i]=_days[i]+1 end
function gmtime(t,us)
--print(os.date("!\n%c\t%j",t),t)
local y,j,m,d,w,h,n,s
local mdays=_days
s=t
-- First calculate the number of four-year-interval, so calculation
-- of leap year will be simple. Btw, because 2000 IS a leap year and
-- 2100 is out of range, this formula is so simple.
y=s/FSEC
s=s-y*FSEC
y=y*4+BASE_YEAR -- 1970, 1974, 1978, ...
if s>=YSEC then
y=y+1 -- 1971, 1975, 1979,...
s=s-YSEC
if s>=YSEC then
y=y+1 -- 1972, 1976, 1980,... (leap years!)
s=s-YSEC
if s>=LSEC then
y=y+1 -- 1971, 1975, 1979,...
s=s-LSEC
else -- leap year
mdays=_lpdays
end
end
end
j=s/DSEC
s=s-j*DSEC
local m=1
while mdays[m]<j do m=m+1 end
m=m-1
local d=(j-mdays[m])
-- Calculate day of week. Sunday is 0
w=(t/DSEC+BASE_DOW)%7
-- Calculate the time of day from the remaining seconds
h=s/3600
s=s-h*3600
n=s/60
s=s-n*60
return string.format('%04d-%02d-%02dT%02d:%02d:%02d.%06dZ',y,m,d,h,n,s,us)
end
|
if mcbPacker then --mcbPacker.ignore
mcbPacker.require("s5CommunityLib/comfort/table/KeyOf")
end --mcbPacker.ignore
ObserverInfo = {ObservedPlayers = {}, ObservedResearch = {}, ObservedUpgrade = {}, ShowLines = {}}
function ObserverInfo.InitIfLocalSpecForAllPlayers(guipath)
if GUI.GetPlayerID()==17 then
local p = {}
for i=1,XNetwork.GameInformation_GetMapMaximumNumberOfHumanPlayer() do
if XNetwork.GameInformation_IsHumanPlayerAttachedToPlayerID(i)==1 then
table.insert(p, i)
end
end
ObserverInfo.Init(p, guipath)
end
end
function ObserverInfo.Init(players, guipath)
ObserverInfo.ObservedPlayers = players
ObserverInfo.GameCallback_StartResearch = GameCallback_StartResearch
function GameCallback_StartResearch(id, tech, state)
if ObserverInfo.GameCallback_StartResearch then
ObserverInfo.GameCallback_StartResearch(id, tech, state)
end
if IsAlive(id) and KeyOf(GetPlayer(id), ObserverInfo.ObservedPlayers) then
ObserverInfo.AddResearch(id, tech)
end
end
ObserverInfo.GameCallback_EntityAttached = GameCallback_EntityAttached
function GameCallback_EntityAttached(attacher, attached_to, attach_type, attached_event)
if ObserverInfo.GameCallback_EntityAttached then
ObserverInfo.GameCallback_EntityAttached(attacher, attached_to, attach_type, attached_event)
end
if attach_type==57 and IsAlive(attached_to)
and ObserverInfo.ShowBuildingsOfUCats[Logic.GetUpgradeCategoryByBuildingType(Logic.GetEntityType(attached_to))]
and KeyOf(GetPlayer(attached_to), ObserverInfo.ObservedPlayers) then
ObserverInfo.AddUpgrade(attached_to)
end
if attach_type==20 and IsAlive(attacher)
and ObserverInfo.ShowBuildingsOfUCats[Logic.GetUpgradeCategoryByBuildingType(Logic.GetEntityType(attacher))]
and KeyOf(GetPlayer(attacher), ObserverInfo.ObservedPlayers) then
ObserverInfo.AddBuild(attacher)
end
end
ObserverInfo.GameCallback_OnBuildingUpgradeComplete = GameCallback_OnBuildingUpgradeComplete
function GameCallback_OnBuildingUpgradeComplete(_OldID, _NewID)
ObserverInfo.GameCallback_OnBuildingUpgradeComplete(_OldID, _NewID)
for i=table.getn(ObserverInfo.ObservedUpgrade),1,-1 do
local r = ObserverInfo.ObservedUpgrade[i]
if r.id==_OldID and r.build==false then
table.remove(ObserverInfo.ObservedUpgrade, i)
end
end
end
ObserverInfo.GameCallback_OnBuildingConstructionComplete = GameCallback_OnBuildingConstructionComplete
function GameCallback_OnBuildingConstructionComplete(_BuildingID,_PlayerID)
ObserverInfo.GameCallback_OnBuildingConstructionComplete(_BuildingID,_PlayerID)
for i=table.getn(ObserverInfo.ObservedUpgrade),1,-1 do
local r = ObserverInfo.ObservedUpgrade[i]
if r.id==_BuildingID and r.build==true then
table.remove(ObserverInfo.ObservedUpgrade, i)
end
end
end
ObserverInfo.GameCallback_OnTechnologyResearched = GameCallback_OnTechnologyResearched
function GameCallback_OnTechnologyResearched(pl,tech)
ObserverInfo.GameCallback_OnTechnologyResearched(pl,tech)
for i=table.getn(ObserverInfo.ObservedResearch),1,-1 do
local r = ObserverInfo.ObservedResearch[i]
if r.player==pl and r.tech==tech then
table.remove(ObserverInfo.ObservedResearch, i)
end
end
end
if XGUIEng.GetWidgetID("ObserverInfo")==0 then
CWidget.Transaction_AddRawWidgetsFromFile(guipath or "data/maps/externalmap/observerinfo.xml", "VideoPreview")
--Script.Load("data/maps/externalmap/ObserverInfoGUI.lua")
CWidget.Transaction_Commit()
end
XGUIEng.ShowWidget("ObserverInfo", 1)
Input.KeyBindDown(Keys.F9, 'XGUIEng.ShowWidget("ObserverInfo", 1-XGUIEng.IsWidgetShown("ObserverInfo"))', 2)
end
ObserverInfo.ShowBuildingsOfUCats = {
[UpgradeCategories.Headquarters] = true,
[UpgradeCategories.Archery] = true,
[UpgradeCategories.Barracks] = true,
[UpgradeCategories.Stable] = true,
[UpgradeCategories.Foundry] = true,
[UpgradeCategories.Tavern] = true,
[UpgradeCategories.Monastery] = true,
[UpgradeCategories.Tower] = true,
[UpgradeCategories.University] = true,
[UpgradeCategories.VillageCenter] = true,
}
function ObserverInfo.UpdateWidget()
local txt = ""
for _,p in ipairs(ObserverInfo.ObservedPlayers) do
txt = txt..ObserverInfo.GetPlayerLine(p)
end
local ttxt = ""
for i=table.getn(ObserverInfo.ObservedResearch),1,-1 do
local r = ObserverInfo.ObservedResearch[i]
local t, del = ObserverInfo.GetResearchTextLine(r)
ttxt = t..ttxt
if del then
table.remove(ObserverInfo.ObservedResearch, i)
end
end
txt = txt.." @cr "..ttxt
ttxt = ""
for i=table.getn(ObserverInfo.ObservedUpgrade),1,-1 do
local r = ObserverInfo.ObservedUpgrade[i]
local t, del = ObserverInfo.GetUpgradeLine(r)
ttxt = t..ttxt
if del then
table.remove(ObserverInfo.ObservedUpgrade, i)
end
end
txt = txt.." @cr "..ttxt
ttxt = ""
for i=table.getn(ObserverInfo.ShowLines),1,-1 do
local r = ObserverInfo.ShowLines[i]
local t, del = ObserverInfo.GetShowLine(r)
ttxt = t..ttxt
if del then
table.remove(ObserverInfo.ShowLines, i)
end
end
txt = txt.." @cr "..ttxt
XGUIEng.SetText("ObserverInfoTxt", txt)
end
function ObserverInfo.AddResearch(id, tech)
ObserverInfo.InsertByPlayer(ObserverInfo.ObservedResearch, {id=id, tech=tech, progressActive=false, timer=Logic.GetTime(), player=GetPlayer(id)})
end
function ObserverInfo.AddUpgrade(id)
ObserverInfo.InsertByPlayer(ObserverInfo.ObservedUpgrade, {id=id, type=ObserverInfo.GetNextETypeInUCat(Logic.GetEntityType(id)), timer=Logic.GetTime(), player=GetPlayer(id), build=false})
end
function ObserverInfo.AddBuild(id)
ObserverInfo.InsertByPlayer(ObserverInfo.ObservedUpgrade, {id=id, type=Logic.GetEntityType(id), timer=Logic.GetTime(), player=GetPlayer(id), build=true})
end
function ObserverInfo.AddLine(pl, txt)
ObserverInfo.InsertByPlayer(ObserverInfo.ShowLines, {player=pl, txt=txt, timer=Logic.GetTime()})
end
function ObserverInfo.InsertByPlayer(t, ins)
local p = ins.player
for i=1,table.getn(t) do
if t[i].player > p then
table.insert(t, i, ins)
return
end
end
table.insert(t, ins)
end
function ObserverInfo.GetPlayerColoredName(p)
return " @color:"..table.concat({GUI.GetPlayerColor(p)}, ",").." "..UserTool_GetPlayerName(p).." @color:255,255,255 "
end
function ObserverInfo.GetTechName(tech)
local stt = "names/"..KeyOf(tech, Technologies)
return XGUIEng.GetStringTableText(stt) or stt
end
function ObserverInfo.GetBuildingTypeName(ty)
local stt = "names/"..Logic.GetEntityTypeName(ty)
return XGUIEng.GetStringTableText(stt) or stt
end
function ObserverInfo.GetResearchTextLine(r)
if IsDead(r.id) or Logic.GetTechnologyResearchedAtBuilding(r.id)~=r.tech or r.cancelled then
if r.timer+15<Logic.GetTime() then
return "", true
end
r.cancelled = true
return " @cr "..ObserverInfo.GetPlayerColoredName(r.player)..ObserverInfo.GetTechName(r.tech)..(r.progressActive and " cancelled" or " 0%")
end
r.progressActive = true
r.timer = Logic.GetTime()
local prog = Logic.GetTechnologyProgress(r.player, r.tech)
return " @cr "..ObserverInfo.GetPlayerColoredName(r.player)..ObserverInfo.GetTechName(r.tech).." "..prog.."%"
end
function ObserverInfo.GetPlayerLine(p)
local skilled, slost, bkilled, blost = ObserverInfo.ReadPlayerKillStats(p)
return ObserverInfo.GetPlayerColoredName(p)
.."A:"..Logic.GetNumberOfAttractedWorker(p)
.." L:"..Logic.GetNumberOfEntitiesOfTypeOfPlayer(p, Entities.PU_Serf)
.." M:"..Logic.GetNumberOfAttractedSoldiers(p).." ("..Logic.GetNumberOfLeader(p)..") Pop:"
..Logic.GetPlayerAttractionUsage(p).."/"..Logic.GetPlayerAttractionLimit(p)
.." KD: "..skilled.."/"..slost.." + "..bkilled.."/"..blost
.." @cr "
end
function ObserverInfo.GetUpgradeLine(r)
if r.build then
if IsDead(r.id) or r.cancelled then
if r.timer+15<Logic.GetTime() then
return "", true
end
r.cancelled = true
return " @cr "..ObserverInfo.GetPlayerColoredName(r.player)..ObserverInfo.GetBuildingTypeName(r.type).." cancelled"
end
r.timer = Logic.GetTime()
local prog = ObserverInfo.ReadBuildProgress(r.id)
prog = math.floor(prog*100)
return " @cr "..ObserverInfo.GetPlayerColoredName(r.player)..ObserverInfo.GetBuildingTypeName(r.type).." "..prog.."%"
else
if IsDead(r.id) or Logic.GetRemainingUpgradeTimeForBuilding(r.id)==Logic.GetTotalUpgradeTimeForBuilding(r.id) or r.cancelled then
if r.timer+15<Logic.GetTime() then
return "", true
end
r.cancelled = true
return " @cr "..ObserverInfo.GetPlayerColoredName(r.player)..ObserverInfo.GetBuildingTypeName(r.type).." cancelled"
end
r.timer = Logic.GetTime()
local t = Logic.GetTotalUpgradeTimeForBuilding(r.id)
local prog = math.floor((t-Logic.GetRemainingUpgradeTimeForBuilding(r.id))/t*100)
return " @cr "..ObserverInfo.GetPlayerColoredName(r.player)..ObserverInfo.GetBuildingTypeName(r.type).." "..prog.."%"
end
end
function ObserverInfo.GetShowLine(r)
if r.timer+15<Logic.GetTime() then
return "", true
end
return " @cr "..ObserverInfo.GetPlayerColoredName(r.player)..r.txt
end
function ObserverInfo.ReadPlayerKillStats(p)
return CppLogic.Logic.PlayerGetKillStatistics(p)
end
function ObserverInfo.ReadBuildProgress(id)
return CppLogic.Entity.Building.GetHeight(id)
end
function ObserverInfo.GetNextETypeInUCat(ety)
local uc = Logic.GetUpgradeCategoryByBuildingType(ety)
local types = {Logic.GetBuildingTypesInUpgradeCategory(uc)}
table.remove(types, 1)
local found = false
for _,et in ipairs(types) do
if found then
return et
elseif et==ety then
found = true
end
end
end
|
local json = require 'cjson'
json.decode_array_with_array_mt(true)
local jsonschema = require 'resty.ljsonschema'
describe("[string coercion]", function()
describe("number:", function()
local schema = {
type = "number",
minimum = 1.1,
maximum = 3,
exclusiveMinimum = true,
}
it("coerces a number", function()
local validator = assert(jsonschema.generate_validator(
schema, {
coercion = true,
}))
assert.is_false(validator("1"))
assert.is_false(validator("1.1"))
assert.is_true(validator("2"))
assert.is_true(validator("3"))
end)
it("does not coerce a number if not set to do so", function()
local validator = assert(jsonschema.generate_validator(
schema, {
coercion = false,
}))
assert.is_false(validator("1"))
assert.is_false(validator("1.1"))
assert.is_false(validator("2"))
assert.is_false(validator("3"))
end)
end)
describe("integer:", function()
local schema = {
type = "integer",
minimum = 1,
maximum = 3,
exclusiveMinimum = true,
}
it("coerces an integer", function()
local validator = assert(jsonschema.generate_validator(
schema, {
coercion = true,
}))
assert.is_false(validator("1"))
assert.is_true(validator("2"))
assert.is_true(validator("3"))
end)
it("does not coerce an integer if not set to do so", function()
local validator = assert(jsonschema.generate_validator(
schema, {
coercion = false,
}))
assert.is_false(validator("1"))
assert.is_false(validator("2"))
assert.is_false(validator("3"))
end)
end)
describe("boolean:", function()
local schema = {
type = "boolean",
}
it("coerces a number", function()
local validator = assert(jsonschema.generate_validator(
schema, {
coercion = true,
}))
assert.is_false(validator("no boolean"))
assert.is_true(validator("true"))
assert.is_true(validator("false"))
end)
it("does not coerce a boolean if not set to do so", function()
local validator = assert(jsonschema.generate_validator(
schema, {
coercion = false,
}))
assert.is_false(validator("no boolean"))
assert.is_false(validator("true"))
assert.is_false(validator("false"))
end)
end)
describe("type list (boolean and number)", function()
local schema = {
type = { "number", "boolean"},
minimum = 1.1,
maximum = 3,
exclusiveMinimum = true,
}
it("coerces a number", function()
local validator = assert(jsonschema.generate_validator(
schema, {
coercion = true,
}))
assert.is_false(validator("1"))
assert.is_false(validator("1.1"))
assert.is_true(validator("2"))
assert.is_true(validator("3"))
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 log = require("apisix.core.log")
local sleep = require("apisix.core.utils").sleep
local timer_every = ngx.timer.every
local timer_at = ngx.timer.at
local update_time = ngx.update_time
local now = ngx.now
local pcall = pcall
local _M = {
version = 0.1,
}
local function _internal(timer)
timer.start_time = now()
repeat
local ok, err = pcall(timer.callback_fun)
if not ok then
log.error("failed to run the timer: ", timer.name, " err: ", err)
sleep(timer.sleep_fail)
elseif timer.sleep_succ > 0 then
sleep(timer.sleep_succ)
end
update_time()
until timer.each_ttl and now() >= timer.start_time + timer.each_ttl
end
local function run_timer(premature, self)
if self.running or premature then
return
end
self.running = true
local ok, err = pcall(_internal, self)
if not ok then
log.error("failed to run timer[", self.name, "] err: ", err)
end
self.running = false
end
function _M.new(name, callback_fun, opts)
if not name then
return nil, "missing argument: name"
end
if not callback_fun then
return nil, "missing argument: callback_fun"
end
opts = opts or {}
local timer = {
name = name,
each_ttl = opts.each_ttl or 1,
sleep_succ = opts.sleep_succ or 1,
sleep_fail = opts.sleep_fail or 5,
start_time = 0,
callback_fun = callback_fun,
running = false,
}
local hdl, err = timer_every(opts.check_interval or 1,
run_timer, timer)
if not hdl then
return nil, err
end
hdl, err = timer_at(0, run_timer, timer)
if not hdl then
return nil, err
end
return timer
end
return _M
|
local dict = require"socket.dict"
print(dict.get("dict://localhost/d:teste"))
for i,v in pairs(dict.get("dict://localhost/d:teste")) do print(v) end
|
-- notify.lua -- Desktop notifications for mpv.
-- Just put this file into your ~/.mpv/lua folder and mpv will find it.
--
-- Copyright (c) 2014 Roland Hieber
--
-- 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.
-------------------------------------------------------------------------------
-- helper functions
-------------------------------------------------------------------------------
function print_debug(s)
-- print("DEBUG: " .. s) -- comment out for no debug info
return true
end
--- Function equivalent to dirname in POSIX systems
--@param str the path string
function basename(str)
if str:match(".-/.-") then
local name = string.gsub(str, "(.*/)(.*)", "%2")
return name
else
return ''
end
end
--@param str the path string
function remove_extension(path)
local found, len, remainder = string.find(path, "^(.*)%.[^%.]*$")
if found then
return remainder
else
return path
end
end
-- -- url-escape a string, per RFC 2396, Section 2
-- function string.urlescape(str)
-- s, c = string.gsub(str, "([^A-Za-z0-9_.!~*'()/-])",
-- function(c)
-- return ("%%%02x"):format(c:byte())
-- end)
-- return s;
-- end
-- escape string for html
function string.htmlescape(str)
str = string.gsub(str, "<", "<")
str = string.gsub(str, ">", ">")
str = string.gsub(str, "&", "&")
str = string.gsub(str, "\"", """)
str = string.gsub(str, "'", "'")
return str
end
-- escape string for shell inclusion
function string.shellescape(str)
return "'"..string.gsub(str, "'", "'\"'\"'").."'"
end
-- -- converts string to a valid filename on most (modern) filesystems
-- function string.safe_filename(str)
-- s, c = string.gsub(str, "([^A-Za-z0-9_.-])",
-- function(c)
-- return ("%02x"):format(c:byte())
-- end)
-- return s;
-- end
-------------------------------------------------------------------------------
-- here we go.
-------------------------------------------------------------------------------
-- http = require("socket.http")
-- http.TIMEOUT = 3
-- http.USERAGENT = "mpv-notify/0.1"
--
-- local CACHE_DIR = os.getenv("XDG_CACHE_HOME")
-- CACHE_DIR = CACHE_DIR or os.getenv("HOME").."/.cache"
-- CACHE_DIR = CACHE_DIR.."/mpv/coverart"
-- print_debug("making " .. CACHE_DIR)
-- os.execute("mkdir -p -- " .. string.shellescape(CACHE_DIR))
--
-- function tmpname()
-- return "/tmp/mpv-coverart." .. math.random(0,0xffffff)
-- end
--
-- -- scale an image file
-- -- @return boolean of success
-- function scale_image(src, dst)
-- convert_cmd = ("convert -scale x64 -- %s %s"):format(
-- string.shellescape(src), string.shellescape(dst))
-- print_debug("executing " .. convert_cmd)
-- if os.execute(convert_cmd) then
-- return true
-- end
-- return false
-- end
--
-- -- look for a list of possible cover art images in the same folder as the file
-- -- @param absolute filename name of currently played file, or nil if no match
-- function get_folder_cover_art(filename)
-- if not filename or string.len(filename) < 1 then
-- return nil
-- end
--
-- print_debug("get_folder_cover_art: filename is " .. filename)
--
-- cover_extensions = { "png", "jpg", "jpeg", "gif" }
-- cover_names = { "cover", "folder", "front", "back", "insert" }
--
-- path = string.match(filename, "^(.*/)[^/]+$")
--
-- for k,name in pairs(cover_names) do
-- for k,ext in pairs(cover_extensions) do
-- morenames = { name, string.upper(name),
-- string.upper(string.sub(name, 1, 1)) .. string.sub(name, 2, -1) }
-- moreexts = { ext, string.upper(ext) }
-- for k,name in pairs(morenames) do
-- for k,ext in pairs(moreexts) do
-- fn = path .. name .. "." .. ext
-- print_debug("get_folder_cover_art: trying " .. fn)
-- f = io.open(fn, "r")
-- if f then
-- f:close()
-- print_debug("get_folder_cover_art: match at " .. fn)
-- return fn
-- end
-- end
-- end
-- end
-- end
-- return nil
-- end
--
-- -- fetch cover art from MusicBrainz/Cover Art Archive
-- -- @return file name of downloaded cover art, or nil in case of error
-- -- @param mbid optional MusicBrainz release ID
-- function fetch_musicbrainz_cover_art(artist, album, mbid)
-- print_debug("fetch_musicbrainz_cover_art parameters:")
-- print_debug("artist: " .. artist)
-- print_debug("album: " .. album)
-- print_debug("mbid: " .. mbid)
--
-- if not artist or artist == "" or not album or album == "" then
-- print("not enough metadata, not fetching cover art.")
-- return nil
-- end
--
-- output_filename = string.safe_filename(artist .. "_" .. album)
-- output_filename = (CACHE_DIR .. "/%s.png"):format(output_filename)
--
-- -- TODO: dirty hack, may only work on Linux.
-- f, err = io.open(output_filename, "r")
-- if f then
-- print_debug("file is already in cache: " .. output_filename)
-- return output_filename -- exists and is readable
-- elseif string.find(err, "[Pp]ermission denied") then
-- print(("cannot read from cached file %s: %s"):format(output_filename, err))
-- return nil
-- end
-- print_debug("fetching album art to " .. output_filename)
--
-- valid_mbid = function(s)
-- return s and string.len(s) > 0 and not string.find(s, "[^0-9a-fA-F-]")
-- end
--
-- -- fetch release MBID from MusicBrainz, needed for Cover Art Archive
-- if not valid_mbid(mbid) then
-- string.gsub(artist, '"', "")
-- query = ("%s AND artist:%s"):format(album, artist)
-- url = "http://musicbrainz.org/ws/2/release?limit=1&query="
-- .. string.urlescape(query)
-- print_debug("fetching " .. url)
-- d, c, h = http.request(url)
-- -- poor man's XML parsing:
-- mbid = string.match(d or "",
-- "<%s*release%s+[^>]*id%s*=%s*['\"]%s*([0-9a-fA-F-]+)%s*['\"]")
-- if not mbid or not valid_mbid(mbid) then
-- print("MusicBrainz returned no match.")
-- print_debug("content: " .. d)
-- return nil
-- end
-- end
-- print_debug("got MusicBrainz ID " .. mbid)
--
-- -- fetch image from Cover Art Archive
-- url = ("http://coverartarchive.org/release/%s/front-250"):format(mbid)
-- print_debug("fetching album cover from " .. url)
-- d, c, h = http.request(url)
-- if c ~= 200 then
-- print_debug(("Cover Art Archive returned HTTP %s for MBID %s"):format(c, mbid))
-- return nil
-- end
-- if not d or string.len(d) < 1 then
-- print_debug(("Cover Art Archive returned no content for MBID %s"):format(mbid))
-- print_debug("HTTP response: " .. d)
-- return nil
-- end
--
-- tmp_filename = tmpname()
-- f = io.open(tmp_filename, "w+")
-- f:write(d)
-- f:flush()
-- f:close()
--
-- -- make it a nice size
-- if scale_image(tmp_filename, output_filename) then
-- if not os.remove(tmp_filename) then
-- print("could not remove" .. tmp_filename .. ", please remove it manually")
-- end
-- return output_filename
-- end
--
-- print(("could not scale %s to %s"):format(tmp_filename, output_filename))
-- return nil
-- end
function notify_current_track()
data = mp.get_property_native("metadata")
function get_metadata(data, keys)
for k,v in pairs(keys) do
if data[v] and string.len(data[v]) > 0 then
return data[v]
end
end
return ""
end
-- srsly MPV, why do we have to do this? :-(
artist = get_metadata(data, {"artist", "ARTIST"})
album = get_metadata(data, {"album", "ALBUM"})
album_mbid = get_metadata(data, {"MusicBrainz Album Id",
"MUSICBRAINZ_ALBUMID"})
title = get_metadata(data, {"title", "TITLE"})
print_debug("notify_current_track: relevant metadata:")
print_debug("artist: " .. artist)
print_debug("album: " .. album)
print_debug("album_mbid: " .. album_mbid)
summary = ""
body = ""
params = ""
scaled_image = ""
delete_scaled_image = false
-- first try finding local cover art
abs_filename = os.getenv("PWD") .. "/" .. mp.get_property_native("path")
-- cover_image = get_folder_cover_art(abs_filename)
-- if cover_image and cover_image ~= "" then
-- scaled_image = tmpname()
-- scale_image(cover_image, scaled_image)
-- delete_scaled_image = true
-- end
-- -- then load cover art from the internet
-- if (not scaled_image or scaled_image == "")
-- and ((artist ~= "" and album ~= "") or album_mbid ~= "") then
-- scaled_image = fetch_musicbrainz_cover_art(artist, album, album_mbid)
-- cover_image = scaled_image
-- end
-- if scaled_image and string.len(scaled_image) > 1 then
-- print("found cover art in " .. cover_image)
-- params = " -i " .. string.shellescape(cover_image)
-- else
params = "-i /usr/share/icons/gnome/scalable/actions/media-playback-start-symbolic.svg"
-- end
if title == "" or title == "na" then
summary = string.shellescape(remove_extension(mp.get_property_native("filename")))
else
summary = string.shellescape(string.htmlescape(title))
end
if artist == "" or artist == "na" then
if album == "" or album == "na" then
body = string.shellescape(basename(os.getenv("PWD")))
else
body = string.shellescape("album: " .. string.htmlescape(album))
end
else
if album == "" or album == "na" then
body = string.shellescape("artist: " .. string.htmlescape(artist))
else
body = string.shellescape("artist : %s<br/><i>album: %s</i>"):format(
string.htmlescape(artist), string.htmlescape(album))
end
end
command = ("notify-send -a mpv %s %s %s"):format(summary, body, params)
print_debug("command: " .. command)
os.execute(command)
if delete_scaled_image and not os.remove(scaled_image) then
print("could not remove" .. scaled_image .. ", please remove it manually")
end
end
-- insert main() here
mp.register_event("file-loaded", notify_current_track)
|
-- 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")
--
-- One-liner description of a type.
Docstrings = class.class(KaitaiStruct)
function Docstrings:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function Docstrings:_read()
self.one = self._io:read_u1()
end
--
-- Another description for parse instance "two".
Docstrings.property.two = {}
function Docstrings.property.two:get()
if self._m_two ~= nil then
return self._m_two
end
local _pos = self._io:pos()
self._io:seek(0)
self._m_two = self._io:read_u1()
self._io:seek(_pos)
return self._m_two
end
--
-- And yet another one for value instance "three".
Docstrings.property.three = {}
function Docstrings.property.three:get()
if self._m_three ~= nil then
return self._m_three
end
self._m_three = 66
return self._m_three
end
--
-- A pretty verbose description for sequence attribute "one".
--
-- This subtype is never used, yet has a very long description
-- that spans multiple lines. It should be formatted accordingly,
-- even in languages that have single-line comments for
-- docstrings. Actually, there's even a MarkDown-style list here
-- with several bullets:
--
-- * one
-- * two
-- * three
--
-- And the text continues after that. Here's a MarkDown-style link:
-- [woohoo](http://example.com) - one day it will be supported as
-- well.
Docstrings.ComplexSubtype = class.class(KaitaiStruct)
function Docstrings.ComplexSubtype:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function Docstrings.ComplexSubtype:_read()
end
|
local Angle = require('neural.angle')
local GPS = require('gps')
local Mobs = require('neural.mobs')
local ni = require('neural.interface')
local Point = require('point')
local Util = require('util')
local os = _G.os
local RADIUS = 13
local ROTATION = math.pi / 16
local uid = ni.getID and ni.getID() or error('Introspection module is required')
local pos = { x = 0, y = 0, z = 0 }
local function findTargets()
local l = ni.sense()
table.sort(l, function(e1, e2)
return Point.distance(e1, pos) < Point.distance(e2, pos)
end)
local targets = { }
for _,v in ipairs(l) do
if v.id ~= uid and Mobs.getNames()[v.name] then
if math.abs(v.y) < 2 and Point.distance(v, pos) < 16 then -- pitch is broken
table.insert(targets, v)
end
end
end
return #targets > 0 and targets
end
local function shootAt(targets)
for _,target in ipairs(targets) do
target = ni.getMetaByID(target.id)
if target and target.isAlive and Point.distance(target, pos) < 14 then
ni.shootAt(target)
end
end
end
local potions = Util.filter(
ni.getEquipmentList(),
function(a)
return a.name == 'minecraft:splash_potion'
end)
local function heal(target)
local hands = { 'main', 'off' }
if #potions > 0 and ni.getMetaOwner().health < 10 then
local yaw, pitch = Angle.away(target.x - .5, 0, target.z - .5)
ni.look(yaw, pitch)
ni.use(.01, hands[potions[1].slot])
ni.launch(yaw, pitch, 1)
table.remove(potions, 1)
end
end
local pt = GPS.locate()
while true do
local targets = findTargets()
if not targets then
local cpt = GPS.locate()
if Point.distance(pt, cpt) > 2 then
print('walking to starting point')
local s, m = ni.goTo(pt.x, pt.y, pt.z)
Util.print({ s, m })
os.sleep(.05)
while ni.isWalking() do
os.sleep(0)
end
Util.print('done walking')
end
os.sleep(1)
else
local target = targets[1]
local angle = math.atan2(-target.x, -target.z) + ROTATION
ni.launchTo({
x = target.x + RADIUS * math.sin(angle),
y = 0,
z = target.z + RADIUS * math.cos(angle)
}, 1)
os.sleep(.2)
shootAt(targets)
heal(target)
if math.random(1, 3) == 3 then
ROTATION = -ROTATION
end
end
end
|
--[[
Event Handler
Creates and passes events to objects that have registred.
]]
local lib
local table_copy
local event_handler
local event_prop_meta
local handler_compare = function(first, second)
return first[3] < second[3]
end
event_handler = {
auto_hook = {},
event = {},
events = {},
event_create = function(self, event_names)
if (type(event_names) == "table") then
for key, event_name in pairs(event_names) do
if (not self.events[event_name]) then
self.events[event_name] = {data = self.event_data:new()}
self:event_handler_make(event_name)
end
end
else
if (not self.events[event_names]) then
self.events[event_names] = {data = self.event_data:new()}
self:event_handler_make(event_names)
end
end
end,
event_handler_make = function(self, event_name)
if (rawget(self.event, event_name)) then
return rawget(self.event, event_name)
else
local handler = function(this, ...)
self:event_fire(event_name, ...)
end
self.event[event_name] = handler
return handler
end
end,
event_hook_object = function(self, object, event_names)
if (type(event_names) == "table") then
for key, event_name in next, event_names do
self:event_hook_object(event_name, object)
end
elseif (event_names) then
local event = self.events[event_names]
local object_events = object.event
if (event and object_events) then
local method = object_events[event_names]
if (method) then
local priority = object_events[event_names .. "_priority"]
event[#event + 1] = {object, method, priority or 0}
end
end
else
local object_events = object.event
local hooked = {}
if (object_events) then
for event_name, method in next, object_events do
if (type(method) == "function" or type(method) == "table") then
local event = self.events[event_name]
if (event) then
hooked[event_name] = true
local priority = object_events[event_name .. "_priority"]
event[#event + 1] = {object, method, priority or 0}
end
end
end
end
for event_name, enabled in pairs(self.auto_hook) do
local event = self.events[event_name]
local method = object[event_name]
if (event and method and (not hooked[event_name])) then
local priority = object[event_name .. "_priority"]
event[#event + 1] = {object, method, priority or 0}
end
end
end
end,
event_hook_light = function(self, object, event_names, method, priority)
if (type(event_names) == "table") then
for key, event_name in next, event_names do
self:event_hook_light(event_name, object, method, priority)
end
else
local event = self.events[event_names]
if (event) then
event[#event + 1] = {object or {}, method, priority or 0}
end
end
end,
event_unhook_by_object = function(self, event_name, object)
local event = self.events[event_name]
if (event) then
for key = 1, #event do
local entry = event[key]
if (entry[1] == object) then
table.remove(event, key)
end
end
end
end,
event_unhook_by_method = function(self, event_name, method)
local event = self.events[event_name]
if (event) then
for key = 1, #event do
local entry = event[key]
if (entry[2] == method) then
table.remove(event, key)
end
end
end
end,
event_sort = function(self, event_names)
if (type(event_names) == "table") then
for key, event_name in pairs(event_names) do
local event = self.events[event_name]
if (event) then
table.sort(event, handler_compare)
end
end
elseif (event_names) then
local event = self.events[event_names]
if (event) then
table.sort(event, handler_compare)
end
else
for event_name, event in next, self.events do
table.sort(event, handler_compare)
end
end
end,
event_fire = function(self, event_name, data)
local event = self.events[event_name]
if (event) then
local event_data = event.data
event_data:update(data)
event_data:add(self)
local flags = event_data.flags
for key = 1, #event do
local handler = event[key]
handler[2](handler[1], event_data)
if (flags.event_unhook) then
event[key] = nil
flags.event_unhook = false
end
if (flags.event_cancel) then
break
end
end
return event_data
else
print("WARNING: Attempt to call event '" .. tostring(event_name) .. "' (an undefined event)")
end
end,
_new = function(base, new)
for key, flag in pairs(new.auto_hook) do
new:event_create(key)
end
return new
end,
event_data = {
stack = {},
flags = {},
update = function(self, data)
for key, value in pairs(self) do
if (type(value) == "table") then
self[key] = {}
elseif (type(value) ~= "function") then
self[key] = nil
end
end
if (data) then
for key, value in pairs(data) do
if (type(value) == "table") then
self[key] = table_copy(value)
else
self[key] = value
end
end
end
end,
reset = function(self)
self.stack = {}
self.flags = {}
end,
add = function(self, item)
self.stack[#self.stack + 1] = item
end,
parent = function(self)
return self.stack[#self.stack]
end
},
init = function(self, engine)
lib = engine.lib
table_copy = lib.utility.table_copy
lib.oop:objectify(self)
lib.oop:objectify(self.event_data)
engine.event = self:new()
end
}
return event_handler |
local staticRuntime = ...
return {
include = function()
includedirs "../vendor/minhook/include/"
end,
run = function()
language "C"
kind "StaticLib"
if staticRuntime then
staticruntime "On"
end
local minhook_dir = "../vendor/minhook/src/"
files_project(minhook_dir) {
"buffer.c",
"hook.c",
"trampoline.c",
}
filter { 'architecture:x86' }
files_project(minhook_dir) {
"HDE/hde32.c"
}
filter { 'architecture:x64' }
files_project(minhook_dir) {
"HDE/hde64.c"
}
end
}
|
require("settings")
require("keymapps")
require("plugins")
require("lsp-config")
|
-- This test file expects to be ran from 'run.lua' in the root Penlight directory.
local dir = require( "pl.dir" )
local file = require( "pl.file" )
local path = require( "pl.path" )
local asserteq = require( "pl.test" ).asserteq
asserteq(dir.fnmatch("foobar", "foo*bar"), true)
asserteq(dir.fnmatch("afoobar", "foo*bar"), false)
asserteq(dir.fnmatch("foobars", "foo*bar"), false)
asserteq(dir.fnmatch("foonbar", "foo*bar"), true)
asserteq(dir.fnmatch("foo'n'bar", "foo*bar"), true)
asserteq(dir.fnmatch("foonbar", "foo?bar"), true)
asserteq(dir.fnmatch("foo'n'bar", "foo?bar"), false)
asserteq(dir.fnmatch("foo", "FOO"), path.is_windows)
asserteq(dir.fnmatch("FOO", "foo"), path.is_windows)
local filtered = dir.filter({"foobar", "afoobar", "foobars", "foonbar"}, "foo*bar")
asserteq(filtered, {"foobar", "foonbar"})
local normpath = path.normpath
local doc_files = dir.getfiles(normpath "doc/", "*.ld")
asserteq(doc_files, {normpath "doc/config.ld"})
local all_doc_files = dir.getallfiles(normpath "doc/", "*.ld")
asserteq(all_doc_files, {normpath "doc/config.ld"})
local test_samples = dir.getallfiles(normpath "tests/lua")
table.sort(test_samples)
asserteq(test_samples, {
normpath "tests/lua/animal.lua",
normpath "tests/lua/bar.lua",
normpath "tests/lua/foo/args.lua",
normpath "tests/lua/mod52.lua",
normpath "tests/lua/mymod.lua"
})
-- Test move files -----------------------------------------
-- Create a dummy file
local fileName = path.tmpname()
file.write( fileName, string.rep( "poot ", 1000 ) )
local newFileName = path.tmpname()
local err, msg = dir.movefile( fileName, newFileName )
-- Make sure the move is successful
assert( err, msg )
-- Check to make sure the original file is gone
asserteq( path.exists( fileName ), false )
-- Check to make sure the new file is there
asserteq( path.exists( newFileName ) , newFileName )
-- Try to move the original file again (which should fail)
local newFileName2 = path.tmpname()
local err, msg = dir.movefile( fileName, newFileName2 )
asserteq( err, false )
-- Clean up
file.delete( newFileName )
-- Test copy files -----------------------------------------
-- Create a dummy file
local fileName = path.tmpname()
file.write( fileName, string.rep( "poot ", 1000 ) )
local newFileName = path.tmpname()
local err, msg = dir.copyfile( fileName, newFileName )
-- Make sure the move is successful
assert( err, msg )
-- Check to make sure the new file is there
asserteq( path.exists( newFileName ) , newFileName )
-- Try to move a non-existant file (which should fail)
local fileName2 = 'blub'
local newFileName2 = 'snortsh'
local err, msg = dir.copyfile( fileName2, newFileName2 )
asserteq( err, false )
-- Clean up the files
file.delete( fileName )
file.delete( newFileName )
-- have NO idea why forcing the return code is necessary here (Windows 7 64-bit)
--os.exit(0)
|
local resourcesPrefix = ARGV[1]
local collectionsPrefix = ARGV[2]
local deltaResourcesPrefix = ARGV[3]
local deltaEtagsPrefix = ARGV[4]
local expirableSet = ARGV[5]
local minscore = tonumber(ARGV[6])
local maxscore = tonumber(ARGV[7])
local confirmCollectionDelete = ARGV[8]
local deleteRecursive = ARGV[9]
local now = tonumber(ARGV[10])
local bulksize = tonumber(ARGV[11])
-- Important: The ARGV-Array is used again in the included del.lua script
-- (see this funny comment with the percent sign below and Java-Method
-- org.swisspush.reststorage.RedisStorage.LuaScriptState.composeLuaScript)
-- we need to initialize all parameters for del.lua here - otherwise we can have side effects
ARGV[10] = ''
ARGV[11] = ''
ARGV[12] = ''
ARGV[13] = ''
local resourcePrefixLength = string.len(resourcesPrefix)
local counter = 0
local KEYS = {}
local resourcesToClean = redis.call('zrangebyscore',expirableSet,minscore,now,'limit',0,bulksize)
for key,value in pairs(resourcesToClean) do
redis.log(redis.LOG_NOTICE, "cleanup resource: "..value)
KEYS[1] = string.sub(value, resourcePrefixLength+1, string.len(value))
--%(delscript)
counter = counter + 1
end
return counter |
print("HR Events")
local isBNW = (GameInfoTypes.UNITCOMBAT_SUBMARINE ~= nil);
local isEEraExt = (GameInfoTypes.UNIT_EE_CUIRASSIER ~= nil);
function JFD_IsUsingPietyPrestige()
local pietyPrestigeModID = "eea66053-7579-481a-bb8d-2f3959b59974"
local isUsingPiety = false
for _, mod in pairs(Modding.GetActivatedMods()) do
if (mod.ID == pietyPrestigeModID) then
isUsingPiety = true
break
end
end
return isUsingPiety
end
function GetHumanPlayer()
local hPlayer = 0;
for oPlayer=0, GameDefines.MAX_MAJOR_CIVS-1 do
local oPlayer = Players[oPlayer];
if (oPlayer:IsAlive()) and (oPlayer:IsHuman()) then
hPlayer = oPlayer;
break
end
end
return hPlayer;
end
function GetRandomHR(lower, upper)
return (Game.Rand((upper + 1) - lower, "")) + lower
end
local rCatholic = GameInfoTypes.RELIGION_CHRISTIANITY;
local rOrthodox = GameInfoTypes.RELIGION_ORTHODOXY;
local rIslam1 = GameInfoTypes.RELIGION_ISLAM;
local rIslam2 = GameInfoTypes.RELIGION_ISLAM_SHIA;
local rIslam3 = GameInfoTypes.RELIGION_ISLAM_IBADI;
local rIslam4 = GameInfoTypes.RELIGION_MUTAZILA;
local rIslam5 = GameInfoTypes.RELIGION_DRUZE;
local rIslam6 = GameInfoTypes.RELIGION_AHMADI;
local rJudaism = GameInfoTypes.RELIGION_JUDAISM;
local rGreek1 = GameInfoTypes.RELIGION_HELLENISM;
local rGreek2 = GameInfoTypes.RELIGION_NUMENISM;
local rGreek3 = GameInfoTypes.RELIGION_IMPERIAL_CULT;
local rGreek4 = GameInfoTypes.RELIGION_HEROS_KARABAZMOS;
local rGreek5 = GameInfoTypes.RELIGION_ATANODJUWAJA;
local rTao = GameInfoTypes.RELIGION_TAOISM;
local rWestAfrica1 = GameInfoTypes.RELIGION_ITAN;
local rWestAfrica2 = GameInfoTypes.RELIGION_ODINANI;
local rWestAfrica3 = GameInfoTypes.RELIGION_VODUN;
local rNorse = GameInfoTypes.RELIGION_FORN_SIDR;
local rHindu1 = GameInfoTypes.RELIGION_HINDUISM;
local rHindu2 = GameInfoTypes.RELIGION_SHAKTI;
local rHindu3 = GameInfoTypes.RELIGION_SHIVA;
local rHindu4 = GameInfoTypes.RELIGION_VISHNU;
local rHindu5 = GameInfoTypes.RELIGION_JAIN;
local rHindu6 = GameInfoTypes.RELIGION_VAJRAYANA;
local rNative1 = GameInfoTypes.RELIGION_WAKAN_TANKA;
local rNative2 = GameInfoTypes.RELIGION_POHAKANTENNA;
local rNative3 = GameInfoTypes.RELIGION_ORENDA;
local rNative4 = GameInfoTypes.RELIGION_SOUTHERN_CULT;
local rNative5 = GameInfoTypes.RELIGION_KACHINA;
local rAfrica1 = GameInfoTypes.RELIGION_AMATONGO;
local rAfrica2 = GameInfoTypes.RELIGION_LAIBONI;
local rAfrica3 = GameInfoTypes.RELIGION_NZAMBIISM;
local rAfrica4 = GameInfoTypes.RELIGION_BUMUNTU;
local rAfrica5 = GameInfoTypes.RELIGION_MWARI;
local rConfucian = GameInfoTypes.RELIGION_CONFUCIANISM;
local rProtestant1 = GameInfoTypes.RELIGION_PROTESTANTISM;
local rProtestant2 = GameInfoTypes.RELIGION_PROTESTANT_CALVINISM;
local rProtestant3 = GameInfoTypes.RELIGION_PROTESTANT_METHODISM;
local rProtestant4 = GameInfoTypes.RELIGION_PROTESTANT_BAPTIST;
local rProtestant5 = GameInfoTypes.RELIGION_CHRISTIAN_ANGLICANISM;
local bHREsoteric = GameInfoTypes.BUILDING_HR_ESOTERIC_DUMMY;
local pHREsoteric = GameInfoTypes.POLICY_HR_ESOTERIC_DUMMY;
local pHRSpiritualist = GameInfoTypes.POLICY_HR_SPIRITUALIST_DUMMY;
local eAncient = GameInfoTypes.ERA_ANCIENT;
local eClassic = GameInfoTypes.ERA_CLASSICAL;
local eIndustrial = GameInfoTypes.ERA_INDUSTRIAL;
local eModern = GameInfoTypes.ERA_MODERN;
local eInformation = GameInfoTypes.ERA_FUTURE;
--=========================================================
--Esotericism
--=========================================================
local Event_TomatekhHREsotericism = {}
Event_TomatekhHREsotericism.Name = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM"
Event_TomatekhHREsotericism.Desc = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_DESC"
Event_TomatekhHREsotericism.EventImage = "HREsoteric.dds"
Event_TomatekhHREsotericism.Weight = 1
Event_TomatekhHREsotericism.CanFunc = (
function(pPlayer)
if load(pPlayer, "Event_TomatekhHREsotericism") == true then return false end
if load(pPlayer, "Event_TomatekhHRAtheism") == true then return false end
local religionID = pPlayer:GetReligionCreatedByPlayer()
if religionID <= 0 then
if (pPlayer:GetNumCities() >= 1) then
religionID = pPlayer:GetCapitalCity():GetReligiousMajority()
end
end
if isUsingPietyPrestige then
religionID = JFD_GetStateReligion(pPlayer:GetID())
end
if religionID <= 0 then return false end
if not isBNW then return false end
if (GetNumReligionsinEmpire(pPlayer) < 2) then return false end
local pTeam = pPlayer:GetTeam();
if (Teams[pTeam]:GetCurrentEra() == eAncient) then return false end
if (Teams[pTeam]:GetCurrentEra() == eClassic) then return false end
if (Teams[pTeam]:GetCurrentEra() == eIndustrial) then return false end
if (Teams[pTeam]:GetCurrentEra() == eInformation) then return false end
Event_TomatekhHREsotericism.Name = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM"
Event_TomatekhHREsotericism.EventImage = "HREsoteric.dds"
if (Teams[pTeam]:GetCurrentEra() <= eIndustrial) then
if (religionID == rCatholic) then
Event_TomatekhHREsotericism.Name = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_CHRISTIAN"
Event_TomatekhHREsotericism.EventImage = "HREsotericChristian.dds"
end
if (religionID == rOrthodox) then
Event_TomatekhHREsotericism.Name = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_EASTERN"
Event_TomatekhHREsotericism.EventImage = "HREsotericOrthodox.dds"
end
if (religionID == rIslam1) or (religionID == rIslam2) or (religionID == rIslam3) or (religionID == rIslam4) or (religionID == rIslam5) or (religionID == rIslam6) then
Event_TomatekhHREsotericism.Name = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_ISLAM"
Event_TomatekhHREsotericism.EventImage = "HREsotericIslam.dds"
end
if (religionID == rJudaism) then
Event_TomatekhHREsotericism.Name = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_JUDAISM"
Event_TomatekhHREsotericism.EventImage = "HREsotericJudaism.dds"
end
if (religionID == rGreek1) or (religionID == rGreek2) or (religionID == rGreek3) or (religionID == rGreek4) or (religionID == rGreek5) then
Event_TomatekhHREsotericism.Name = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_GREEK"
Event_TomatekhHREsotericism.EventImage = "HREsotericGreek.dds"
end
if (religionID == rTao) then
Event_TomatekhHREsotericism.Name = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_TAOISM"
Event_TomatekhHREsotericism.EventImage = "HREsotericTao.dds"
end
if (religionID == rWestAfrica1) or (religionID == rWestAfrica2) or (religionID == rWestAfrica3) then
Event_TomatekhHREsotericism.Name = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_ITAN"
Event_TomatekhHREsotericism.EventImage = "HREsotericIfa.dds"
end
if (religionID == rNorse) then
Event_TomatekhHREsotericism.Name = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_NORSE"
Event_TomatekhHREsotericism.EventImage = "HREsotericNorse.dds"
end
if (religionID == rHindu1) or (religionID == rHindu2) or (religionID == rHindu3) or (religionID == rHindu4) or (religionID == rHindu5) or (religionID == rHindu6) then
Event_TomatekhHREsotericism.Name = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_HINDU"
Event_TomatekhHREsotericism.EventImage = "HREsotericYoga.dds"
end
if (religionID == rNative1) or (religionID == rNative2) or (religionID == rNative3) or (religionID == rNative4) or (religionID == rNative5) then
Event_TomatekhHREsotericism.Name = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_SIOUX"
Event_TomatekhHREsotericism.EventImage = "HREsotericIndian.dds"
end
if (religionID == rAfrica1) or (religionID == rAfrica2) or (religionID == rAfrica3) or (religionID == rAfrica4) or (religionID == rAfrica5) then
Event_TomatekhHREsotericism.Name = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_AFRICA"
Event_TomatekhHREsotericism.EventImage = "HREsotericMuti.dds"
end
if (religionID == rConfucian) then
Event_TomatekhHREsotericism.Name = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_CONFUCIAN"
Event_TomatekhHREsotericism.EventImage = "HREsotericConfuci.dds"
end
if (religionID == rProtestant1) or (religionID == rProtestant2) or (religionID == rProtestant3) or (religionID == rProtestant4) or (religionID == rProtestant5) then
Event_TomatekhHREsotericism.Name = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_PROTESTANT"
Event_TomatekhHREsotericism.EventImage = "HREsotericProtest.dds"
end
elseif (Teams[pTeam]:GetCurrentEra() > eIndustrial) then
Event_TomatekhHREsotericism.Name = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_NEW_AGE"
Event_TomatekhHREsotericism.EventImage = "HREsotericNewAge.dds"
end
Event_TomatekhHREsotericism.Desc = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_DESC"
if (Teams[pTeam]:GetCurrentEra() <= eIndustrial) then
if (religionID == rProtestant1) or (religionID == rProtestant2) or (religionID == rProtestant3) or (religionID == rProtestant4) or (religionID == rProtestant5) then
Event_TomatekhHREsotericism.Desc = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_PROTESTANT_DESC"
end
elseif (Teams[pTeam]:GetCurrentEra() > eIndustrial) then
Event_TomatekhHREsotericism.Desc = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_NEW_AGE_DESC"
end
return true
end
)
Event_TomatekhHREsotericism.Outcomes = {}
-- Outcome 1
Event_TomatekhHREsotericism.Outcomes[1] = {}
Event_TomatekhHREsotericism.Outcomes[1].Name = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_OUTCOME_1"
Event_TomatekhHREsotericism.Outcomes[1].Desc = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_OUTCOME_1_DESC"
Event_TomatekhHREsotericism.Outcomes[1].Weight = 1
Event_TomatekhHREsotericism.Outcomes[1].CanFunc = (
function(pPlayer)
local religionID = pPlayer:GetReligionCreatedByPlayer()
if religionID <= 0 then
if (pPlayer:GetNumCities() >= 1) then
religionID = pPlayer:GetCapitalCity():GetReligiousMajority()
end
end
if isUsingPietyPrestige then
religionID = JFD_GetStateReligion(pPlayer:GetID())
end
local pTeam = pPlayer:GetTeam();
if (Teams[pTeam]:GetCurrentEra() <= eIndustrial) then
if (religionID == rProtestant1) or (religionID == rProtestant2) or (religionID == rProtestant3) or (religionID == rProtestant4) or (religionID == rProtestant5) then
Event_TomatekhHREsotericism.Outcomes[1].Name = Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_PROTESTANT_OUTCOME_1")
else
Event_TomatekhHREsotericism.Outcomes[1].Name = Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_OUTCOME_1")
end
elseif (Teams[pTeam]:GetCurrentEra() > eIndustrial) then
Event_TomatekhHREsotericism.Outcomes[1].Name = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_NEW_AGE_OUTCOME_1"
end
Event_TomatekhHREsotericism.Outcomes[1].Desc = Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_OUTCOME_1_DESC")
return true
end
)
Event_TomatekhHREsotericism.Outcomes[1].DoFunc = (
function(pPlayer)
local religionID = pPlayer:GetReligionCreatedByPlayer()
if religionID <= 0 then
if (pPlayer:GetNumCities() >= 1) then
religionID = pPlayer:GetCapitalCity():GetReligiousMajority()
end
end
if isUsingPietyPrestige then
religionID = JFD_GetStateReligion(pPlayer:GetID())
end
save(pPlayer, "Event_TomatekhHREsotericism", true)
save(pPlayer, "Event_TomatekhHREsotericism_One", true)
local pTeam = pPlayer:GetTeam();
if (Teams[pTeam]:GetCurrentEra() <= eIndustrial) then
if (religionID == rProtestant1) or (religionID == rProtestant2) or (religionID == rProtestant3) or (religionID == rProtestant4) or (religionID == rProtestant5) then
JFD_SendNotification(pPlayer:GetID(), "NOTIFICATION_GENERIC", Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_PROTESTANT_OUTCOME_NOTIFICATION"), Locale.ConvertTextKey(Event_TomatekhHREsotericism.Name))
local hPlayer = GetHumanPlayer();
if hPlayer ~= 0 then
if hPlayer ~= pPlayer then
local pTeam = pPlayer:GetTeam();
local hTeam = hPlayer:GetTeam();
if Teams[pTeam]:IsHasMet(hTeam) then
Events.GameplayAlertMessage("A religious renewal movement has spread through " .. Locale.ConvertTextKey(pPlayer:GetCivilizationShortDescription()) .. "!")
end
end
end
else
JFD_SendNotification(pPlayer:GetID(), "NOTIFICATION_GENERIC", Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_OUTCOME_NOTIFICATION"), Locale.ConvertTextKey(Event_TomatekhHREsotericism.Name))
local hPlayer = GetHumanPlayer();
if hPlayer ~= 0 then
if hPlayer ~= pPlayer then
local pTeam = pPlayer:GetTeam();
local hTeam = hPlayer:GetTeam();
if Teams[pTeam]:IsHasMet(hTeam) then
Events.GameplayAlertMessage("" .. Locale.ConvertTextKey(pPlayer:GetCivilizationShortDescription()) .. " has developed a new mystic tradition.")
end
end
end
end
elseif (Teams[pTeam]:GetCurrentEra() > eIndustrial) then
JFD_SendNotification(pPlayer:GetID(), "NOTIFICATION_GENERIC", Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_NEW_AGE_OUTCOME_NOTIFICATION"), Locale.ConvertTextKey(Event_TomatekhHREsotericism.Name))
local hPlayer = GetHumanPlayer();
if hPlayer ~= 0 then
if hPlayer ~= pPlayer then
local pTeam = pPlayer:GetTeam();
local hTeam = hPlayer:GetTeam();
if Teams[pTeam]:IsHasMet(hTeam) then
Events.GameplayAlertMessage("A New Age religious movement has started in " .. Locale.ConvertTextKey(pPlayer:GetCivilizationShortDescription()) .. ".")
end
end
end
end
for pCity in pPlayer:Cities() do
if not (pCity:IsHasBuilding(bHREsoteric)) then
pCity:SetNumRealBuilding(bHREsoteric, 1);
end
end
end
)
-- Outcome 2
Event_TomatekhHREsotericism.Outcomes[2] = {}
Event_TomatekhHREsotericism.Outcomes[2].Name = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_OUTCOME_2"
Event_TomatekhHREsotericism.Outcomes[2].Desc = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_OUTCOME_2_DESC"
Event_TomatekhHREsotericism.Outcomes[2].Weight = 10
Event_TomatekhHREsotericism.Outcomes[2].CanFunc = (
function(pPlayer)
local religionID = pPlayer:GetReligionCreatedByPlayer()
if religionID <= 0 then
if (pPlayer:GetNumCities() >= 1) then
religionID = pPlayer:GetCapitalCity():GetReligiousMajority()
end
end
if isUsingPietyPrestige then
religionID = JFD_GetStateReligion(pPlayer:GetID())
end
local pTeam = pPlayer:GetTeam();
if (Teams[pTeam]:GetCurrentEra() <= eIndustrial) then
if (religionID == rProtestant1) or (religionID == rProtestant2) or (religionID == rProtestant3) or (religionID == rProtestant4) or (religionID == rProtestant5) then
Event_TomatekhHREsotericism.Outcomes[2].Name = Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_PROTESTANT_OUTCOME_2")
else
Event_TomatekhHREsotericism.Outcomes[2].Name = Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_OUTCOME_2")
end
elseif (Teams[pTeam]:GetCurrentEra() > eIndustrial) then
Event_TomatekhHREsotericism.Outcomes[2].Name = "TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_NEW_AGE_OUTCOME_2"
end
Event_TomatekhHREsotericism.Outcomes[2].Desc = Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_OUTCOME_2_DESC")
return true
end
)
Event_TomatekhHREsotericism.Outcomes[2].DoFunc = (
function(pPlayer)
local religionID = pPlayer:GetReligionCreatedByPlayer()
if religionID <= 0 then
if (pPlayer:GetNumCities() >= 1) then
religionID = pPlayer:GetCapitalCity():GetReligiousMajority()
end
end
if isUsingPietyPrestige then
religionID = JFD_GetStateReligion(pPlayer:GetID())
end
save(pPlayer, "Event_TomatekhHREsotericism", true)
local pTeam = pPlayer:GetTeam();
if (Teams[pTeam]:GetCurrentEra() <= eIndustrial) then
if (religionID == rProtestant1) or (religionID == rProtestant2) or (religionID == rProtestant3) or (religionID == rProtestant4) or (religionID == rProtestant5) then
JFD_SendNotification(pPlayer:GetID(), "NOTIFICATION_GENERIC", Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_PROTESTANT_OUTCOME_NOTIFICATION"), Locale.ConvertTextKey(Event_TomatekhHREsotericism.Name))
local hPlayer = GetHumanPlayer();
if hPlayer ~= pPlayer then
local pTeam = pPlayer:GetTeam();
local hTeam = hPlayer:GetTeam();
if Teams[pTeam]:IsHasMet(hTeam) then
Events.GameplayAlertMessage("A religious renewal movement has spread through " .. Locale.ConvertTextKey(pPlayer:GetCivilizationShortDescription()) .. ".")
end
end
else
JFD_SendNotification(pPlayer:GetID(), "NOTIFICATION_GENERIC", Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_OUTCOME_NOTIFICATION"), Locale.ConvertTextKey(Event_TomatekhHREsotericism.Name))
local hPlayer = GetHumanPlayer();
if hPlayer ~= pPlayer then
local pTeam = pPlayer:GetTeam();
local hTeam = hPlayer:GetTeam();
if Teams[pTeam]:IsHasMet(hTeam) then
Events.GameplayAlertMessage("" .. Locale.ConvertTextKey(pPlayer:GetCivilizationShortDescription()) .. " has developed a new mystic tradition!")
end
end
end
elseif (Teams[pTeam]:GetCurrentEra() > eIndustrial) then
JFD_SendNotification(pPlayer:GetID(), "NOTIFICATION_GENERIC", Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_ESOTERICISM_NEW_AGE_OUTCOME_NOTIFICATION"), Locale.ConvertTextKey(Event_TomatekhHREsotericism.Name))
local hPlayer = GetHumanPlayer();
if hPlayer ~= 0 then
if hPlayer ~= pPlayer then
local pTeam = pPlayer:GetTeam();
local hTeam = hPlayer:GetTeam();
if Teams[pTeam]:IsHasMet(hTeam) then
Events.GameplayAlertMessage("A New Age religious movement has started in " .. Locale.ConvertTextKey(pPlayer:GetCivilizationShortDescription()) .. ".")
end
end
end
end
if not pPlayer:HasPolicy(pHREsoteric) then
pPlayer:SetNumFreePolicies(1)
pPlayer:SetNumFreePolicies(0)
pPlayer:SetHasPolicy(pHREsoteric, true);
end
end
)
tEvents.Event_TomatekhHREsotericism = Event_TomatekhHREsotericism
GameEvents.PlayerDoTurn.Add(
function(iPlayer)
local pPlayer = Players[iPlayer];
if (pPlayer:IsAlive()) then
if load(pPlayer, "Event_TomatekhHREsotericism_One") == true then
local EsotericFaith = 0;
for pCity in pPlayer:Cities() do
if not (pCity:IsHasBuilding(bHREsoteric)) then
pCity:SetNumRealBuilding(bHREsoteric, 1);
end
local fPop = pCity:GetPopulation();
if fPop >= 5 then
local bFaith = math.floor(fPop / 5)
EsotericFaith = EsotericFaith + bFaith;
end
end
--Building_YieldChangesPerPop doesn't work with faith?
pPlayer:ChangeFaith(EsotericFaith);
end
end
end)
--=========================================================
--Spiritualism
--=========================================================
local Event_TomatekhHRSpiritualism = {}
Event_TomatekhHRSpiritualism.Name = "TXT_KEY_EVENT_TOMATEKH_HR_SPIRITUALISM"
Event_TomatekhHRSpiritualism.Desc = "TXT_KEY_EVENT_TOMATEKH_HR_SPIRITUALISM_DESC"
Event_TomatekhHRSpiritualism.EventImage = "HRSpiritualism.dds"
Event_TomatekhHRSpiritualism.Weight = 2
Event_TomatekhHRSpiritualism.CanFunc = (
function(pPlayer)
if load(pPlayer, "Event_TomatekhHRSpiritualism") == true then return false end
if load(pPlayer, "Event_TomatekhHRAtheism") == true then return false end
local religionID = pPlayer:GetReligionCreatedByPlayer()
if religionID <= 0 then
if (pPlayer:GetNumCities() >= 1) then
religionID = pPlayer:GetCapitalCity():GetReligiousMajority()
end
end
if isUsingPietyPrestige then
religionID = JFD_GetStateReligion(pPlayer:GetID())
end
if religionID <= 0 then return false end
if (GetNumReligionsinEmpire(pPlayer) < 2) then return false end
if not isBNW then return false end
local pTeam = pPlayer:GetTeam();
if not (Teams[pTeam]:GetCurrentEra() == eIndustrial) then return false end
Event_TomatekhHRSpiritualism.Name = "TXT_KEY_EVENT_TOMATEKH_HR_SPIRITUALISM"
return true
end
)
Event_TomatekhHRSpiritualism.Outcomes = {}
-- Outcome 1
Event_TomatekhHRSpiritualism.Outcomes[1] = {}
Event_TomatekhHRSpiritualism.Outcomes[1].Name = "TXT_KEY_EVENT_TOMATEKH_HR_SPIRITUALISM_OUTCOME_1"
Event_TomatekhHRSpiritualism.Outcomes[1].Desc = "TXT_KEY_EVENT_TOMATEKH_HR_SPIRITUALISM_OUTCOME_1_DESC"
Event_TomatekhHRSpiritualism.Outcomes[1].Weight = 10
Event_TomatekhHRSpiritualism.Outcomes[1].CanFunc = (
function(pPlayer)
Event_TomatekhHRSpiritualism.Outcomes[1].Desc = Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_SPIRITUALISM_OUTCOME_1_DESC")
return true
end
)
Event_TomatekhHRSpiritualism.Outcomes[1].DoFunc = (
function(pPlayer)
save(pPlayer, "Event_TomatekhHRSpiritualism", true)
if not pPlayer:HasPolicy(pHRSpiritualist) then
pPlayer:SetNumFreePolicies(1)
pPlayer:SetNumFreePolicies(0)
pPlayer:SetHasPolicy(pHRSpiritualist, true);
end
JFD_SendNotification(pPlayer:GetID(), "NOTIFICATION_GENERIC", Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_SPIRITUALISM_OUTCOME_1_NOTIFICATION"), Locale.ConvertTextKey(Event_TomatekhHRSpiritualism.Name))
local hPlayer = GetHumanPlayer();
if hPlayer ~= 0 then
if hPlayer ~= pPlayer then
local pTeam = pPlayer:GetTeam();
local hTeam = hPlayer:GetTeam();
if Teams[pTeam]:IsHasMet(hTeam) then
Events.GameplayAlertMessage("The " .. Locale.ConvertTextKey(pPlayer:GetCivilizationAdjective()) .. " are attempting to contact the spirit world!")
end
end
end
end
)
tEvents.Event_TomatekhHRSpiritualism = Event_TomatekhHRSpiritualism
--=========================================================
--Rosicrucian Enlightenment
--=========================================================
local Event_TomatekhHRRosyCross = {}
Event_TomatekhHRRosyCross.Name = "TXT_KEY_EVENT_TOMATEKH_HR_ROSY_CROSS"
Event_TomatekhHRRosyCross.Desc = "TXT_KEY_EVENT_TOMATEKH_HR_ROSY_CROSS_DESC"
Event_TomatekhHRRosyCross.EventImage = "HRRosyCross.dds"
Event_TomatekhHRRosyCross.Weight = 1
Event_TomatekhHRRosyCross.CanFunc = (
function(pPlayer)
if load(pPlayer, "Event_TomatekhHRRosyCross") == true then return false end
if load(pPlayer, "Event_TomatekhHRAtheism") == true then return false end
local religionID = pPlayer:GetReligionCreatedByPlayer()
if religionID <= 0 then
if (pPlayer:GetNumCities() >= 1) then
religionID = pPlayer:GetCapitalCity():GetReligiousMajority()
end
end
if isUsingPietyPrestige then
religionID = JFD_GetStateReligion(pPlayer:GetID())
end
if religionID <= 0 then return false end
if (GetNumReligionsinEmpire(pPlayer) < 2) then return false end
if not isBNW then return false end
local eRenID = GameInfoTypes.ERA_RENAISSANCE;
local eIndID = GameInfoTypes.ERA_INDUSTRIAL;
if isEEraExt then
eIndID = GameInfoTypes.ERA_ENLIGHTENMENT;
end
local pTeam = pPlayer:GetTeam();
if (Teams[pTeam]:GetCurrentEra() < eRenID) or (Teams[pTeam]:GetCurrentEra() > eIndID) then return false end
Event_TomatekhHRRosyCross.Name = "TXT_KEY_EVENT_TOMATEKH_HR_ROSY_CROSS"
return true
end
)
Event_TomatekhHRRosyCross.Outcomes = {}
-- Outcome 1
Event_TomatekhHRRosyCross.Outcomes[1] = {}
Event_TomatekhHRRosyCross.Outcomes[1].Name = "TXT_KEY_EVENT_TOMATEKH_HR_ROSY_CROSS_OUTCOME_1"
Event_TomatekhHRRosyCross.Outcomes[1].Desc = "TXT_KEY_EVENT_TOMATEKH_HR_ROSY_CROSS_OUTCOME_1_DESC"
Event_TomatekhHRRosyCross.Outcomes[1].Weight = 1
Event_TomatekhHRRosyCross.Outcomes[1].CanFunc = (
function(pPlayer)
local Award = 0;
local Proph = pPlayer:GetMinimumFaithNextGreatProphet();
local Faith = pPlayer:GetFaith();
if Faith >= Proph then
Award = Proph;
elseif Faith < Proph then
Award = (Proph - Faith);
end
Award = math.ceil(Award);
Event_TomatekhHRRosyCross.Outcomes[1].Desc = Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_ROSY_CROSS_OUTCOME_1_DESC", Award)
return true
end
)
Event_TomatekhHRRosyCross.Outcomes[1].DoFunc = (
function(pPlayer)
save(pPlayer, "Event_TomatekhHRRosyCross", true)
local Award = 0;
local Proph = pPlayer:GetMinimumFaithNextGreatProphet();
local Faith = pPlayer:GetFaith();
if Faith >= Proph then
Award = Proph;
elseif Faith < Proph then
Award = (Proph - Faith);
end
Award = math.ceil(Award);
pPlayer:ChangeFaith(Award);
JFD_SendNotification(pPlayer:GetID(), "NOTIFICATION_GENERIC", Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_ROSY_CROSS_OUTCOME_1_NOTIFICATION"), Locale.ConvertTextKey(Event_TomatekhHRRosyCross.Name))
local hPlayer = GetHumanPlayer();
if hPlayer ~= 0 then
if hPlayer ~= pPlayer then
local pTeam = pPlayer:GetTeam();
local hTeam = hPlayer:GetTeam();
if Teams[pTeam]:IsHasMet(hTeam) then
Events.GameplayAlertMessage("Rosicrucianism has provided " .. Locale.ConvertTextKey(pPlayer:GetCivilizationAdjective()) .. " citizens with new insights into their faith.")
end
end
end
end
)
-- Outcome 2
Event_TomatekhHRRosyCross.Outcomes[2] = {}
Event_TomatekhHRRosyCross.Outcomes[2].Name = "TXT_KEY_EVENT_TOMATEKH_HR_ROSY_CROSS_OUTCOME_2"
Event_TomatekhHRRosyCross.Outcomes[2].Desc = "TXT_KEY_EVENT_TOMATEKH_HR_ROSY_CROSS_OUTCOME_2_DESC"
Event_TomatekhHRRosyCross.Outcomes[2].Weight = 10
Event_TomatekhHRRosyCross.Outcomes[2].CanFunc = (
function(pPlayer)
local Award = 0;
local Proph = pPlayer:GetMinimumFaithNextGreatProphet();
local Faith = pPlayer:GetFaith();
if Faith >= Proph then
Award = Proph;
elseif Faith < Proph then
Award = (Proph - Faith);
end
Award = math.ceil(Award / 2);
Event_TomatekhHRRosyCross.Outcomes[2].Desc = Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_ROSY_CROSS_OUTCOME_2_DESC", Award)
return true
end
)
Event_TomatekhHRRosyCross.Outcomes[2].DoFunc = (
function(pPlayer)
save(pPlayer, "Event_TomatekhHRRosyCross", true)
local Award = 0;
local Proph = pPlayer:GetMinimumFaithNextGreatProphet();
local Faith = pPlayer:GetFaith();
if Faith >= Proph then
Award = Proph;
elseif Faith < Proph then
Award = (Proph - Faith);
end
Award = math.ceil(Award / 2);
local pTeamTechs = Teams[pPlayer:GetTeam()]:GetTeamTechs()
pTeamTechs:ChangeResearchProgress(pPlayer:GetCurrentResearch(), Award, pPlayer:GetID())
JFD_SendNotification(pPlayer:GetID(), "NOTIFICATION_GENERIC", Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_ROSY_CROSS_OUTCOME_2_NOTIFICATION"), Locale.ConvertTextKey(Event_TomatekhHRRosyCross.Name))
local hPlayer = GetHumanPlayer();
if hPlayer ~= 0 then
if hPlayer ~= pPlayer then
local pTeam = pPlayer:GetTeam();
local hTeam = hPlayer:GetTeam();
if Teams[pTeam]:IsHasMet(hTeam) then
Events.GameplayAlertMessage("Rosicrucianism has inspired " .. Locale.ConvertTextKey(pPlayer:GetCivilizationAdjective()) .. " citizens to form an Invisible College.")
end
end
end
end
)
tEvents.Event_TomatekhHRRosyCross = Event_TomatekhHRRosyCross
--=========================================================
--Revelation
--=========================================================
local Event_TomatekhHRDivineRevelation = {}
Event_TomatekhHRDivineRevelation.Name = "TXT_KEY_EVENT_TOMATEKH_HR_REVELATION"
Event_TomatekhHRDivineRevelation.Desc = "TXT_KEY_EVENT_TOMATEKH_HR_REVELATION_DESC"
Event_TomatekhHRDivineRevelation.EventImage = "HRDivineInsp.dds"
Event_TomatekhHRDivineRevelation.Weight = 1
Event_TomatekhHRDivineRevelation.CanFunc = (
function(pPlayer)
if load(pPlayer, "Event_TomatekhHRDivineRevelation") == true then return false end
if load(pPlayer, "Event_TomatekhHRAtheism") == true then return false end
if pPlayer:HasCreatedReligion() then return false end
if (Game.GetNumReligionsStillToFound() <= 0) then return false end
local Proph = pPlayer:GetMinimumFaithNextGreatProphet();
local Faith = pPlayer:GetFaith();
if Faith >= Proph then return false end
if not isBNW then return false end
Event_TomatekhHRDivineRevelation.Name = "TXT_KEY_EVENT_TOMATEKH_HR_REVELATION"
return true
end
)
Event_TomatekhHRDivineRevelation.Outcomes = {}
-- Outcome 1
Event_TomatekhHRDivineRevelation.Outcomes[1] = {}
Event_TomatekhHRDivineRevelation.Outcomes[1].Name = "TXT_KEY_EVENT_TOMATEKH_HR_REVELATION_OUTCOME_1"
Event_TomatekhHRDivineRevelation.Outcomes[1].Desc = "TXT_KEY_EVENT_TOMATEKH_HR_REVELATION_OUTCOME_1_DESC"
Event_TomatekhHRDivineRevelation.Outcomes[1].Weight = 10
Event_TomatekhHRDivineRevelation.Outcomes[1].CanFunc = (
function(pPlayer)
local Proph = pPlayer:GetMinimumFaithNextGreatProphet();
local Faith = pPlayer:GetFaith();
local Award = (Proph - Faith);
Award = math.ceil(Award / 3);
if Award <= 1 then
Award = 1;
end
Event_TomatekhHRDivineRevelation.Outcomes[1].Desc = Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_REVELATION_OUTCOME_1_DESC", Award)
return true
end
)
Event_TomatekhHRDivineRevelation.Outcomes[1].DoFunc = (
function(pPlayer)
save(pPlayer, "Event_TomatekhHRDivineRevelation", true)
local Proph = pPlayer:GetMinimumFaithNextGreatProphet();
local Faith = pPlayer:GetFaith();
local Award = (Proph - Faith);
Award = math.ceil(Award / 3);
if Award <= 1 then
Award = 1;
end
pPlayer:ChangeFaith(Award);
JFD_SendNotification(pPlayer:GetID(), "NOTIFICATION_GENERIC", Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_REVELATION_OUTCOME_1_NOTIFICATION"), Locale.ConvertTextKey(Event_TomatekhHRDivineRevelation.Name))
local hPlayer = GetHumanPlayer();
if hPlayer ~= 0 then
if hPlayer ~= pPlayer then
local pTeam = pPlayer:GetTeam();
local hTeam = hPlayer:GetTeam();
if Teams[pTeam]:IsHasMet(hTeam) then
Events.GameplayAlertMessage("Rumors of divine revelation are circulating " .. Locale.ConvertTextKey(pPlayer:GetCivilizationShortDescription()) .. "!")
end
end
end
end
)
tEvents.Event_TomatekhHRDivineRevelation = Event_TomatekhHRDivineRevelation
--=========================================================
--Atheism
--=========================================================
local Event_TomatekhHRAtheism = {}
Event_TomatekhHRAtheism.Name = "TXT_KEY_EVENT_TOMATEKH_HR_ATHEISM"
Event_TomatekhHRAtheism.Desc = "TXT_KEY_EVENT_TOMATEKH_HR_ATHEISM_DESC"
Event_TomatekhHRAtheism.EventImage = "HRAtheism.dds"
Event_TomatekhHRAtheism.Weight = 2
Event_TomatekhHRAtheism.CanFunc = (
function(pPlayer)
if load(pPlayer, "Event_TomatekhHRAtheism") == true then return false end
local pTeam = pPlayer:GetTeam();
if (Teams[pTeam]:GetCurrentEra() <= eIndustrial) then return false end
if (GetNumReligionsinEmpire(pPlayer) < 1) then return false end
if not isBNW then return false end
Event_TomatekhHRAtheism.Name = "TXT_KEY_EVENT_TOMATEKH_HR_ATHEISM"
return true
end
)
Event_TomatekhHRAtheism.Outcomes = {}
-- Outcome 1
Event_TomatekhHRAtheism.Outcomes[1] = {}
Event_TomatekhHRAtheism.Outcomes[1].Name = "TXT_KEY_EVENT_TOMATEKH_HR_ATHEISM_OUTCOME_1"
Event_TomatekhHRAtheism.Outcomes[1].Desc = "TXT_KEY_EVENT_TOMATEKH_HR_ATHEISM_OUTCOME_1_DESC"
Event_TomatekhHRAtheism.Outcomes[1].Weight = 10
Event_TomatekhHRAtheism.Outcomes[1].CanFunc = (
function(pPlayer)
Event_TomatekhHRAtheism.Outcomes[1].Desc = Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_ATHEISM_OUTCOME_1_DESC")
return true
end
)
Event_TomatekhHRAtheism.Outcomes[1].DoFunc = (
function(pPlayer)
save(pPlayer, "Event_TomatekhHRAtheism", true)
JFD_SendNotification(pPlayer:GetID(), "NOTIFICATION_GENERIC", Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_ATHEISM_OUTCOME_1_NOTIFICATION"), Locale.ConvertTextKey(Event_TomatekhHRAtheism.Name))
local hPlayer = GetHumanPlayer();
if hPlayer ~= 0 then
if hPlayer ~= pPlayer then
local pTeam = pPlayer:GetTeam();
local hTeam = hPlayer:GetTeam();
if Teams[pTeam]:IsHasMet(hTeam) then
Events.GameplayAlertMessage("The " .. Locale.ConvertTextKey(pPlayer:GetCivilizationAdjective()) .. " have begun to question the existence of God.")
end
end
end
end
)
tEvents.Event_TomatekhHRAtheism = Event_TomatekhHRAtheism
--=========================================================
--Rapture
--=========================================================
local Event_TomatekhHRRapture = {}
Event_TomatekhHRRapture.Name = "TXT_KEY_EVENT_TOMATEKH_HR_RAPTURE"
Event_TomatekhHRRapture.Desc = "TXT_KEY_EVENT_TOMATEKH_HR_RAPTURE_DESC"
Event_TomatekhHRRapture.EventImage = "HRRapture.dds"
Event_TomatekhHRRapture.Weight = 1
Event_TomatekhHRRapture.CanFunc = (
function(pPlayer)
if load(pPlayer, "Event_TomatekhHRRapture") == true then return false end
if load(pPlayer, "Event_TomatekhHRAtheism") == true then return false end
local pTeam = pPlayer:GetTeam();
if (Teams[pTeam]:GetCurrentEra() <= eModern) then return false end
if (GetNumReligionsinEmpire(pPlayer) < 1) then return false end
if pPlayer:GetNumCities() <= 0 then return false end
if pPlayer:GetNumCities() >= 1 then
local pcCity = pPlayer:GetCapitalCity();
local pcPop = pcCity:GetPopulation();
if pcPop <= 3 then return false end
end
if not isBNW then return false end
Event_TomatekhHRRapture.Name = "TXT_KEY_EVENT_TOMATEKH_HR_RAPTURE"
return true
end
)
Event_TomatekhHRRapture.Outcomes = {}
-- Outcome 1
Event_TomatekhHRRapture.Outcomes[1] = {}
Event_TomatekhHRRapture.Outcomes[1].Name = "TXT_KEY_EVENT_TOMATEKH_HR_RAPTURE_OUTCOME_1"
Event_TomatekhHRRapture.Outcomes[1].Desc = "TXT_KEY_EVENT_TOMATEKH_HR_RAPTURE_OUTCOME_1_DESC"
Event_TomatekhHRRapture.Outcomes[1].Weight = 10
Event_TomatekhHRRapture.Outcomes[1].CanFunc = (
function(pPlayer)
Event_TomatekhHRRapture.Outcomes[1].Desc = Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_RAPTURE_OUTCOME_1_DESC")
return true
end
)
Event_TomatekhHRRapture.Outcomes[1].DoFunc = (
function(pPlayer)
save(pPlayer, "Event_TomatekhHRRapture", true)
JFD_SendNotification(pPlayer:GetID(), "NOTIFICATION_GENERIC", Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_RAPTURE_OUTCOME_1_NOTIFICATION"), Locale.ConvertTextKey(Event_TomatekhHRRapture.Name))
for pCity in pPlayer:Cities() do
local RandomHR = GetRandomHR(1, 3)
if pCity:GetPopulation() > RandomHR then
pCity:ChangePopulation(-RandomHR, true);
end
end
local hPlayer = GetHumanPlayer();
if hPlayer ~= 0 then
if hPlayer ~= pPlayer then
local pTeam = pPlayer:GetTeam();
local hTeam = hPlayer:GetTeam();
if Teams[pTeam]:IsHasMet(hTeam) then
Events.GameplayAlertMessage("" .. Locale.ConvertTextKey(pPlayer:GetCivilizationShortDescription()) .. " was left behind...")
end
end
end
end
)
tEvents.Event_TomatekhHRRapture = Event_TomatekhHRRapture
--=========================================================
--Millenarianism
--=========================================================
local Event_TomatekhHRDoomCult = {}
Event_TomatekhHRDoomCult.Name = "TXT_KEY_EVENT_TOMATEKH_HR_DOOM_CULT"
Event_TomatekhHRDoomCult.Desc = "TXT_KEY_EVENT_TOMATEKH_HR_DOOM_CULT_DESC"
Event_TomatekhHRDoomCult.EventImage = "HRDoomCult.dds"
Event_TomatekhHRDoomCult.Weight = 3
Event_TomatekhHRDoomCult.CanFunc = (
function(pPlayer)
Event_TomatekhHRDoomCult.Name = "TXT_KEY_EVENT_TOMATEKH_HR_DOOM_CULT"
if load(pPlayer, "Event_TomatekhHRDoomCult") == true then return false end
if load(pPlayer, "Event_TomatekhHRAtheism") == true then return false end
if (pPlayer:GetCivilizationType() == GameInfoTypes.CIVILIZATION_MAYA) then return false end
local Turn = 0
if (Game.GetGameTurnYear() >= 250) and (Game.GetGameTurnYear() < 1000) then
Turn = 1;
end
if (Game.GetGameTurnYear() >= 1250) and (Game.GetGameTurnYear() < 2000) then
Turn = 1;
Event_TomatekhHRDoomCult.EventImage = "HRDoomCult2.dds"
end
if (Turn == 0) then return false end
if not isBNW then return false end
return true
end
)
Event_TomatekhHRDoomCult.Outcomes = {}
-- Outcome 1
Event_TomatekhHRDoomCult.Outcomes[1] = {}
Event_TomatekhHRDoomCult.Outcomes[1].Name = "TXT_KEY_EVENT_TOMATEKH_HR_DOOM_CULT_OUTCOME_1"
Event_TomatekhHRDoomCult.Outcomes[1].Desc = "TXT_KEY_EVENT_TOMATEKH_HR_DOOM_CULT_OUTCOME_1_DESC"
Event_TomatekhHRDoomCult.Outcomes[1].Weight = 10
Event_TomatekhHRDoomCult.Outcomes[1].CanFunc = (
function(pPlayer)
local Date = 2000
if (Game.GetGameTurnYear() >= 250) and (Game.GetGameTurnYear() < 1000) then
Date = 1000;
end
if (Game.GetGameTurnYear() >= 1250) and (Game.GetGameTurnYear() < 2000) then
Date = 2000;
end
Event_TomatekhHRDoomCult.Outcomes[1].Desc = Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_DOOM_CULT_OUTCOME_1_DESC", Date)
return true
end
)
Event_TomatekhHRDoomCult.Outcomes[1].DoFunc = (
function(pPlayer)
save(pPlayer, "Event_TomatekhHRDoomCult", true)
JFD_SendNotification(pPlayer:GetID(), "NOTIFICATION_GENERIC", Locale.ConvertTextKey("TXT_KEY_EVENT_TOMATEKH_HR_DOOM_CULT_OUTCOME_1_NOTIFICATION"), Locale.ConvertTextKey(Event_TomatekhHRDoomCult.Name))
if (Game.GetGameTurnYear() >= 250) and (Game.GetGameTurnYear() < 1000) then
save(pPlayer, "HR Millenarianism 1000", true)
end
if (Game.GetGameTurnYear() >= 1250) and (Game.GetGameTurnYear() < 2000) then
save(pPlayer, "HR Millenarianism 2000", true)
end
local RandomHR = GetRandomHR(1, 2)
if RandomHR == 1 then
save(pPlayer, "HR Millenarianism Bad", true)
elseif RandomHR == 2 then
save(pPlayer, "HR Millenarianism Good", true)
end
local hPlayer = GetHumanPlayer();
if hPlayer ~= 0 then
if hPlayer ~= pPlayer then
local pTeam = pPlayer:GetTeam();
local hTeam = hPlayer:GetTeam();
if Teams[pTeam]:IsHasMet(hTeam) then
Events.GameplayAlertMessage("" .. Locale.ConvertTextKey(pPlayer:GetCivilizationAdjective()) .. " citizens are convinced the world is going to end!")
end
end
end
end
)
tEvents.Event_TomatekhHRDoomCult = Event_TomatekhHRDoomCult
local speed = Game.GetGameSpeedType();
local MinorAnarchy = 0;
local MinorGA = 0;
if speed == GameInfo.GameSpeeds['GAMESPEED_QUICK'].ID then
MinorAnarchy = 1;
MinorGA = 3;
elseif speed == GameInfo.GameSpeeds['GAMESPEED_STANDARD'].ID then
MinorAnarchy = 1;
MinorGA = 4;
elseif speed == GameInfo.GameSpeeds['GAMESPEED_EPIC'].ID then
MinorAnarchy = 1;
MinorGA = 5;
elseif speed == GameInfo.GameSpeeds['GAMESPEED_MARATHON'].ID then
MinorAnarchy = 2;
MinorGA = 8;
else
MinorAnarchy = 2;
MinorGA = 8;
end
function HREndofWorld(playerID)
local pPlayer = Players[playerID]
if (load(pPlayer, "HR Millenarianism 1000") == true) then
if (Game.GetGameTurnYear() >= 1000) then
save(pPlayer, "HR Millenarianism 1000", false)
if (load(pPlayer, "HR Millenarianism Bad") == true) then
save(pPlayer, "HR Millenarianism Bad", false)
if pPlayer:IsAnarchy() then
pPlayer:ChangeAnarchyNumTurns(MinorAnarchy);
else
pPlayer:SetAnarchyNumTurns(MinorAnarchy);
end
if (pPlayer:IsHuman()) and (playerID == Game.GetActivePlayer()) then
Events.GameplayAlertMessage("[COLOR_NEGATIVE_TEXT]An unprecedented solar eclipse has incited your citizens to riot in the streets![ENDCOLOR]");
end
end
if (load(pPlayer, "HR Millenarianism Good") == true) then
save(pPlayer, "HR Millenarianism Good", false)
local gAge = pPlayer:GetNumGoldenAges()
pPlayer:ChangeGoldenAgeTurns(MinorGA)
pPlayer:SetNumGoldenAges(gAge)
if (pPlayer:IsHuman()) and (playerID == Game.GetActivePlayer()) then
Events.GameplayAlertMessage("[COLOR_POSITIVE_TEXT]Looks like the world didn't end after all...[ENDCOLOR]");
end
end
end
end
if (load(pPlayer, "HR Millenarianism 2000") == true) then
if (Game.GetGameTurnYear() >= 2000) then
save(pPlayer, "HR Millenarianism 1000", false)
if (load(pPlayer, "HR Millenarianism Bad") == true) then
save(pPlayer, "HR Millenarianism Bad", false)
if pPlayer:IsAnarchy() then
pPlayer:ChangeAnarchyNumTurns(MinorAnarchy);
else
pPlayer:SetAnarchyNumTurns(MinorAnarchy);
end
if (pPlayer:IsHuman()) and (playerID == Game.GetActivePlayer()) then
Events.GameplayAlertMessage("[COLOR_NEGATIVE_TEXT]Y2K will kill us all![ENDCOLOR]");
end
end
if (load(pPlayer, "HR Millenarianism Good") == true) then
save(pPlayer, "HR Millenarianism Good", false)
local gAge = pPlayer:GetNumGoldenAges()
pPlayer:ChangeGoldenAgeTurns(MinorGA)
pPlayer:SetNumGoldenAges(gAge)
if (pPlayer:IsHuman()) and (playerID == Game.GetActivePlayer()) then
Events.GameplayAlertMessage("[COLOR_POSITIVE_TEXT]Looks like the world didn't end after all...[ENDCOLOR]");
end
end
end
end
end
GameEvents.PlayerDoTurn.Add(HREndofWorld)
|
-- QWERTYSHR
local assert = require "lib.assert"
local inspect = require "lib.inspect"
local layout = require "lib.layout"
local shr = require "layouts.jp109.SHR"
return layout.new {
name = "QWERTYSHR",
build = function (model, keytable, options)
local K = model:map_to_key()
local C = model:map_to_char()
local left_thumb_key_list = keytable:map(options.left_thumb_key or "Space")
local left_thumb_key_role = options.left_thumb_key_role or KeyRole.TRIGGER
local left_thumb_command = model:map_to_key(options.left_thumb_command or {"Space"})
local right_thumb_key_list = keytable:map(options.right_thumb_key or "Convert")
local right_thumb_key_role = options.right_thumb_key_role or KeyRole.TRIGGER
local right_thumb_command = model:map_to_key(options.right_thumb_command or {"Convert"})
local left_left_thumb_key_list = keytable:map(options.left_left_thumb_key or "NonConvert")
local left_left_thumb_key_role = options.left_left_thumb_key_role or KeyRole.TRIGGER
local left_left_thumb_command = model:map_to_key(options.left_left_thumb_command or {"NonConvert"})
local right_right_thumb_key_list = keytable:map(options.right_right_thumb_key or "KatakanaHiragana")
local right_right_thumb_key_role = options.right_right_thumb_key_role or KeyRole.TRIGGER
local right_right_thumb_command = model:map_to_key(options.right_right_thumb_command or {"KatakanaHiragana"})
local alphanumeric_commands = model:map_to_keys(shr.QWERTY_COMMANDS)
local alphanumeric_shift_commands = model:map_to_keys(shr.QWERTY_SHIFT_COMMANDS)
local qwerty_alphanumeric_commands = model:map_to_keys {
{"1"}, {"2"}, {"3"}, {"4"}, {"5"}, {"6"}, {"7"}, {"8"}, {"9"}, {"0"}, {"-"}, {"^"}, {"\\|"},
{"q"}, {"w"}, {"e"}, {"r"}, {"t"}, {"y"}, {"u"}, {"i"}, {"o"}, {"p"}, {"@"}, {"["},
{"a"}, {"s"}, {"d"}, {"f"}, {"g"}, {"h"}, {"j"}, {"k"}, {"l"}, {";"}, {":"}, {"]"},
{"z"}, {"x"}, {"c"}, {"v"}, {"b"}, {"n"}, {"m"}, {","}, {"."}, {"/"}, {"\\_"},
}
local qwerty_alphanumeric_shift_commands = model:map_to_keys {
{"!"}, {"\""}, {"#"}, {"$"}, {"%"}, {"&"}, {"'"}, {"("}, {")"}, {"Shift+0"}, {"="}, {"~"}, {"|"},
{"Q"}, {"W"}, {"E"}, {"R"}, {"T"}, {"Y"}, {"U"}, {"I"}, {"O"}, {"P"}, {"`"}, {"{"},
{"A"}, {"S"}, {"D"}, {"F"}, {"G"}, {"H"}, {"J"}, {"K"}, {"L"}, {"+"}, {"*"}, {"}"},
{"Z"}, {"X"}, {"C"}, {"V"}, {"B"}, {"N"}, {"M"}, {"<"}, {">"}, {"?"}, {"_"},
}
local left_thumb_commands = model:map_to_keys(shr.LEFT_THUMB_COMMANDS)
local right_thumb_commands = model:map_to_keys(shr.RIGHT_THUMB_COMMANDS)
local cao_alphanumeric_commands = nil
local cao_alphanumeric_shift_commands = nil
if options.cao_type == "QWERTY" then
cao_alphanumeric_commands = qwerty_alphanumeric_commands
cao_alphanumeric_shift_commands = qwerty_alphanumeric_shift_commands
else
cao_alphanumeric_commands = qwerty_alphanumeric_commands
cao_alphanumeric_shift_commands = qwerty_alphanumeric_shift_commands
end
return {
simul_key_flows {
key_lists = keytable.alphanumeric_key_lists,
},
simul_key_flows {
key_lists = {
left_thumb_key_list,
right_thumb_key_list,
}
},
immediate_key_flows {
key_lists = {
left_left_thumb_key_list,
right_right_thumb_key_list,
}
},
immediate_key_flows {
key_lists = keytable.non_alphanumeric_key_lists,
},
immediate_key_flows {
key_lists = keytable.modifier_key_lists,
},
simple_mappings {
trigger_key_lists = keytable.alphanumeric_key_lists,
modifier_key_lists = keytable.modifier_key_lists,
commands = alphanumeric_commands,
shift_commands = alphanumeric_shift_commands,
},
extended_mappings {
trigger_key_lists = keytable.alphanumeric_key_lists,
shift_key_list = {left_thumb_key_list, left_thumb_key_role},
commands = left_thumb_commands,
},
extended_mappings {
trigger_key_lists = keytable.alphanumeric_key_lists,
shift_key_list = {right_thumb_key_list, right_thumb_key_role},
commands = right_thumb_commands,
},
simple_mappings {
trigger_key_lists = {left_thumb_key_list, right_thumb_key_list, left_left_thumb_key_list, right_right_thumb_key_list},
modifier_key_lists = keytable.modifier_key_lists,
commands = {left_thumb_command, right_thumb_command, left_left_thumb_command, right_right_thumb_command},
},
simple_mappings {
trigger_key_lists = keytable.non_alphanumeric_key_lists,
modifier_key_lists = keytable.modifier_key_lists,
commands = model.non_alphanumeric_commands,
},
modifiers_mappings {
modifier_key_lists = keytable.modifier_key_lists,
},
}
end
}
|
RegisterClientScript()
local vec2meta = RegisterMetatable("vec2")
vec2meta.__index = vec2meta
function vec2meta:Distance(vec)
return (self - vec):Length()
end
function vec2meta:DistanceTest(vec, distance)
return self:SquaredDistance(vec) < distance*distance
end
function vec2meta:GetNormalized()
local length = self:Length()
local normal = Vec2(self.x / length, self.y / length)
return normal, length
end
function vec2meta:Length()
return math.sqrt(self:SquaredLength())
end
function vec2meta:Normalize()
local length = self:Length()
self.x = self.x / length
self.y = self.y / length
return length
end
function vec2meta:SquaredLength()
return self.x * self.x + self.y * self.y
end
function vec2meta:SquaredDistance(vec)
return (self - vec):SquaredLength()
end
function vec2meta:__add(other)
if (getmetatable(other) == vec2meta) then
return Vec2(self.x + other.x, self.y + other.y)
else
error("Must be a vector2")
end
end
function vec2meta.__mul(lhs, rhs)
if (getmetatable(lhs) == vec2meta) then
if (getmetatable(rhs) == vec2meta) then
return Vec2(lhs.x * rhs.x, lhs.y * rhs.y)
elseif (type(rhs) == "number") then
return Vec2(lhs.x * rhs, lhs.y * rhs)
end
elseif (type(lhs) == "number") then
assert(getmetatable(rhs) == vec2meta)
return Vec2(lhs * rhs.x, lhs * rhs.y)
else
error("Factors must be a vector2 or a number")
end
end
function vec2meta.__div(lhs, rhs)
if (getmetatable(lhs) == vec2meta) then
if (getmetatable(rhs) == vec2meta) then
return Vec2(lhs.x / rhs.x, lhs.y / rhs.y)
elseif (type(rhs) == "number") then
return Vec2(lhs.x / rhs, lhs.y / rhs)
end
elseif (type(lhs) == "number") then
assert(getmetatable(rhs) == vec2meta)
return Vec2(lhs / rhs.x, lhs / rhs.y)
else
error("Divider must be a vector2 or a number")
end
end
function vec2meta:__sub(other)
if (getmetatable(other) == vec2meta) then
return Vec2(self.x - other.x, self.y - other.y)
else
error("Must be a vector")
end
end
function vec2meta:__unm()
return Vec2(-self.x, -self.y)
end
function vec2meta:__tostring()
return "vec2(" .. tostring(self.x) .. ", " .. tostring(self.y) .. ")"
end
function Vec2(x, y)
local vec2 = {x = x or 0, y = y or 0}
return setmetatable(vec2, vec2meta)
end
|
pg = pg or {}
pg.equip_data_by_quality = {
{
gear_score_addition = 5,
equip_quality = 1,
gear_score = 30,
destory_resource_ratio = 1
},
{
gear_score_addition = 8,
equip_quality = 2,
gear_score = 50,
destory_resource_ratio = 2
},
{
gear_score_addition = 10,
equip_quality = 3,
gear_score = 80,
destory_resource_ratio = 3
},
{
gear_score_addition = 12,
equip_quality = 4,
gear_score = 120,
destory_resource_ratio = 4
},
{
gear_score_addition = 15,
equip_quality = 5,
gear_score = 180,
destory_resource_ratio = 5
},
{
gear_score_addition = 20,
equip_quality = 6,
gear_score = 300,
destory_resource_ratio = 6
},
all = {
1,
2,
3,
4,
5,
6
}
}
return
|
--------------------------------
-- @module ClippingNode
-- @extend Node
-- @parent_module cc
--------------------------------
-- Inverted. If this is set to true,<br>
-- the stencil is inverted, so the content is drawn where the stencil is NOT drawn.<br>
-- This default to false.
-- @function [parent=#ClippingNode] isInverted
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#ClippingNode] setInverted
-- @param self
-- @param #bool inverted
--------------------------------
--
-- @function [parent=#ClippingNode] setStencil
-- @param self
-- @param #cc.Node stencil
--------------------------------
-- The alpha threshold.<br>
-- The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold.<br>
-- Should be a float between 0 and 1.<br>
-- This default to 1 (so alpha test is disabled).
-- @function [parent=#ClippingNode] getAlphaThreshold
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- The Node to use as a stencil to do the clipping.<br>
-- The stencil node will be retained.<br>
-- This default to nil.
-- @function [parent=#ClippingNode] getStencil
-- @param self
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
--
-- @function [parent=#ClippingNode] setAlphaThreshold
-- @param self
-- @param #float alphaThreshold
--------------------------------
-- @overload self, cc.Node
-- @overload self
-- @function [parent=#ClippingNode] create
-- @param self
-- @param #cc.Node stencil
-- @return ClippingNode#ClippingNode ret (retunr value: cc.ClippingNode)
--------------------------------
--
-- @function [parent=#ClippingNode] visit
-- @param self
-- @param #cc.Renderer renderer
-- @param #mat4_table parentTransform
-- @param #unsigned int parentFlags
return nil
|
local UpvalueHacker = require("tools/upvaluehacker")
local AddPrefabPostInit = AddPrefabPostInit
GLOBAL.setfenv(1, GLOBAL)
AddPrefabPostInit("pigking", function(inst)
if not TheWorld.ismastersim then return end
inst:DoTaskInTime(0, function(inst) -- Compatible with Mio the Nightmare Eater
local on_trade_for_gold = UpvalueHacker.GetUpvalue(inst.components.trader.onaccept, "ontradeforgold")
local function on_accept_fn(inst, item, giver)
local is_special_event_active = IsSpecialEventActive
IsSpecialEventActive = function(event)
if event == SPECIAL_EVENTS.HALLOWED_NIGHTS then
return false
end
return is_special_event_active(event)
end
on_trade_for_gold(inst, item, giver)
IsSpecialEventActive = is_special_event_active
end
UpvalueHacker.SetUpvalue(inst.components.trader.onaccept, "ontradeforgold", on_accept_fn)
end)
end)
|
function widget:GetInfo()
return {
name = "CaretakerRefresher",
desc = "Refreshes caretaker jobs prioritizing repair and reclaim. Version v0.3",
author = "zenfur, terve886",
date = "2019",
license = "MIT",
layer = 11,
enabled = true
}
end
options_path = 'Settings/Unit Behaviour/Refresher AI'
options_order = {
'updateRate',
'orderOverride',
}
options = {
updateRate = {
name = 'Refresh rate (higher numbers are faster but more CPU intensive):',
type = 'number',
min = 10, max = 600, step = 10,
value = 200,
},
orderOverride = {
name = 'Manual order expire time',
type = 'number',
min = 300, max = 30*180, step = 300,
value = 30*60
},
}
local sqrt = math.sqrt
local UPDATE_FRAME=options.updateRate.value
local UnitRegister = {}
local GetUnitMaxRange = Spring.GetUnitMaxRange
local GetUnitPosition = Spring.GetUnitPosition
local GetMyAllyTeamID = Spring.GetMyAllyTeamID
local GetUnitTeam = Spring.GetUnitTeam
local GiveOrderToUnit = Spring.GiveOrderToUnit
local GetGroundHeight = Spring.GetGroundHeight
local GetUnitsInSphere = Spring.GetUnitsInSphere
local GetUnitsInCylinder = Spring.GetUnitsInCylinder
local GetUnitAllyTeam = Spring.GetUnitAllyTeam
local GetUnitTeam = Spring.GetUnitTeam
local GetUnitNearestEnemy = Spring.GetUnitNearestEnemy
local GetUnitIsDead = Spring.GetUnitIsDead
local GetMyTeamID = Spring.GetMyTeamID
local GetUnitDefID = Spring.GetUnitDefID
local GetTeamUnits = Spring.GetTeamUnits
local GetUnitArmored = Spring.GetUnitArmored
local GetUnitStates = Spring.GetUnitStates
local IsUnitSelected = Spring.IsUnitSelected
local GetFeatureHealth = Spring.GetFeatureHealth
--[[
( number featureID ) -> nil | number health, number maxHealth, number resurrectProgress
--]]
local GetUnitHealth = Spring.GetUnitHealth
--[[
( number unitID ) -> nil | number health, number maxHealth, number paralyzeDamage,
number captureProgress, number buildProgress
--]]
local GetFeaturesInCylinder = Spring.GetFeaturesInCylinder
--[[ ( number x, number z, number radius )
-> featureTable = { [1] = number featureID, etc... }
--]]
local GetFeatureResources = Spring.GetFeatureResources
--[[
( number featureID ) -> nil | number RemainingMetal, number maxMetal,
number RemainingEnergy, number maxEnergy, number reclaimLeft, number reclaimTime
--]]
local GetFeaturePosition = Spring.GetFeaturePosition
--[[
( number featureID, [, boolean midPos [, boolean aimPos ] ] ) ->
nil |
number bpx, number bpy, number bpz [,
number mpx, number mpy, number mpz [,
number apx, number apy, number apz ]]
--]]
local Echo = Spring.Echo
local target_name = "staticcon"
local caretakerUnitDefID = UnitDefNames["staticcon"].id
local GetSpecState = Spring.GetSpectatingState
local CMD_STOP = CMD.STOP
local CMD_ATTACK = CMD.ATTACK
local CMD_PATROL = CMD.PATROL
local CMD_RECLAIM = CMD.RECLAIM
local CMD_REPAIR = CMD.REPAIR
local originX = 0.0
local originZ = 0.0
------------------------------------------------------------------------------
--[[
To use in future:
CommandNotifyTF()
ZK-Specific: Captures terraform commands from gui_lasso_terraform widget.
CommandNotifyRaiseAndBuild()
ZK-Specific: Captures raise-and-build commands from gui_lasso_terraform widget.
widget:CommandNotify()
This captures all the build-related commands from units in our group,
and adds them to the global queue.
TODOs:
#2 Every options.updateRate + some random refresh said caretaker job
#3 Count caretakers, Count income, count storage
]]--
local JOB_SABOTAGE = 0
local JOB_REPAIR = 1
local JOB_RECLAIM = 2
local JOB_BUILD = 3
local JOB_OVERRIDE = 4
local JOB_GUARD = 5
local JOB_IDLE = 999
local CaretakerController = {
unitID,
pos,
allyTeamID = GetMyAllyTeamID(),
selfTeamID = GetMyTeamID(),
range,
jobs,
currentJob,
last_job_id,
jobTargetID,
dontManageUntil = 0,
new = function(self, unitID)
--Echo("CaretakerController added:" .. unitID)
self = deepcopy(self)
self.unitID = unitID
DefID = GetUnitDefID(unitID)
self.range = UnitDefs[DefID].buildDistance - 25
self.pos = {GetUnitPosition(self.unitID)}
self.jobs = {}
self.currentJob = JOB_IDLE
self.last_job_id = -1
return self
end,
unset = function(self)
--Echo("CaretakerController removed:" .. self.unitID)
GiveOrderToUnit(self.unitID,CMD_STOP, {}, {""},1)
return nil
end,
setForceTarget = function(self, param)
self.forceTarget = param[1]
end,
findJobs = function(self)
self.jobTargetID = nil
--Echo("Searching jobs...")
units = GetUnitsInCylinder(self.pos[1], self.pos[3], self.range)
wrecks = GetFeaturesInCylinder(self.pos[1], self.pos[3], self.range)
reclaim_job = false
sabotage_job = false
repair_job = false
build_job = false
-- find ally build jobs in the area
-- is nanoframe
-- find reclaim jobs in the area
-- find enemy build jobs in the area
-- is enemy
-- is nanoframe
-- find ally repair jobs in the area
max_dist = 0.0
total_metal = 0.0
for index, w in ipairs(wrecks) do
if w and GetFeatureHealth(w) then
metal = select(1, GetFeatureResources(w))
resurrect_progress = select(3, GetFeatureHealth(w))
xx, yy, zz = GetFeaturePosition(w)
dist = (xx-originX)*(xx-originX) + (zz-originZ)*(zz-originZ)
if metal > 0 and resurrect_progress == 0 then
total_metal = total_metal + metal
if dist > max_dist then
reclaim_job = w
max_dist = dist
end
end
end
end
for index, unit in ipairs(units) do
unitAlliance = GetUnitAllyTeam(unit)
hp, mxhp, _, _, bp = GetUnitHealth(unit)
-- Echo("Unit alliance " .. unitAlliance .. " " .. self.allyTeamID)
if unitAlliance ~= self.allyTeamID then
if bp and bp < 1.0 then
sabotage_job = unit
end
else
if bp and bp < 1.0 then
if GetUnitStates(self.unitID).movestate > 1 -- if set to ROAM accept ally buildorders
or self.selfTeamID == GetUnitTeam(unit) then
build_job = unit
end
elseif hp < mxhp then
repair_job = unit
end
end
end
--Echo("Found jobs for " .. self.unitID)
if reclaim_job then
--Echo("Reclaim job found ".. reclaim_job)
end
if sabotage_job then
--Echo("Sabotage job found " .. sabotage_job)
end
if repair_job then
--Echo("Repair job found " .. repair_job)
end
if build_job then
--Echo("Building job found " .. build_job)
end
return {repair = repair_job, sabotage = sabotage_job, reclaim = reclaim_job, build = build_job}
end,
handle=function(self)
Echo(self.currentJob)
if (GetUnitStates(self.unitID).movestate > 0) then
--[[ manage todo:
if guarding check if guard target is in range
if repairing check if repair target is in range
--]]if (self.currentJob == JOB_OVERRIDE and self.jobTargetID)then
targetPositionX, targetPositionY, targetPositionZ = GetUnitPosition(self.jobTargetID)
if(distance(self.pos[1],self.pos[3],targetPositionX,targetPositionZ)>self.range)then
self.currentJob = JOB_IDLE
end
end
--Echo("Current job " .. self.currentJob)
if self.currentJob ~= JOB_OVERRIDE then -- and not IsUnitSelected(self.unitID)
jobs = self:findJobs() -- active job hunting
-- job selection
if jobs["sabotage"] then
--Echo("Selecting sabotage job")
if self.last_job_id ~= jobs["sabotage"] then
GiveOrderToUnit(self.unitID, CMD_RECLAIM, {jobs["sabotage"]}, {""}, 1)
self.currentJob = JOB_SABOTAGE
self.last_job_id = jobs["sabotage"]
end
elseif jobs["repair"] then
--Echo("Selecting repair job")
if self.last_job_id ~= jobs["repair"] then
GiveOrderToUnit(self.unitID, CMD_REPAIR, {jobs["repair"]}, {""}, 1)
self.currentJob = JOB_REPAIR
self.last_job_id = jobs["repair"]
end
elseif jobs["reclaim"] then
--Echo("Selecting reclaim job")
if self.last_job_id ~= jobs["reclaim"] then
--Echo("Last reclaim job id: " .. self.last_job_id)
GiveOrderToUnit(self.unitID, CMD_RECLAIM, {Game.maxUnits + jobs["reclaim"]}, {""}, 1)--{self.pos[1], self.pos[2], self.pos[3], self.range}, {""}, 1)
self.currentJob = JOB_RECLAIM
self.last_job_id = jobs["reclaim"]
end
elseif jobs["build"] then
--Echo("Selecting build job")
if self.last_job_id ~= jobs["build"] then
GiveOrderToUnit(self.unitID, CMD_REPAIR, {jobs["build"]}, {""}, 1)
self.currentJob = JOB_BUILD
self.last_job_id = jobs["build"]
end
end
end
end
end
}
function distance ( x1, y1, x2, y2 )
local dx = (x1 - x2)
local dy = (y1 - y2)
return sqrt ( dx * dx + dy * dy )
end
function widget:CommandNotify(cmdID, params, options)
if selectedCaretakers ~= nil then
if (cmdID == CMD_STOP) then
for i=1, #selectedCaretakers do
UnitRegister[selectedCaretakers[i]].currentJob = JOB_IDLE
UnitRegister[selectedCaretakers[i]].last_job_id = -1
end
else
for i=1, #selectedCaretakers do
UnitRegister[selectedCaretakers[i]].currentJob = JOB_OVERRIDE
if #params==1 then
UnitRegister[selectedCaretakers[i]].jobTargetID = params[1]
else
UnitRegister[selectedCaretakers[i]].jobTargetID = nil
end
UnitRegister[selectedCaretakers[i]].last_job_id = -1
end
end
end
end
function widget:SelectionChanged(selectedUnits)
selectedCaretakers = filterCaretakers(selectedUnits)
end
function filterCaretakers(units)
local filtered = {}
local n = 0
for i = 1, #units do
local unitID = units[i]
if (caretakerUnitDefID == GetUnitDefID(unitID)) then
n = n + 1
filtered[n] = unitID
end
end
if n == 0 then
return nil
else
return filtered
end
end
function widget:UnitCmdDone(unitID, unitDefID, unitTeam, cmdID, cmdParams, cmdOpts, cmdTag)
if not (UnitRegister[unitID] == nil) then
UnitRegister[unitID].currentJob = JOB_IDLE
UnitRegister[unitID].last_job_id = -1
UnitRegister[unitID]:handle()
end
end
function widget:UnitFinished(unitID, unitDefID, unitTeam)
if (string.match(UnitDefs[unitDefID].name, "dyn"))
and (unitTeam==GetMyTeamID()) then
originX, _, originZ = GetUnitPosition(unitID)
Echo("Commander found, initializing X, Y, Z as " .. originX .. " " .. _ .. " " .. originZ)
end
end
function widget:UnitCreated(unitID, unitDefID, unitTeam)
if (UnitDefs[unitDefID].name==target_name)
and (unitTeam==GetMyTeamID()) then
UnitRegister[unitID] = CaretakerController:new(unitID);
end
end
-- removing transferred units
function widget:UnitTaken(unitID, unitDefID, unitTeam, newTeam)
if not (UnitRegister[unitID]==nil) and unitID == GetMyTeamID() then
UnitRegister[unitID]=UnitRegister[unitID]:unset();
end
end
-- accepting transferred units - add them to register
function widget:UnitGiven(unitID, unitDefID, newTeam, unitTeam)
if (UnitDefs[unitDefID].name==target_name)
and (unitTeam==GetMyTeamID()) then
UnitRegister[unitID] = CaretakerController:new(unitID);
end
end
function widget:UnitDestroyed(unitID)
if not (UnitRegister[unitID]==nil) then
UnitRegister[unitID]=UnitRegister[unitID]:unset();
end
end
function widget:GameFrame(n)
if (n%options.updateRate.value==0) then
for _, TargetUnit in pairs(UnitRegister) do
TargetUnit:handle()
-- todo: switch to scheduled management model using value below
TargetUnit.dontManageUntil = TargetUnit.dontManageUntil + options.updateRate.value + n%4
end
end
end
function widget:Initialize()
-- disable if spectating or resigned
widget:PlayerChanged()
local units = GetTeamUnits(Spring.GetMyTeamID())
for i=1, #units do
DefID = GetUnitDefID(units[i])
if (UnitDefs[DefID].name==target_name) then
if (UnitRegister[units[i]]==nil) then
UnitRegister[units[i]]=CaretakerController:new(units[i])
end
end
end
end
function deepcopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[deepcopy(orig_key)] = deepcopy(orig_value)
end
setmetatable(copy, deepcopy(getmetatable(orig)))
else
copy = orig
end
return copy
end
-- The rest of the code is there to disable the widget for spectators
function widget:PlayerChanged(playerID)
if GetSpecState() then
Echo( widget:GetInfo().name .. ": Spectator mode. Widget removed." )
widgetHandler:RemoveWidget(widget)
return
end
end
|
-- List of locks
LOCKS_ARRAY =
{
"NONE",
"PIGGIFTS",
"TREES",
"SPIDERDENS",
"ROCKS",
"FARM",
"MEAT",
"BEEHIVE",
"KILLERBEES",
"PIGKING",
"MONSTERS_DEFEATED",
"HARD_MONSTERS_DEFEATED",
"SPIDERS_DEFEATED",
"BASIC_COMBAT",
"ADVANCED_COMBAT",
"ONLYTIER1",
"TIER1",
"TIER2",
"TIER3",
"TIER4",
"TIER5",
"LIGHT",
"FUNGUS",
"CAVE",
"LABYRINTH",
"WILDS",
"RUINS",
"SACRED",
--"ADVANCED_COMBAT",
}
LOCKS = {}
for i,v in ipairs(LOCKS_ARRAY) do
assert(LOCKS[v] == nil, "Lock "..v.." is defined twice!")
LOCKS[v] = i
end
-- List of keys
KEYS_ARRAY =
{
"NONE",
"PICKAXE",
"AXE",
"GRASS",
"STONE",
"WOOD",
"MEAT",
"PIGS",
"FIRE",
"POOP",
"WOOL",
"FARM",
"HONEY",
"GOLD",
"BEEHAT",
"TRINKETS",
"HARD_WALRUS",
"HARD_SPIDERS",
"HARD_HOUNDS",
"HARD_MERMS",
"HARD_TENTACLES",
"WALRUS",
"SPIDERS",
"HOUNDS",
"MERMS",
"GEARS",
"CHESSMEN",
"TENTACLES",
"TIER1",
"TIER2",
"TIER3",
"TIER4",
"TIER5",
"TIER6",
"LIGHT",
"FUNGUS",
"CAVE",
"LABYRINTH",
"WILDS",
"RUINS",
"SACRED",
}
KEYS = {}
for i,v in ipairs(KEYS_ARRAY) do
assert(KEYS[v] == nil, "Key "..v.." is defined twice!")
KEYS[v] = i
end
-- Locks are unlocked if ANY key is provided.
-- However, ALL locks must be opened for a task to be unlocked.
LOCKS_KEYS =
{
[LOCKS.NONE] =
{},
[LOCKS.HARD_MONSTERS_DEFEATED] =
{
KEYS.HARD_WALRUS,
KEYS.HARD_SPIDERS,
KEYS.HARD_HOUNDS,
KEYS.HARD_MERMS,
KEYS.HARD_TENTACLES,
KEYS.CHESSMEN,
},
[LOCKS.MONSTERS_DEFEATED] =
{
KEYS.WALRUS,
KEYS.SPIDERS,
KEYS.HOUNDS,
KEYS.MERMS,
KEYS.TENTACLES,
KEYS.CHESSMEN,
},
[LOCKS.SPIDERS_DEFEATED] =
{
KEYS.SPIDERS,
},
[LOCKS.BASIC_COMBAT] =
{
KEYS.AXE,
KEYS.PIGS,
},
[LOCKS.ADVANCED_COMBAT] =
{
KEYS.GOLD,
KEYS.HONEY,
},
[LOCKS.ROCKS] =
{
KEYS.PICKAXE
},
[LOCKS.PIGGIFTS] =
{
KEYS.MEAT,
KEYS.AXE,
KEYS.PICKAXE,
},
[LOCKS.TREES] =
{
KEYS.AXE,
KEYS.FIRE,
},
[LOCKS.SPIDERDENS] =
{
KEYS.PIGS,
KEYS.FIRE,
KEYS.AXE,
KEYS.PICKAXE,
KEYS.HONEY,
},
[LOCKS.BEEHIVE] =
{
KEYS.AXE,
},
[LOCKS.FARM] =
{
KEYS.POOP,
},
[LOCKS.MEAT] =
{
KEYS.SPIDERS,
KEYS.PIGS,
KEYS.FARM,
},
[LOCKS.KILLERBEES] =
{
KEYS.BEEHAT,
},
[LOCKS.PIGKING] =
{
KEYS.TRINKETS,
},
[LOCKS.TREES] =
{
KEYS.AXE,
KEYS.PIGS,
},
[LOCKS.ONLYTIER1] =
{
KEYS.TIER1,
},
[LOCKS.TIER1] =
{
KEYS.TIER1,
KEYS.TIER2,
},
[LOCKS.TIER2] =
{
KEYS.TIER2,
KEYS.TIER3,
},
[LOCKS.TIER3] =
{
KEYS.TIER3,
KEYS.TIER4,
},
[LOCKS.TIER4] =
{
KEYS.TIER4,
KEYS.TIER5,
},
[LOCKS.TIER5] =
{
KEYS.TIER5,
KEYS.TIER6,
},
[LOCKS.LIGHT] =
{
KEYS.LIGHT,
},
[LOCKS.CAVE] =
{
KEYS.CAVE,
},
[LOCKS.FUNGUS] =
{
KEYS.FUNGUS,
},
[LOCKS.LABYRINTH] =
{
KEYS.LABYRINTH,
},
[LOCKS.WILDS] =
{
KEYS.WILDS,
},
[LOCKS.RUINS] =
{
KEYS.RUINS
},
[LOCKS.SACRED] =
{
KEYS.SACRED
}
}
for lock,keyset in pairs(LOCKS_KEYS) do
assert(lock ~= nil and lock == LOCKS[LOCKS_ARRAY[lock]], "A lock in the lock_keys is misnamed!")
local count = 0
for i,key in pairs(keyset) do
assert(key ~= nil and key == KEYS[KEYS_ARRAY[key]], "A key in lock "..LOCKS_ARRAY[lock].." is misnamed!")
count = count + 1
end
assert(#keyset == count, "There appears to be an incorrectly named key in locks_keys: "..LOCKS_ARRAY[lock])
-- NOTE: This wil **NOT** catch it if the typo is in the last key in the list. ... But it's better than nothing...
end
--print("LOCKS")
--dumptable(LOCKS,1)
--print("KEYS")
--dumptable(KEYS,1)
--print("LOCKS_KEYS")
--dumptable(LOCKS_KEYS,1,1)
|
local dropList = {}
RegisterNetEvent("b03461cc:pd-inventory:remove")
AddEventHandler("b03461cc:pd-inventory:remove",function(zone, id)
if dropList[zone][tostring(id)] then
dropList[zone][tostring(id)] = nil
end
end)
RegisterNetEvent("b03461cc:pd-inventory:createForAll")
AddEventHandler("b03461cc:pd-inventory:createForAll",function(id,zone,marker)
if not dropList[zone] then dropList[zone] = {} end
dropList[zone][tostring(id)] = marker
end)
local cooldown = false
Citizen.CreateThread(function()
while true do
idle = 500
if dropList[gridZone] then
idle = 1
for k,v in pairs(dropList[gridZone]) do
local x,y,z = table.unpack(GetEntityCoords(PlayerPedId()))
local _,cdz = GetGroundZFor_3dCoord(v.x,v.y,v.z)
if GetDistanceBetweenCoords(v.x,v.y,cdz,x,y,z,true) <= 3.5 then
DrawMarker(20,v.x,v.y,cdz+0.15,0,0,0,0,180.0,130.0,0.25,0.5,0.25,255,255,255,200,0,0,0,0)
end
end
end
Citizen.Wait(idle)
end
end)
------------------------------------------------------------------------------------------------------------------------------------------------------
-- Drop Callbacks
------------------------------------------------------------------------------------------------------------------------------------------------------
RegisterNUICallback("DropItem", function(data, cb)
if IsPedSittingInAnyVehicle(PlayerPedId()) then
return
end
if type(data.number) == "number" and math.floor(data.number) == data.number then
TriggerServerEvent("b03461cc:pd-inventory:dropItem", GetEntityCoords(PlayerPedId()), gridZone, data.data.item, data.number)
end
Wait(300)
updateInventory()
updateDrop()
end)
RegisterNUICallback("PickupItem", function(data, cb)
if type(data.number) == "number" and math.floor(data.number) == data.number then
TriggerServerEvent("b03461cc:pd-inventory:pickupItem", GetEntityCoords(PlayerPedId()), gridZone, data.data.item, data.number)
end
Wait(300)
updateInventory()
updateDrop()
end) |
-- Tests that work in E3. With game config of E3.
-- Tests are under scripts/test/e3 and all files must be in scripts/test/e3/init.lua
path = 'scripts'
if config.install then
path = config.install .. '/' .. path
package.path = package.path .. ';' .. config.install .. '/lunit/?.lua'
--needed to find lunit if not run form eressea root. Needs right [lua] install setting in eressea.ini (point to eressea root from the start folder)
end
package.path = package.path .. ';' .. path .. '/?.lua;' .. path .. '/?/init.lua'
config.rules = 'e4'
require 'eressea'
require 'eressea.path'
require 'eressea.xmlconf'
require 'tests.e3'
require 'lunit'
eressea.settings.set("rules.alliances", "0")
rules = require('eressea.' .. config.rules)
result = lunit.main()
return result.errors + result.failed
|
--***********************************************************
--** THE INDIE STONE **
--** Author: turbotutone **
--***********************************************************
require "DebugUIs/DebugMenu/Base/ISDebugSubPanelBase";
---@class ISStatsAndBody : ISDebugSubPanelBase
ISStatsAndBody = ISDebugSubPanelBase:derive("ISStatsAndBody");
function ISStatsAndBody:initialise()
ISPanel.initialise(self);
end
function ISStatsAndBody:createChildren()
ISPanel.createChildren(self);
local x,y,w, obj = 10,10,self.width-30;
self:initHorzBars(x,w);
y, obj = ISDebugUtils.addLabel(self,"float_title",x+(w/2),y,"Player Stats and Body", UIFont.Medium);
obj.center = true;
y, obj = ISDebugUtils.addLabel(self,"float_title",x+(w/2),y,"(morale can only be adjusted when stress > 0)", UIFont.Small);
obj.center = true;
y, obj = ISDebugUtils.addLabel(self,"float_title",x+(w/2),y,"(pain and sickness cannot be adjusted manually)", UIFont.Small);
obj.center = true;
y = ISDebugUtils.addHorzBar(self,y+5)+5;
local player = getPlayer();
local stats = player:getStats();
local body = player:getBodyDamage();
self.sliderOptions = {};
self.boolOptions = {};
self:addSliderOption(stats,"Hunger", 0, 1);
self:addSliderOption(stats,"Thirst", 0, 1);
self:addSliderOption(stats,"Fatigue", 0, 1);
self:addSliderOption(stats,"Endurance", 0, 1);
local op = self:addSliderOption(stats,"Fitness", 0, 2); -- -1 to 1, use applymod due to slider
op.applyMod = 1;
self:addSliderOption(stats,"Drunkenness", 0, 100, 1);
self:addSliderOption(stats,"Anger", 0, 1);
--self:addSliderOption(stats,"Boredom", 0, 1);
self:addSliderOption(stats,"Fear", 0, 1);
self:addSliderOption(stats,"Pain", 0, 100, 1);
self:addSliderOption(stats,"Panic", 0, 100, 1);
self:addSliderOption(stats,"Morale", 0, 1);
self:addSliderOption(stats,"Stress", 0, 1);
self:addSliderOption(stats,"StressFromCigarettes", 0, stats:getMaxStressFromCigarettes());
self:addSliderOption(player,"TimeSinceLastSmoke", 0, 10);
self:addSliderOption(body,"BoredomLevel", 0, 100, 1);
self:addSliderOption(body,"UnhappynessLevel", 0, 100, 1);
self:addSliderOption(stats,"Sanity", 0, 1);
self:addSliderOption(body,"Wetness", 0, 100, 1);
self:addSliderOption(body,"Temperature", 20, 40, 0.1);
op = self:addSliderOption(body,"ColdDamageStage", 0, 1);
op.title = "ColdDamageStage (hypo 4)";
self:addSliderOption(body,"OverallBodyHealth", 0, 100, 1);
op = self:addSliderOption(body,"ColdStrength", 0, 100, 1);
op.title = "CatchAColdStrength";
self:addSliderOption(stats,"Sickness", 0, 1);
self:addSliderOption(body,"InfectionLevel", 0, 100, 1);
self:addSliderOption(body,"FakeInfectionLevel", 0, 100, 1);
self:addSliderOption(body,"FoodSicknessLevel", 0, 100, 1);
self:addBoolOption(body,"IsInfected", "IsInfected", "setInfected");
self:addBoolOption(body,"IsFakeInfected", "IsFakeInfected", "setIsFakeInfected");
self:addBoolOption(body,"IsOnFire", "IsOnFire", "setIsOnFire");
self:addBoolOption(player,"Ghost", "isGhostMode", "setGhostMode");
self:addBoolOption(player,"God Mod", "isGodMod", "setGodMod");
self:addBoolOption(player,"Invisible", "isInvisible", "setInvisible");
--self:addBoolOption(body,"HasACold", "isHasACold", "setHasACold");
local barMod = 3;
local y2, label, value, slider;
for k,v in ipairs(self.sliderOptions) do
y2,label = ISDebugUtils.addLabel(self,v,x,y,v.title or v.var, UIFont.Small);
y2,value = ISDebugUtils.addLabel(self,v,x+(w/2)-20,y,"0", UIFont.Small, false);
y,slider = ISDebugUtils.addSlider(self,v,x+(w/2),y,w/2, 18, ISStatsAndBody.onSliderChange);
slider.valueLabel = value;
v.label = label;
v.labelValue = value;
v.slider = slider;
--slider:setCurrentValue(v.java[v.get](v.java[v.get]));
slider:setValues(v.min, v.max, v.step, v.step, true);
local val = v.java[v.get](v.java) + v.applyMod;
--print(v.var.." = "..tostring(val))
slider:setCurrentValue(val);
y = ISDebugUtils.addHorzBar(self,y+barMod)+barMod;
end
local tickbox;
for k,v in ipairs(self.boolOptions) do
y2,label = ISDebugUtils.addLabel(self,v,x,y,v.var, UIFont.Small);
local tickOptions = {};
table.insert(tickOptions, { text = "Enabled", ticked = false });
y,tickbox = ISDebugUtils.addTickBox(self,v,x+(w/2),y,w/2,ISDebugUtils.FONT_HGT_SMALL,v.var,tickOptions,ISStatsAndBody.onTicked);
v.label = label;
v.tickbox = tickbox;
y = ISDebugUtils.addHorzBar(self,y+barMod)+barMod;
end
self:setScrollHeight(y+10);
end
function ISStatsAndBody:addSliderOption(_java, _var, _min, _max, _step, _get, _set)
local option = {
java = _java,
var = _var,
min = _min,
max = _max,
step = _step or 0.01,
get = _get or "get".._var,
set = _set or "set".._var,
applyMod = 0,
};
table.insert(self.sliderOptions,option);
return option;
end
function ISStatsAndBody:addBoolOption(_java, _var, _get, _set)
local bool = {
java = _java,
var = _var,
get = _get,
set = _set,
};
table.insert(self.boolOptions,bool);
return bool;
end
function ISStatsAndBody:prerender()
ISDebugSubPanelBase.prerender(self);
local val;
for k,v in ipairs(self.sliderOptions) do
val = v.java[v.get](v.java);
v.slider.currentValue = val + v.applyMod;
if v.slider.pretext then
v.labelValue:setName(v.slider.pretext..ISDebugUtils.printval(val,3));
else
v.labelValue:setName(ISDebugUtils.printval(val,3));
end
end
for k,v in ipairs(self.boolOptions) do
val = v.java[v.get](v.java);
v.tickbox.selected[1] = val;
end
end
function ISStatsAndBody:onSliderChange(_newval, _slider)
local v = _slider.customData;
if v.var=="Fitness" then
local xp = getPlayer():getXp();
local val = (_newval/2)*10;
--print("fitness = "..tostring(val))
xp:setXPToLevel(Perks.Fitness, val);
getPlayer():setPerkLevelDebug(Perks.Fitness, val);
return;
elseif v.var=="OverallBodyHealth" then
local b = getPlayer():getBodyDamage();
if _newval<b:getOverallBodyHealth() then
b:ReduceGeneralHealth(b:getOverallBodyHealth()-_newval);
elseif _newval>b:getOverallBodyHealth() then
b:AddGeneralHealth(_newval-b:getOverallBodyHealth());
end
return;
elseif v.var=="ColdStrength" then
local b = getPlayer():getBodyDamage();
if _newval>0 then
b:setHasACold(true);
else
b:setHasACold(false);
end
end
v.java[v.set](v.java,_newval-v.applyMod);
end
function ISStatsAndBody:onTicked(_index, _selected, _arg1, _arg2, _tickbox)
local v = _tickbox.customData;
v.java[v.set](v.java, not v.java[v.get](v.java));
end
function ISStatsAndBody:update()
ISPanel.update(self);
end
function ISStatsAndBody:new(x, y, width, height, doStencil)
local o = {};
o = ISDebugSubPanelBase:new(x, y, width, height, doStencil);
setmetatable(o, self);
self.__index = self;
return o;
end
|
char = game.Players.acb227.Character
function spark()
Hit = char.Head.CFrame
pcall(function() workspace.Guideline:remove() end)
local P = Instance.new("Part")
P.Name = "Guideline"
local Place0 = workspace.Visualist.Head.CFrame
P.formFactor = 0
P.Size = Vector3.new(1,1,(Place0.p - Hit.p).magnitude)
P.CFrame = CFrame.new((Place0.p + Hit.p)/2,Place0.p)
P.Parent = workspace
P.BrickColor = BrickColor.Black()
P.Anchored = true
P.CanCollide = false
P.Transparency = 1
m = Instance.new("BlockMesh")
m.Scale = Vector3.new(0.1,0.1,1)
m.Parent = P
mh = char.Head.CFrame
for c1 = 1, 1 do
oldHit = char.Head.CFrame
for count = 1, 9 do
val1 = Vector3.new(math.random(-1,1),math.random(-1,1),math.random(-1,1))
val2 = P.Size.z / 10
val3 = P.CFrame.lookVector * -1
val4 = count * val2
val5 = val4 * val3
val6 = workspace.Visualist.Head.CFrame.p
Hit = CFrame.new(val5 + val1 + val6)
local s = Instance.new("Part")
s.Name = "Spark"
local Place0 = oldHit
s.formFactor = 0
s.Size = Vector3.new(1,1,(Place0.p - Hit.p).magnitude)
s.CFrame = CFrame.new((Place0.p + Hit.p)/2,Place0.p)
s.Parent = P
s.BrickColor = BrickColor.White()
s.Anchored = true
s.CanCollide = false
m = Instance.new("BlockMesh")
m.Scale = Vector3.new(0.1,0.1,1)
m.Parent = s
clone = s:clone()
clone.Mesh.Scale = Vector3.new(0.3,0.3,1.1)
clone.BrickColor = BrickColor.Blue()
clone.Transparency = 0.8
clone.Parent = s.Parent
oldHit = Hit
end
Hit = oldHit
local s = Instance.new("Part")
s.Name = "Spark"
local Place0 = mh
s.formFactor = 0
s.Size = Vector3.new(1,1,(Place0.p - Hit.p).magnitude)
s.CFrame = CFrame.new((Place0.p + Hit.p)/2,Place0.p)
s.Parent = P
s.BrickColor = BrickColor.White()
s.Anchored = true
s.CanCollide = false
m = Instance.new("BlockMesh")
m.Scale = Vector3.new(0.1,0.1,1)
m.Parent = s
clone = s:clone()
clone.Mesh.Scale = Vector3.new(0.3,0.3,1.1)
clone.BrickColor = BrickColor.Blue()
clone.Transparency = 0.8
clone.Parent = s.Parent
wait(0.5)
end
P:remove()
end
while true do
spark()
wait()
end
|
-- Make sure Graphite is in our path
-- Only these examples need to do this
if (not __GRAPHITE_IN_PATH) then
__GRAPHITE_IN_PATH = true
package.path = package.path .. ";../?/init.lua"
end
--[[
Graphite: Simple OOP
Graphite provides an expressive OOP implementation.
For inheritance, see easy-oop-inhertiance
]]
local Graphite = require("Graphite")
-- Create a class representing something with a Name
-- Also give it a __tostring
local Named = Graphite.OOP:Class()
:Members {
Name = "Unknown"
}
:Metatable {
__tostring = function(self)
return self.Name
end
}
-- Give it a constructor with an optional 'name' argument
function Named:_init(name)
self.Name = name or "Unknown"
end
-- Usage
-- Create Bob and Jan
local Bob = Named:New("Bob")
local Jan = Named:New("Jan")
-- These give results as expected
print("Bob's name is " .. Bob.Name)
print("Jan's name is " .. Jan.Name)
-- We can change values with no problem
Bob.Name = "Bobby"
-- Bob has legally changed his name to Bobby!
print("Bob's new name is " .. Bob.Name)
-- Let's create a clone of Jan and name her Janice
local Janice = Jan:Copy()
Janice.Name = "Janice"
-- Our clone lives and has her own identity!
print("Janice's name is " .. Janice.Name) |
-- @Author:pandayu
-- @Version:1.0
-- @DateTime:2018-09-09
-- @Project:pandaCardServer CardGame
-- @Contact: QQ:815099602
local CDb = require "include.db"
local config = require "game.config"
local timetool = require "include.timetool"
local rankMgr = require "manager.rankMgr"
local roleMgr = require "manager.roleMgr"
local _M = {}
_M.soldiers = {}
_M.update_time = {d=-1,h=21,m=0,s=0}
function _M:init(db_config)
self.db = CDb:new(db_config)
local result = self.db:get_all_record()
if not result then return false end
for i=1,#result do
local v = result[i]
self.soldiers[v.soldier_id] = v
end
for id,v in pairs(config.template.hero) do
config.rank_type["soldier_"..id] = "soldier_"..id
config.rank["soldier_"..id] = {
type = "soldier_"..id,
asc = false
}
config.reward["soldier_"..id] = {
type = "soldier_"..id,
rank_type = "soldier_"..id,
title = "名将榜奖励",
content = "你在士兵培养上有独到的见解,司令部特给予优秀的指挥官予以奖励!以资鼓励!",
template = "general",
update_time = self.update_time,
}
rankMgr:append_new_rank("soldier_"..id,false)
end
if not self.soldiers[0] then
self:append(0)
self.soldiers[0].first_record = timetool:get_next_time(timetool:now(),self.update_time)
self.db:update(self.soldiers[0])
end
return true
end
function _M:append(soldier_id)
if not self.soldiers[soldier_id] then
local v = {}
v.soldier_id = soldier_id
v.first_record = 0
v.second_record = 0
v.third_record = 0
self.db:append(v)
self.soldiers[soldier_id] = v
end
end
function _M:record_first(soldier_id,role_id)
self:append(soldier_id)
if self.soldiers[soldier_id].first_record ~= 0 then return false end
self.soldiers[soldier_id].first_record = role_id
self.db:update(self.soldiers[soldier_id])
return true
end
function _M:record_second(soldier_id,role_id)
self:append(soldier_id)
if self.soldiers[soldier_id].second_record ~= 0 then return false end
self.soldiers[soldier_id].second_record = role_id
self.db:update(self.soldiers[soldier_id])
return true
end
function _M:record_third(soldier_id,role_id)
self:append(soldier_id)
if self.soldiers[soldier_id].third_record ~= 0 then return false end
self.soldiers[soldier_id].third_record = role_id
self.db:update(self.soldiers[soldier_id])
return true
end
function _M:record(soldier_id,pos,role_id)
if pos == 1 then return self:record_first(soldier_id,role_id)
elseif pos == 2 then return self:record_second(soldier_id,role_id)
elseif pos == 3 then return self:record_third(soldier_id,role_id)
end
end
function _M:save()
self.db:clean(true)
end
function _M:get_soldier_can_record_pos(soldier_id,role_id)
self:append(soldier_id)
local index = false
if self.soldiers[soldier_id].first_record == 0 then index = 1
elseif self.soldiers[soldier_id].second_record == 0 then index = 2
elseif self.soldiers[soldier_id].third_record == 0 then index = 3
end
if index then
if self.soldiers[soldier_id].first_record ~= role_id and self.soldiers[soldier_id].second_record ~= role_id and self.soldiers[soldier_id].third_record ~= role_id then
return index end
end
return false
end
function _M:get_soldier_info(soldier_id)
self:append(soldier_id)
local info = {}
info.id = soldier_id
info.first = roleMgr:get_role_name(self.soldiers[soldier_id].first_record)
info.second = roleMgr:get_role_name(self.soldiers[soldier_id].second_record)
info.third = roleMgr:get_role_name(self.soldiers[soldier_id].third_record)
return info
end
function _M:send()
local ct = timetool:now()
local nt = self.soldiers[0].first_record
if nt < ct then
for id,v in pairs(config.template.hero) do
local rank_type = "soldier_" .. id
local rank = rankMgr:get(rank_type)
if rank then
local ids = rank:get_range_ids(1,5)
for i,rid in ipairs(ids) do
local role = roleMgr:get_role(rid)
if role then
local soldier = role.soldiers:get(id)
if soldier then soldier:get_badge(nt) end
end
end
end
end
nt = timetool:get_next_time(nt,self.update_time)
self.soldiers[0].first_record = nt
self.db:update(self.soldiers[0])
end
end
return _M |
EditorConsole = EditorConsole or class(EditorPart)
function EditorConsole:init(parent, menu)
self._parent = parent
self._options_menu = menu:Menu({
name = "console_options",
background_color = BeardLibEditor.Options:GetValue("BackgroundColor"),
auto_height = true,
offset = 0,
layer = 999,
items_size = 18,
position = "TopLeft",
scrollbar = false,
visible = false,
align_method = "grid",
})
self._menu = menu:Menu({
name = "console_output",
h = 400,
layer = 999,
size_by_text = true,
override_size_limit = true,
should_scroll_down = true,
visible = false,
position = function(item)
item:Panel():set_position(self._options_menu:Panel():leftbottom())
end,
background_color = BeardLibEditor.Options:GetValue("BackgroundColor"),
})
ItemExt:add_funcs(self, self._options_menu)
local opt = {border_bottom = true, text_align = "center", border_size = 1, border_color = BeardLibEditor.Options:GetValue("AccentColor"), w = self._options_menu.w / 5}
self:button("Close", ClassClbk(self, "ToggleConsole"), opt)
self:button("Clear", ClassClbk(self, "Clear"), table.merge(opt, {border_color = Color("ffc300")}))
self.info_log = self:tickbox("Info", ClassClbk(self, "FilterConsole"), true, table.merge(opt, {border_color = Color.yellow}))
self.mission_log = self:tickbox("Mission", ClassClbk(self, "FilterConsole"), false, table.merge(opt, {border_color = Color.green}))
self.error_log = self:tickbox("Errors", ClassClbk(self, "FilterConsole"), true, table.merge(opt, {border_color = Color.red}))
ItemExt:add_funcs(self)
self:Clear()
self.closed = true
self._triggers = {}
end
function EditorConsole:ToggleConsole()
self.closed = not self.closed
self._options_menu:SetVisible(not self.closed)
self._menu:SetVisible(not self.closed)
end
function EditorConsole:PrintMessage(type, message, ...)
message = message:format(...)
local date = Application:date("%X")
self:divider(date .. ": " .. tostring(message), {type = type, visible = self[type]:Value(), border_color = type == "mission" and Color.green or type == "error" and Color.red or Color.yellow})
if #self._menu._my_items > 100 then --hardcoded for now
self:RemoveItem(self._menu._my_items[1])
end
if self._menu.items_panel:h() > self._menu.panel:h() and not self._menu._grabbed_scroll_bar then
self._menu.items_panel:set_bottom(self._menu.items_panel:parent():h())
self._menu:CheckItems()
self._menu._scroll:_check_scroll_indicator_states()
end
end
function EditorConsole:FilterConsole(item)
for _, item in pairs(self._menu._my_items) do
item:SetVisible(self[item.type]:Value())
end
end
function EditorConsole:Log(msg, ...) self:PrintMessage("info_log", msg, ...) end
function EditorConsole:LogMission(msg, ...) self:PrintMessage("mission_log", msg, ...) end
function EditorConsole:Error(msg, ...) self:PrintMessage("error_log", msg, ...) end
function EditorConsole:Clear() self:ClearItems() end
function EditorConsole:disable()
EditorConsole.super.disable(self)
self._enabled = false
end
function EditorConsole:enable()
EditorConsole.super.enable(self)
self:bind_opt("ToggleConsole", ClassClbk(self, "ToggleConsole"))
self._enabled = true
end |
local class = require "xgame.class"
local assert = assert
local next = next
local pairs = pairs
local tostring = tostring
local ANONYMOUS = {}
local hashlist = {}
local Dispatcher = class("Dispatcher")
function Dispatcher:ctor()
self._listeners = {}
end
function Dispatcher:addListener(event, listener, owner, priority)
assert(event, "no event")
assert(listener, "no listener")
local list = self._listeners[event]
if not list then
list = hashlist.new()
self._listeners[event] = list
end
list:insert(owner or ANONYMOUS, listener, priority)
end
function Dispatcher:removeListener(event, listener, owner)
assert(event, "no event")
assert(listener, "no listener")
local list = self._listeners[event]
if list then
list:remove(owner or ANONYMOUS, listener)
if list:empty() then
self._listeners[event] = nil
end
end
end
function Dispatcher:dispatch(event, ...)
assert(event, "no event")
if self:hasListener(event) then
for _, owner, listener in pairs(self._listeners[event]) do
if owner == ANONYMOUS then
listener(self, ...)
else
listener(owner, self, ...)
end
end
end
end
function Dispatcher:hasListener(event)
return self._listeners[event] ~= nil
end
--
-- hashlist
--
hashlist.__index = hashlist
local function makeindex(owner, handler)
return tostring(owner) .. "|" .. tostring(handler)
end
function hashlist.new()
local self = setmetatable({}, hashlist)
self.header = {}
self.header.next = self.header
self.header.prev = self.header
self.entries = {}
return self
end
local function itor(header, current)
local entry = current.next
if entry ~= header then
return entry, entry.key, entry.value
end
end
function hashlist:__pairs()
return itor, self.header, self.header
end
function hashlist:insert(key, value, priority)
local idx = makeindex(key, value)
if self.entries[idx] then
return
end
local entry = {key = key, value = value, priority = priority}
local header, current = self.header
if not priority then
current = header.prev
else
current = header
local next = current.next
while next ~= header do
if not next.priority or priority > next.priority then
break
else
current = next
next = current.next
end
end
end
entry.next = current.next
entry.prev = current
current.next.prev = entry
current.next = entry
self.entries[idx] = entry
end
function hashlist:empty()
return next(self.entries) == nil
end
function hashlist:remove(key, value)
local idx = makeindex(key, value)
local entry = self.entries[idx]
if entry then
entry.prev.next = entry.next
entry.next.prev = entry.prev
self.entries[idx] = nil
end
end
return Dispatcher
|
--[[
____________________________________________________________________________________________________________________________________________________________________________
@CloneTrooper1019, 2014-,2015 <3
(Some code provided by Mark Langen, also known as stravant)
This module comes with API for controlling 3D to 2D.
PLEASE NOTE:
The API assumes there is nothing in front of the model being displayed
(whether its a GUI, or anything in the workspace)
____________________________________________________________________________________________________________________________________________________________________________
API DETAILS
____________________________________________________________________________________________________________________________________________________________________________
* Module3D:Attach3D(Instance guiObj, Instance model, bool useExtentsSize = false)
Description:
* Attaches a part/model to the center of the gui object specified.
* Can have its offset changed as well as its active state. By default the model is hidden, and you need to call SetActive onto it manually
Arguments:
* Instance guiObj
- guiObj must be any kind of Gui object that contains a "Position" property, such as a Frame, ImageLabel, etc.
* Instance model
- model can be either a Model, or a BasePart (Part, Wedge, Truss, etc).
* bool useExtents = false
- Whether or not the module should calculate the bounds of the model using Model:GetExtentsSize() or Model:GetModelSize()
- This argument is optional, and excluding it will set it to false
- See these wiki pages to know the difference:
* http://wiki.roblox.com/index.php?title=API:Class/Model/GetModelSize
* http://wiki.roblox.com/index.php?title=API:Class/Model/GetExtentsSize
Returns:
* Controller
- This is a small library representing the 3D model. It has a few functions and one property.
* Controller:SetActive(boolean active)
- Toggles whether or not the 3D Object should be shown or not
* Controller:SetOffset(CoordinateFrame Offset)
- Sets a CFrame offset from the location its trying to place the 3D Model.
- Note that by default, it sets the CFrame a blank CFrame.new()
* Controller:SetCFrame(CoordinateFrame Offset) [deprecated]
- Does the same thing as SetOffset,
- This only exists for compatability with older versions and should not be used.
* Controller:End()
- Effectively removes the model and disconnects its movement events.
* Controller.Object3D
- The current model being used.
Example Code:
----------------------------------------------------------------------------------------------------------
local self = script.Parent
local frame = self:WaitForChild("Frame")
local module3D = require(self:WaitForChild("Module3D"))
local model = workspace:WaitForChild("Guy")
local activeModel = handler:Attach3D(frame,model)
activeModel:SetActive(true)
activeModel:SetCFrame(CFrame.Angles(0,math.pi,0))
----------------------------------------------------------------------------------------------------------
____________________________________________________________________________________________________________________________________________________________________________
* Module3D:AnimAttach3D( BasePart rootPart, GuiObject guiObj )
Description:
* This functions almost identical to the Attach3D function, however there are some important differences.
* The model is not cloned, instead it is inputted directly. So if you want to reuse the source model, make sure you clone it prior.
* It expects that all parts are connected with Motor6D, and will not do any welding unlike Attach3D
* The argument SHOULD be the RootPart for the animation (so if you are using a character it should be the HumanoidRootPart)
* The Controller class which is returned also has a LoadAnimation function which returns an AnimationTrack to be played on the model.
____________________________________________________________________________________________________________________________________________________________________________
* Module3d:AdornScreenGuiToWorld(Instance screenGui, number depth = 1)
Description:
* This function takes a ScreenGui, and turns it into a BillboardGui
* The BillboardGui is adorned to a part which mirrors the CFrame of the Camera,
and applies a forward offset to the BillboardGui based on the depth value.
Arguments:
* Instance screenGui
- guiObj must be a ScreenGui. If you only need to do this with one frame, its reccomended you just make the entire ScreenGui an adorn.
* number depth = 1
- How many studs in front of the camera the GUI will be.
- This argument is optional, and excluding it will set it to 1.
Returns:
* Instance SurfaceGui
- This is the SurfaceGui version of your ScreenGui.
* 3dGuiModifier
- This is a small library with 2 functions. It allows you to change the depth of the WorldGui, and reset it back to a ScreenGui.
* 3dController:SetDepth(number depth)
- Sets a new depth value.
* 3dGuiModifier:Reset()
- Returns the ScreenGui to its former state, Destroys the old BillboardGui, and disconnects the movement event.
Example Code:
local oldGui = script.Parent
local module3D = require(oldGui:WaitForChild("Module3D"))
local newGui,modifier = handler:AdornScreenGuiToWorld(screenGui,3)
print(oldGui.Parent,newGui.Parent)
wait(1)
modifier:SetDepth(2)
wait(1)
modifier:Reset()
print(oldGui.Parent,newGui.Parent)
----------------------------------------------------------------------------------------------------------
Notes:
* BillboardGuis can't receive input properly on mobile devices.
I advice only using this method for backdrops instead of interactive elements.
____________________________________________________________________________________________________________________________________________________________________________ --]]
local moduleAPI = {}
local c = workspace.CurrentCamera
local player = game.Players.LocalPlayer
local rs = game:GetService("RunService")
local argTemp = "Argument #%d"
local shouldTemp = "%s should be %s (not %s)"
local function vowel(name)
local vowels = "aeiou"
local char = name:match(".")
if not string.sub(name,1,2) == "us" then
for vowel in vowels:gmatch(".") do
if char == vowel and string.sub(name,1,2) ~= "us" then
return "an '"..name.."'"
end
end
end
return "a "..name
end
local function checkArgs(args)
local arg = 1
for var,check in pairs(args) do
local s = argTemp:format(arg)
assert(var ~= nil, s.." missing or nil")
local valueType = type(var)
if type(check) == "function" then
local isValid,argumentType = check(var)
assert(isValid, shouldTemp:format(s, vowel(argumentType), vowel(valueType)))
else
assert(valueType == check, shouldTemp:format(s, vowel(check), vowel(valueType)))
end
arg = arg + 1
end
end
local function getDepthForWidth(partWidth, visibleSize)
local resolution = c.ViewportSize
local aspectRatio = resolution.X / resolution.Y
local hfactor = math.tan(math.rad(c.FieldOfView)/2)
local wfactor = aspectRatio*hfactor
return -(-0.5*resolution.X*partWidth/(visibleSize*wfactor))
end
function moduleAPI:Attach3D(guiObj,model,useExtentsSize)
checkArgs
{
[guiObj] = function ()
return guiObj:IsA("GuiObject"), "GuiObject"
end;
[model] = function ()
return (model:IsA("Model") or model:IsA("BasePart")),"Model or BasePart"
end
}
-- Create our 3D Model
local m = Instance.new("Model")
m.Name = model.Name.."_3D"
m.Parent = c
-- Gather up and tweak the parts.
local parts = {}
if model:IsA("BasePart") then
local this = model:clone()
this.Parent = m
table.insert(parts,this)
else
local function recurse(obj)
for _,v in pairs(obj:GetChildren()) do
local part do
if v:IsA("BasePart") then
part = v:clone()
elseif v:IsA("Hat") and v:findFirstChild("Handle") then
part = v.Handle:clone()
end
end
if part then
local cf = part.CFrame
part.Parent = m
part.CFrame = cf
if part.Name == "Head" then
part.Name = "head"
end
table.insert(parts,part)
elseif not v:IsA("Model") and not v:IsA("Sound") and not v:IsA("Script") then
v:clone().Parent = m
else
recurse(v)
end
end
end
recurse(model)
end
-- Create a primary center part for our model.
local extents = (useExtentsSize and m:GetExtentsSize() or m:GetModelSize())
local maxExtent = math.max(extents.X,extents.Y,extents.Z) * 1.2
local primary = Instance.new("Part")
primary.Anchored = true
primary.Transparency = 1
primary.CanCollide = false
primary.Name = "Centroid"
primary.FormFactor = "Custom"
primary.Size = extents
primary.CFrame = CFrame.new(m:GetModelCFrame().p)
primary.Parent = m
m.PrimaryPart = primary
-- Weld the parts in our model to our primary part.
for _,v in pairs(parts) do
v.Anchored = false
v.CanCollide = false
local w = Instance.new("Weld")
w.Part0 = primary
w.Part1 = v
w.C0 = primary.CFrame:toObjectSpace(v.CFrame)
w.Parent = primary
end
-- Hook up the code for CFraming the model in 3D space.
local cf = CFrame.new()
local active = false
local lib = {}
lib.Object3D = m
function lib:SetActive(b)
checkArgs{[b] = "boolean"}
active = b
end
function lib:SetOffset(newCF)
checkArgs{[newCF] = function ()
local isCFrame = pcall(function () return newCF:components() end)
return isCFrame,"CFrame"
end}
cf = newCF
end
function lib:SetCFrame(newCF)
lib:SetOffset(newCF)
end
function lib:GetDepth()
local size = math.min(guiObj.AbsoluteSize.X, guiObj.AbsoluteSize.Y)
return getDepthForWidth(maxExtent, size)
end
function lib:GetDepthForBackdrop()
local depth = lib:GetDepth()
return depth + maxExtent
end
local nowhere = CFrame.new(99999,99999,99999)
local function updateModel()
local nextCF = nowhere
if active then
local camCF = c.CoordinateFrame
local sizeX,sizeY = guiObj.AbsoluteSize.X, guiObj.AbsoluteSize.Y
local posX,posY = guiObj.AbsolutePosition.X + (sizeX / 2), guiObj.AbsolutePosition.Y + (sizeY / 2)
local posZ = lib:GetDepth()
nextCF = CFrame.new(c:ScreenPointToRay(posX,posY,posZ).Origin) * (camCF-camCF.p) * cf
end
primary.Anchored = false
primary.CFrame = nextCF
primary.Anchored = true
end
local con = rs.RenderStepped:connect(updateModel)
function lib:End()
con:disconnect()
m:Destroy()
end
return lib
end
function moduleAPI:AdornScreenGuiToWorld(screenGui,depth)
checkArgs
{
[screenGui] = function ()
return (screenGui:IsA("ScreenGui") or screenGui:IsA("BillboardGui")) or false,"ScreenGui or BillboardGui"
end
}
local depth = type(depth) == "number" and depth or 1
local s = Instance.new("BillboardGui",screenGui.Parent)
s.Name = screenGui.Name
local adorn = Instance.new("Part",s)
adorn.Name = screenGui.Name.."_Adornee"
adorn.FormFactor = "Custom"
adorn.Anchored = true
adorn.CanCollide = false
adorn.Size = Vector3.new()
adorn.Transparency = 1
adorn.Locked = true
local con
local modifier = {}
function modifier:SetDepth(n)
checkArgs(n,"number")
depth = n
end
function modifier:Reset()
screenGui.Parent = s.Parent
for _,v in pairs(s:GetChildren()) do
v.Parent = screenGui
end
con:disconnect()
adorn:Destroy()
s:Destroy()
end
local function updateAdorn()
local success,did = pcall(function ()
local res = c.ViewportSize
adorn.CFrame = c.CoordinateFrame
s.Size = UDim2.new(0,res.X,0,res.Y)
s.StudsOffset = Vector3.new(0,0,-depth)
return true
end)
if not success or not did then
warn(script:GetFullName()..": The adornee was destroyed! The gui has been reset.")
modifier:Reset()
end
end
con = rs.RenderStepped:connect(updateAdorn)
s.Adornee = adorn
for _,v in pairs(screenGui:GetChildren()) do
v.Parent = s
end
screenGui.Parent = nil
return s,modifier
end
function moduleAPI:AnimAttach3D(rootPart,guiObj)
checkArgs
{
[rootPart] = function ()
return rootPart:IsA("BasePart") or false,"BasePart"
end;
[guiObj] = function ()
return guiObj:IsA("GuiObject") or false,"GuiObject"
end;
}
local model = rootPart.Parent
assert(model and model:IsA("Model"),"rootPart.Parent should be a Model")
local animator = model:FindFirstChild("AnimationController")
if not animator then
animator = Instance.new("AnimationController",model)
end
model.PrimaryPart = rootPart
local cf = CFrame.new()
local active = false
local maxExtent = model:GetModelSize().magnitude
local lib = {}
lib.Object3D = model
model.Parent = c
function lib:SetActive(b)
checkArgs{[b] = "boolean"}
active = b
end
function lib:SetOffset(newCF)
checkArgs
{
[newCF] = function ()
local isCFrame = pcall(function () return newCF:components() end)
return isCFrame,"CFrame"
end
}
cf = newCF
end
function lib:SetCFrame(newCF)
lib:SetOffset(newCF)
end
function lib:GetDepth()
local size = math.min(guiObj.AbsoluteSize.X, guiObj.AbsoluteSize.Y)
return getDepthForWidth(maxExtent, size)
end
function lib:LoadAnimation(anim)
checkArgs
{
[anim] = function ()
return anim:IsA("Animation") or false,"Animation"
end
}
return animator:LoadAnimation(anim)
end
local nowhere = CFrame.new(99999,99999,99999)
local function updateModel()
local nextCF = nowhere
if active then
local camCF = c.CoordinateFrame
local sizeX,sizeY = guiObj.AbsoluteSize.X, guiObj.AbsoluteSize.Y
local posX,posY = guiObj.AbsolutePosition.X + (sizeX / 2), guiObj.AbsolutePosition.Y + (sizeY / 2)
local posZ = lib:GetDepth()
nextCF = CFrame.new(c:ScreenPointToRay(posX,posY,posZ).Origin) * (camCF-camCF.p) * cf
end
model.PrimaryPart = rootPart
rootPart.Anchored = true
model:SetPrimaryPartCFrame(nextCF)
end
local con = rs.RenderStepped:connect(updateModel)
function lib:End()
con:disconnect()
end
return lib
end
return moduleAPI |
iterate = dofile('utils.lua').iterate
test_run = require('test_run').new()
test_run:cmd("push filter '(error: .builtin/.*[.]lua):[0-9]+' to '\\1'")
# Tree single-part unique
space = box.schema.space.create('tweedledum')
idx1 = space:create_index('primary', { type = 'tree', parts = {1, 'string'}, unique = true})
-- Hash single-part unique
idx5 = space:create_index('i4', { type = 'hash', parts = {1, 'string'}, unique = true})
-- Hash multi-part unique
idx6 = space:create_index('i5', { type = 'hash', parts = {2, 'string', 3, 'string'}, unique = true})
space:insert{'pid_001', 'sid_001', 'tid_998', 'a'}
space:insert{'pid_002', 'sid_001', 'tid_997', 'a'}
space:insert{'pid_003', 'sid_002', 'tid_997', 'b'}
space:insert{'pid_005', 'sid_002', 'tid_996', 'b'}
space:insert{'pid_007', 'sid_003', 'tid_996', 'a'}
space:insert{'pid_011', 'sid_004', 'tid_996', 'c'}
space:insert{'pid_013', 'sid_005', 'tid_996', 'b'}
space:insert{'pid_017', 'sid_006', 'tid_996', 'a'}
space:insert{'pid_019', 'sid_005', 'tid_995', 'a'}
space:insert{'pid_023', 'sid_005', 'tid_994', 'a'}
-------------------------------------------------------------------------------
-- Iterator: hash single-part unique
-------------------------------------------------------------------------------
iterate('tweedledum', 'i4', 0, 1)
iterate('tweedledum', 'i4', 0, 1, box.index.ALL)
iterate('tweedledum', 'i4', 0, 1, box.index.EQ)
iterate('tweedledum', 'i4', 0, 1, box.index.EQ, 'pid_003')
iterate('tweedledum', 'i4', 0, 1, box.index.EQ, 'pid_666')
-------------------------------------------------------------------------------
-- Iterator: hash multi-part unique
-------------------------------------------------------------------------------
iterate('tweedledum', 'i5', 1, 3, box.index.ALL)
iterate('tweedledum', 'i5', 1, 3, box.index.EQ, 'sid_005')
iterate('tweedledum', 'i5', 1, 3, box.index.EQ, 'sid_005', 'tid_995')
iterate('tweedledum', 'i5', 1, 3, box.index.EQ, 'sid_005', 'tid_999')
iterate('tweedledum', 'i5', 1, 3, box.index.EQ, 'sid_005', 'tid_995', 'a')
space:drop()
-------------------------------------------------------------------------------
-- Iterator: https://github.com/tarantool/tarantool/issues/464
-- Iterator safety after changing schema
-------------------------------------------------------------------------------
space = box.schema.space.create('test', {temporary=true})
idx1 = space:create_index('primary', {type='HASH',unique=true})
idx2 = space:create_index('t1', {type='TREE',unique=true})
idx3 = space:create_index('t2', {type='TREE',unique=true})
box.space.test:insert{0}
box.space.test:insert{1}
gen1, param1, state1 = space.index.t1:pairs({}, {iterator = box.index.ALL})
gen1(param1, state1)
gen2, param2, state2 = space.index.t2:pairs({}, {iterator = box.index.ALL})
gen2(param2, state2)
id = space.index.t1.id
box.schema.index.drop(space.id, id)
gen1(param1, state1)
gen2(param2, state2)
gen2, param2, state2 = space.index.t2:pairs({}, {iterator = box.index.ALL})
gen2(param2, state2)
gen2(param2, state2)
space:drop()
-------------------------------------------------------------------------------
-- Iterator: https://github.com/tarantool/tarantool/issues/498
-- Iterator is not checked for wrong type; accept lowercase iterator
-------------------------------------------------------------------------------
space = box.schema.space.create('test', {temporary=true})
idx1 = space:create_index('primary', {type='TREE',unique=true})
space:insert{0}
space:insert{1}
gen, param, state = space.index.primary:pairs({}, {iterator = 'ALL'})
gen(param, state)
gen(param, state)
gen(param, state)
gen, param, state = space.index.primary:pairs({}, {iterator = 'all'})
gen(param, state)
gen(param, state)
gen, param, state = space.index.primary:pairs({}, {iterator = 'mistake'})
space:select({}, {iterator = box.index.ALL})
space:select({}, {iterator = 'all'})
space:select({}, {iterator = 'mistake'})
space:drop()
-------------------------------------------------------------------------------
-- Restore GE iterator for HASH https://github.com/tarantool/tarantool/issues/836
-------------------------------------------------------------------------------
space = box.schema.space.create('test', {temporary=true})
idx1 = space:create_index('primary', {type='hash',unique=true})
for i = 0,5 do space:insert{i} end
space:select(2)
space:select(5, {iterator="GE"})
space:select(nil, {iterator="GE"})
space:select(5, {iterator="GT"})
l = space:select(nil, {limit=2, iterator="GT"})
l
l = space:select(l[#l][1], {limit=2, iterator="GT"})
l
l = space:select(l[#l][1], {limit=2, iterator="GT"})
l
l = space:select(l[#l][1], {limit=2, iterator="GT"})
l
space:drop()
iterate = nil
|
local cjson = require "cjson"
local fernet = require "resty.fernet"
local function readfile(path)
local file = io.open(path, "rb")
if not file then return nil end
local content = file:read("*a")
file:close()
return content
end
local function parse_time(ts)
local pattern = "(%d+)-(%d+)-(%d+)T(%d+):(%d+):(%d+)([+-])(%d+):(%d+)"
local year, month, day, hour, min, sec, tz_dir, tz_hours, _ = string.match(ts, pattern)
local now = os.time({ year=year, month=month, day=day, hour=hour, min=min, sec=sec })
if tz_dir == "+" then
tz_hours = 0 - tz_hours
end
return now + 3600 * tz_hours
end
local total = 0
local failing = 0
local function pass(msg)
total = total + 1
print("\27[32m" .. msg .. "\27[39m")
end
local function fail(msg)
total = total + 1
failing = failing + 1
print("\27[31m" .. msg .. "\27[39m")
end
local function review(msg)
total = total + 1
print("\27[33m" .. msg .. "\27[39m")
end
local function test_generate(case)
local f = fernet:new(case.secret)
local iv = ""
for _, b in ipairs(case.iv) do
iv = iv .. string.char(b)
end
f._time = function(self) return parse_time(case.now) end
f._iv = function(self) return iv end
local token, err = f:encrypt(case.src)
if err then
return err
end
if token ~= case.token then
return "expected " .. case.token .. ", got " .. token
end
return nil
end
local function test_verify(case)
local f = fernet:new(case.secret)
f._time = function(self) return parse_time(case.now) end
local src, err = f:decrypt(case.token, case.ttl_sec)
if err then return err end
if case.src and src ~= case.src then
return "expected " .. case.src .. ", got " .. src
end
return nil
end
local generate = cjson.decode(assert(readfile("spec/generate.json")))
for _, case in pairs(generate) do
local err = test_generate(case)
if err then
fail("generate test failed: " .. err)
else
pass("generate test passed")
end
end
local verify = cjson.decode(assert(readfile("spec/verify.json")))
for _, case in pairs(verify) do
local err = test_verify(case)
if err then
fail("verify test failed: " .. err)
else
pass("verify test passed")
end
end
local invalid = cjson.decode(assert(readfile("spec/invalid.json")))
for _, case in pairs(invalid) do
print("negative test '" .. case.desc .. "':")
local ok, value = pcall(function () return test_verify(case) end)
if ok then
if value then
review(" review expected error '" .. value .. "'")
else
fail(" should have returned an error, but did not")
end
else
fail(" failed with uncaught error: " .. value)
end
end
print(string.format("%d test ran - %d failures", total, failing))
|
--[=[
MIT License
Copyright (c) 2016 Johannes Westhuis, Alexander Schulz
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.
]=]--
--pack
local luagi = require("luagi")
local test_helper = require("test_helper")
describe( "new_packbuilder #pack", function()
local repo = nil
local err = nil
local pack = nil
setup( function()
test_helper.setup()
repo, err = luagi.open( test_helper.path )
if err then return end
pack, err = repo:new_packbuilder()
end)
it("should not have an error", function()
assert.is.falsy( err )
assert.is.not_nil( pack )
assert.is.not_nil( pack.insert_tree )
end)
describe( "set_threads #pack", function()
it("should set the right amount", function()
assert.are.equal( 1, pack:set_threads( 1 ) )
assert.are.equal( 1100, pack:set_threads( 1100 ) )
assert.are.equal( 0, pack:set_threads( 0 ) )
end)
end)
describe( "count #pack", function()
it("should be zero", function()
assert.are.equal( 0, pack:count() )
end)
end)
describe( "write #pack", function()
it("should be zero", function()
local pstr = pack:write()
local s, e = pstr:find( "PAC" )
assert.are.equal( 1, s )
assert.are.equal( 3, e )
assert.are.equal( 32, #pstr )
end)
end)
describe( "hash #pack", function()
it("should be zero", function()
assert.are.equal( "0000000000000000000000000000000000000000", pack:hash() )
end)
end)
describe( "written #pack", function()
it("should be zero", function()
assert.are.equal( 0, pack:written() )
end)
end)
end)
describe( "insert #pack", function()
local repo = nil
local err = nil
local pack = nil
local id = "4aa7714edd19d6c8a0ccfb9a2d8650e69ae2bd09"
setup( function()
test_helper.setup()
repo, err = luagi.open( test_helper.path )
if err then return end
pack, err = repo:new_packbuilder()
if err then return end
pack:insert( id, "commit" )
end)
it("should not have an error", function()
assert.is.falsy( err )
assert.is.not_nil( pack )
assert.is.not_nil( pack.insert_tree )
end)
describe( "count #pack", function()
it("should be zero", function()
assert.are.equal( 1, pack:count() )
end)
end)
describe( "write #pack", function()
it("should be zero", function()
local pstr = pack:write()
local s, e = pstr:find( "PAC" )
assert.are.equal( 1, s )
assert.are.equal( 3, e )
assert.are.equal( 199, #pstr )
end)
end)
describe( "hash #pack", function()
it("should be zero", function()
assert.are.equal( "0000000000000000000000000000000000000000", pack:hash() )
end)
end)
describe( "written #pack", function()
it("should be zero", function()
assert.are.equal( 1, pack:written() )
end)
end)
end)
describe( "insert_tree #pack", function()
local id = "064ee3e735ab74ab468be05c34e7f7fda011cb3b"
local repo = nil
local err = nil
local pack = nil
setup( function()
test_helper.setup()
repo, err = luagi.open( test_helper.path )
if err then return end
pack, err = repo:new_packbuilder()
if err then return end
pack:insert_tree( id )
end)
it("should not have an error", function()
assert.is.falsy( err )
assert.is.not_nil( pack )
assert.is.not_nil( pack.insert_tree )
end)
describe( "count #pack", function()
it("should be zero", function()
assert.are.equal( 3, pack:count() )
end)
end)
describe( "write #pack", function()
it("should be zero", function()
local pstr = pack:write()
local s, e = pstr:find( "PAC" )
assert.are.equal( 1, s )
assert.are.equal( 3, e )
assert.are.equal( 145, #pstr )
end)
end)
describe( "hash #pack", function()
it("should be zero", function()
assert.are.equal( "0000000000000000000000000000000000000000", pack:hash() )
end)
end)
describe( "written #pack", function()
it("should be zero", function()
assert.are.equal( 3, pack:written() )
end)
end)
end)
describe( "insert_commit #pack", function()
local repo = nil
local err = nil
local pack = nil
local id = "4aa7714edd19d6c8a0ccfb9a2d8650e69ae2bd09"
setup( function()
test_helper.setup()
repo, err = luagi.open( test_helper.path )
if err then return end
pack, err = repo:new_packbuilder()
if err then return end
pack:insert_commit( id )
end)
it("should not have an error", function()
assert.is.falsy( err )
assert.is.not_nil( pack )
assert.is.not_nil( pack.insert_tree )
end)
describe( "count #pack", function()
it("should be zero", function()
assert.are.equal( 7, pack:count() )
end)
end)
describe( "write #pack", function()
it("should be zero", function()
local pstr = pack:write()
local s, e = pstr:find( "PAC" )
assert.are.equal( 1, s )
assert.are.equal( 3, e )
assert.are.equal( 457, #pstr )
end)
end)
describe( "hash #pack", function()
it("should be zero", function()
assert.are.equal( "0000000000000000000000000000000000000000", pack:hash() )
end)
end)
describe( "written #pack", function()
it("should be zero", function()
assert.are.equal( 7, pack:written() )
end)
end)
end)
describe( "write_file #pack", function()
local repo = nil
local err = nil
local pack = nil
local id = "4aa7714edd19d6c8a0ccfb9a2d8650e69ae2bd09"
setup( function()
test_helper.setup()
repo, err = luagi.open( test_helper.path )
if err then return end
pack, err = repo:new_packbuilder()
if err then return end
pack:insert_commit( id )
pack:write_file( test_helper.extract_path )
end)
it("should not have an error", function()
assert.is.falsy( err )
assert.is.not_nil( pack )
assert.is.not_nil( pack.insert_tree )
end)
describe( "count #pack", function()
it("should be zero", function()
assert.are.equal( 7, pack:count() )
end)
end)
describe( "write #pack", function()
it("should be zero", function()
local pstr = pack:write()
local s, e = pstr:find( "PAC" )
assert.are.equal( 1, s )
assert.are.equal( 3, e )
assert.are.equal( 32, #pstr )
end)
end)
describe( "hash #pack", function()
it("should be zero", function()
assert.are.equal( "1811f0739e5ef2777866e93a6f75bd33442613ea", pack:hash() )
end)
end)
describe( "written #pack", function()
it("should be zero", function()
assert.are.equal( 0, pack:written() )
end)
end)
describe( "foreach #pack", function()
local count = 0
local sum = 0
local function f( msg )
sum = sum + #msg
count = count + 1
end
pack:foreach( f )
assert.are.equal( 2, count )
assert.are.equal( 32, sum )
end)
end)
describe( "set_callbacks #pack", function() pending("luagi_packbuilder_set_callbacks ") end)
|
---------------------------------------------------------------
-- Widget tracking
---------------------------------------------------------------
-- Used to track and bind interface widgets to the controller.
-- Necessary since widgets might be created at a later time.
local widgetTrackers, IsFrameWidget = {}, C_Widget.IsFrameWidget
local function CheckWidgetTrackers(self)
if not InCombatLockdown() then
for button, widget in pairs(widgetTrackers) do
if IsFrameWidget(_G[widget]) then
self:LoadInterfaceBinding(button, widget)
widgetTrackers[button] = nil
end
end
if not next(widgetTrackers) then
self:RemoveUpdateSnippet(CheckWidgetTrackers)
end
end
end
function ConsolePort:AddWidgetTracker(button, action)
widgetTrackers[button] = action
self:AddUpdateSnippet(CheckWidgetTrackers)
end
---------------------------------------------------------------
-- Frame tracking
---------------------------------------------------------------
-- Used to track and bind addon frames to the UI cursor.
-- Necessary since all frames do not exist on ADDON_LOADED.
-- Automatically adds all special frames, i.e. closed with ESC.
local specialFrames, frameTrackers = {}, {}
local function CheckSpecialFrames(self)
local frames = UISpecialFrames
for i, frame in pairs(frames) do
if not specialFrames[frame] then
if self:AddFrame(frame) then
specialFrames[frame] = true
end
end
end
end
function ConsolePort:UpdateFrameTracker()
CheckSpecialFrames(self)
for frame in pairs(frameTrackers) do
if self:AddFrame(frame) then
frameTrackers[frame] = nil
end
end
end
function ConsolePort:AddFrameTracker(frame)
frameTrackers[frame] = true
end
---------------------------------------------------------------
-- Action button / action bar caching
---------------------------------------------------------------
-- Used to find action bars and action buttons from various
-- sources, to extend their hotkey functionality or cache them
-- on handlers for later manipulation.
local IGNORE_FRAMES = {}
local VALID_BUTTON_TYPE = {
Button = true,
CheckButton = true,
}
-- Helpers:
local function GetContainer(this)
local parent = this:GetParent()
return (not parent or parent == UIParent) and this or GetContainer(parent)
end
local function ValidateActionID(this)
return this:IsProtected() and VALID_BUTTON_TYPE[this:GetObjectType()] and this:GetAttribute('action')
end
local function IsActionButton(this, action)
return action and tonumber(action) and this:GetAttribute('type') == 'action'
end
-- Callbacks:
local function CacheActionButton(cache, this, action)
cache[this] = action
return false -- continue when found
end
local function CacheActionBar(cache, this, action)
local container = GetContainer(this)
cache[container] = container:GetName() or tostring(container)
return true -- break when found
end
-- Scanner:
local function FindActionButtons(callback, cache, this, sibling, ...)
if not this or this:IsForbidden() or IGNORE_FRAMES[this] then return cache end
if sibling then FindActionButtons(callback, cache, sibling, ...) end
-------------------------------------
local action = ValidateActionID(this)
if IsActionButton(this, action) and callback(cache, this, action) then
return cache
end
FindActionButtons(callback, cache, this:GetChildren())
return cache
end
---------------------------------------------------------------
-- Get all buttons that look like action buttons
---------------------------------------------------------------
function ConsolePort:GetActionButtons(asTable, parent)
local buttons = FindActionButtons(CacheActionButton, {}, parent or UIParent)
if asTable then return buttons end
return pairs(buttons)
end
---------------------------------------------------------------
-- Get all container frames that look like action bars
---------------------------------------------------------------
function ConsolePort:GetActionBars(asTable, parent)
local bars = FindActionButtons(CacheActionBar, {}, parent or UIParent)
if asTable then return bars end
return pairs(bars)
end
function ConsolePort:SetIgnoreFrameForActionLookup(frame, enabled)
IGNORE_FRAMES[frame] = enabled
end |
--性能测试
--https://github.com/lulersoft/ME
local testui2={}
local this
local gameObject
local transform
local colors={Color.red, Color.yellow, Color.blue, Color.white, Color.black, Color.cyan}
function testui2.Start()
this=testui2.this
gameObject=testui2.gameObject
transform=testui2.transform
this.usingUpdate=false
this.renderer.material.color = colors[math.floor(6 * math.random())]
--this:Invoke("DestoryMe",35)
--35秒后销毁
this:RunCoroutine(WaitForSeconds(35),testui2.DestoryMe,nil)
end
function testui2.Update()
transform:Rotate(0, 5, 0)
this.renderer.material.color = colors[math.floor(6 * math.random())]
end
function testui2.DestoryMe()
GameObject.Destroy(gameObject)
end
return testui2 |
function start (song)
strumLine1Visible = false
end
|
local login_fillInfo=
{
name="login_fillInfo",type=0,typeName="View",time=0,report=0,x=0,y=0,width=1280,height=720,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignTopLeft,
{
name="shiled",type=1,typeName="Image",time=89955743,report=0,x=335,y=205,width=64,height=64,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignTopLeft,file="hall/common/bg_shiled.png"
},
{
name="contentView",type=0,typeName="View",time=89955747,report=0,x=0,y=0,width=800,height=560,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,
{
name="bg",type=1,typeName="Image",time=89955748,report=0,x=0,y=0,width=0,height=0,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignCenter,file="hall/common/popupWindow/popupWindow_bg_55_55_55_55.png",gridLeft=55,gridRight=55,gridTop=55,gridBottom=55
},
{
name="titleBg",type=1,typeName="Image",time=89955749,report=0,x=0,y=-54,width=617,height=190,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTop,file="hall/common/popupWindow/popupWindow_title.png",
{
name="title",type=4,typeName="Text",time=89955750,report=0,x=0,y=-5,width=10,height=50,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=34,textAlign=kAlignCenter,colorRed=255,colorGreen=235,colorBlue=186,string=[[完善个人信息,获取1000银币]]
}
},
{
name="closeBtn",type=2,typeName="Button",time=89955751,report=0,x=-15,y=-15,width=60,height=60,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopRight,file="hall/common/popupWindow/popupWindow_close.png"
},
{
name="avatarsView",type=0,typeName="View",time=89955843,report=0,x=0,y=-10,width=696,height=348,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter
},
{
name="nickView",type=0,typeName="View",time=89955865,report=0,x=0,y=30,width=560,height=75,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottom,
{
name="nickBg",type=1,typeName="Image",time=89956106,report=0,x=0,y=0,width=300,height=75,visible=1,fillParentWidth=0,fillParentHeight=1,nodeAlign=kAlignLeft,file="hall/common/input_bg_l25_r25_t25_b25.png",gridLeft=25,gridRight=25,gridTop=25,gridBottom=25,
{
name="nickEdit",type=0,typeName="EditText",time=94728596,x=10,y=0,width=290,height=75,nodeAlign=kAlignLeft,visible=1,fillParentWidth=0,fillParentHeight=0,string=[[昵称]],fontSize=30,textAlign=kAlignLeft,colorRed=118,colorGreen=72,colorBlue=18
}
},
{
name="confirmBtn",type=2,typeName="Button",time=89955753,report=0,x=0,y=0,width=235,height=85,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignRight,file="hall/common/btns/btn_green_164x89_l25_r25_t25_b25.png",gridLeft=25,gridRight=25,gridTop=25,gridBottom=25,
{
name="name",type=4,typeName="Text",time=89955754,report=0,x=0,y=0,width=10,height=30,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=34,textAlign=kAlignCenter,colorRed=255,colorGreen=250,colorBlue=200,string=[[立即领取]]
}
}
}
}
}
return login_fillInfo; |
--[[**********************************
*
* Multi Theft Auto - Admin Panel
*
* client\main\admin_server.lua
*
* Original File by lil_Toady
*
**************************************]]
aServerTab = {
Weathers = {},
WeatherMax = 255,
glitches = {
QuickReload = 'Quick Reload',
FastMove = 'Fast Move',
FastFire = 'Fast Fire',
CrouchBug = 'Crouch Bug',
HighCloseRangeDamage = 'High Close Range Damage',
HitAnim = 'Hit Anim',
FastSprint = 'Fast Sprint',
BadDrivebyHitBox = 'Bad Driveby Hit Box',
QuickStand = 'Quick Stand'
},
worldproperties = {
HoverCars = 'Hover Cars',
AirCars = 'Air Cars',
ExtraBunny = 'Extra Bunny',
ExtraJump = 'Extra Jump',
RandomFoliage = 'Random Foliage',
SniperMoon = 'Sniper Moon',
ExtraAirResistance = 'Extra Air Resistance',
UnderWorldWarp = 'Under World Warp'
}
}
function aServerTab.Create(tab)
aServerTab.Tab = tab
guiCreateHeader(0.02, 0.015, 0.30, 0.035, "Server info:", true, tab)
aServerTab.Server = guiCreateLabel(0.03, 0.060, 0.40, 0.035, "Server: Unknown", true, tab)
aServerTab.Password = guiCreateLabel(0.03, 0.105, 0.40, 0.035, "Password: None", true, tab)
aServerTab.GameType = guiCreateLabel(0.03, 0.150, 0.40, 0.035, "Game Type: None", true, tab)
aServerTab.MapName = guiCreateLabel(0.03, 0.195, 0.40, 0.035, "Map Name: None", true, tab)
aServerTab.Players = guiCreateLabel(0.03, 0.240, 0.20, 0.035, "Players: 0/0", true, tab)
aServerTab.SetPassword = guiCreateButton(0.42, 0.060, 0.18, 0.04, "Set Password", true, tab, "setpassword")
aServerTab.ResetPassword = guiCreateButton(0.42, 0.105, 0.18, 0.04, "Reset Password", true, tab, "setpassword")
aServerTab.SetGameType = guiCreateButton(0.42, 0.150, 0.18, 0.04, "Set Game Type", true, tab, "setgame")
aServerTab.SetMapName = guiCreateButton(0.42, 0.195, 0.18, 0.04, "Set Map Name", true, tab, "setmap")
aServerTab.Shutdown = guiCreateButton(0.42, 0.240, 0.18, 0.04, "Shutdown", true, tab, "shutdown")
aServerTab.ClearChat = guiCreateButton(0.42, 0.285, 0.18, 0.04, "Clear Chat", true, tab, "clearchat")
guiCreateHeader(0.02, 0.305, 0.30, 0.035, "Server properties:", true, tab)
aServerTab.WeatherCurrent =
guiCreateLabel(
0.03,
0.350,
0.45,
0.035,
"Current Weather: " .. getWeather() .. " (" .. getWeatherNameFromID(getWeather()) .. ")",
true,
tab
)
aServerTab.Weather = guiCreateComboBox(0.35, 0.3425, 0.25, 0.50, "Weather", true, tab)
aServerTab.WeatherSet = guiCreateButton(0.50, 0.395, 0.10, 0.04, "Set", true, tab, "setweather")
aServerTab.WeatherBlend = guiCreateButton(0.35, 0.395, 0.135, 0.04, "Blend", true, tab, "blendweather")
local th, tm = getTime()
aServerTab.TimeCurrent = guiCreateLabel(0.03, 0.440, 0.25, 0.035, "Time: " .. th .. ":" .. tm, true, tab)
aServerTab.TimeH = guiCreateEdit(0.35, 0.440, 0.055, 0.04, "12", true, tab)
aServerTab.TimeM = guiCreateEdit(0.425, 0.440, 0.055, 0.04, "00", true, tab)
guiCreateLabel(0.415, 0.440, 0.05, 0.04, ":", true, tab)
guiEditSetMaxLength(aServerTab.TimeH, 2)
guiEditSetMaxLength(aServerTab.TimeM, 2)
aServerTab.TimeSet = guiCreateButton(0.50, 0.440, 0.10, 0.04, "Set", true, tab, "settime")
aServerTab.GravityCurrent =
guiCreateLabel(0.03, 0.485, 0.28, 0.035, "Gravitation: " .. string.format("%.3f", getGravity()), true, tab)
aServerTab.Gravity = guiCreateEdit(0.35, 0.485, 0.135, 0.04, "0.008", true, tab)
aServerTab.GravitySet = guiCreateButton(0.50, 0.485, 0.10, 0.04, "Set", true, tab, "setgravity")
aServerTab.SpeedCurrent = guiCreateLabel(0.03, 0.530, 0.30, 0.035, "Game Speed: " .. getGameSpeed(), true, tab)
aServerTab.Speed = guiCreateEdit(0.35, 0.530, 0.135, 0.04, "1", true, tab)
aServerTab.SpeedSet = guiCreateButton(0.50, 0.530, 0.10, 0.04, "Set", true, tab, "setgamespeed")
aServerTab.BlurCurrent = guiCreateLabel(0.03, 0.575, 0.25, 0.035, "Blur Level: 36", true, tab)
aServerTab.Blur = guiCreateEdit(0.35, 0.575, 0.135, 0.04, "36", true, tab)
aServerTab.BlurSet = guiCreateButton(0.50, 0.575, 0.10, 0.04, "Set", true, tab, "setblurlevel")
aServerTab.HeatHazeCurrent =
guiCreateLabel(0.03, 0.620, 0.25, 0.035, "Heat Haze Level: " .. getHeatHaze(), true, tab)
aServerTab.HeatHaze = guiCreateEdit(0.35, 0.620, 0.135, 0.04, "80", true, tab)
aServerTab.HeatHazeSet = guiCreateButton(0.50, 0.620, 0.10, 0.04, "Set", true, tab, "setheathazelevel")
guiSetEnabled(aServerTab.HeatHazeSet, true)
aServerTab.WavesCurrent = guiCreateLabel(0.03, 0.665, 0.25, 0.035, "Wave Height: " .. getWaveHeight(), true, tab)
aServerTab.Waves = guiCreateEdit(0.35, 0.665, 0.135, 0.04, "0", true, tab)
aServerTab.WavesSet = guiCreateButton(0.50, 0.665, 0.10, 0.04, "Set", true, tab, "setwaveheight")
aServerTab.FPSCurrent = guiCreateLabel(0.03, 0.710, 0.25, 0.035, "FPS Limit: 36", true, tab)
aServerTab.FPS = guiCreateEdit(0.35, 0.710, 0.135, 0.04, "36", true, tab)
aServerTab.FPSSet = guiCreateButton(0.50, 0.710, 0.10, 0.04, "Set", true, tab, "setfpslimit")
guiCreateHeader(0.02, 0.755, 0.30, 0.035, "Automatic scripts:", true, tab)
aServerTab.PingKickerCheck =
guiCreateCheckBox(0.03, 0.800, 0.30, 0.04, "Ping Kicker", false, true, tab, "setpingkicker")
aServerTab.PingKicker = guiCreateEdit(0.35, 0.800, 0.135, 0.04, "300", true, tab)
aServerTab.PingKickerSet = guiCreateButton(0.50, 0.800, 0.10, 0.04, "Set", true, tab, "setpingkicker")
guiSetEnabled(aServerTab.PingKicker, false)
guiSetEnabled(aServerTab.PingKickerSet, false)
aServerTab.FPSKickerCheck =
guiCreateCheckBox(0.03, 0.845, 0.30, 0.04, "FPS Kicker", false, true, tab, "setfpskicker")
aServerTab.FPSKicker = guiCreateEdit(0.35, 0.845, 0.135, 0.04, "5", true, tab)
aServerTab.FPSKickerSet = guiCreateButton(0.50, 0.845, 0.10, 0.04, "Set", true, tab, "setfpskicker")
guiSetEnabled(aServerTab.FPSKicker, false)
guiSetEnabled(aServerTab.FPSKickerSet, false)
aServerTab.IdleKickerCheck =
guiCreateCheckBox(0.03, 0.890, 0.30, 0.04, "Idle Kicker", false, true, tab, "setidlekicker")
aServerTab.IdleKicker = guiCreateEdit(0.35, 0.890, 0.135, 0.04, "10", true, tab)
aServerTab.IdleKickerSet = guiCreateButton(0.50, 0.890, 0.10, 0.04, "Set", true, tab, "setidlekicker")
guiSetEnabled(aServerTab.IdleKicker, false)
guiSetEnabled(aServerTab.IdleKickerSet, false)
guiCreateHeader(0.65, 0.015, 0.30, 0.035, "Allowed glitches:", true, tab)
local i = 1
for k,v in pairs(aServerTab.glitches) do
aServerTab[k] = guiCreateCheckBox(0.66, 0.015 + (0.045 * i), 0.40, 0.04, v, false, true, tab, "setglitch")
guiSetEnabled(aServerTab[k], true)
i = i + 1
end
local headerPosition = 0.060 + (0.045 * i)
guiCreateHeader(0.65, headerPosition, 0.30, 0.035, "Special world properties:", true, tab)
local i2 = 1
for k,v in pairs(aServerTab.worldproperties) do
aServerTab[k] = guiCreateCheckBox(0.66, headerPosition + (0.045 * i2), 0.40, 0.04, v, false, true, tab, 'setworldproperty')
guiSetEnabled(aServerTab[k], true)
i2 = i2 + 1
end
addEventHandler("onClientGUIClick", aServerTab.Tab, aServerTab.onClientClick)
addEventHandler('onClientGUIChanged', aServerTab.Tab, aServerTab.onClientChanged)
addEventHandler(EVENT_SYNC, root, aServerTab.onClientSync)
addEventHandler("onAdminRefresh", aServerTab.Tab, aServerTab.onRefresh)
local node = xmlLoadFile("conf\\weathers.xml")
if (node) then
local weathers = 0
while (true) do
local weather = xmlFindChild(node, "weather", weathers)
if (not weather) then
break
end
local id = tonumber(xmlNodeGetAttribute(weather, "id"))
local name = xmlNodeGetAttribute(weather, "name")
aServerTab.Weathers[id] = name
weathers = weathers + 1
end
end
for i3 = 0,19 do
guiComboBoxAddItem(aServerTab.Weather, i3 .. " (" .. getWeatherNameFromID(i3) .. ")")
end
sync(SYNC_SERVER)
aServerTab.onRefresh()
end
function aServerTab.onClientClick(button)
if (button == "left") then
if (source == aServerTab.SetGameType) then
local gametype = inputBox("Game Type", "Enter game type:")
if (gametype) then
triggerServerEvent("aServer", localPlayer, "setgame", gametype)
end
elseif (source == aServerTab.SetMapName) then
local mapname = inputBox("Map Name", "Enter map name:")
if (mapname) then
triggerServerEvent("aServer", localPlayer, "setmap", mapname)
end
elseif (source == aServerTab.SetPassword) then
local password = inputBox("Server password", "Enter server password: (32 characters max)")
if (password and password:len() > 0) then
triggerServerEvent("aServer", localPlayer, "setpassword", password)
end
elseif (source == aServerTab.ResetPassword) then
if (messageBox("Reset password?", MB_QUESTION, MB_YESNO)) then
triggerServerEvent("aServer", localPlayer, "setpassword", "")
end
elseif (source == aServerTab.Shutdown) then
if (messageBox("Are you sure you want to shutdown the server?", MB_QUESTION, MB_YESNO )) then
triggerServerEvent("aServer", localPlayer, "shutdown")
end
elseif (source == aServerTab.ClearChat) then
triggerServerEvent("aServer", localPlayer, "clearchat", "")
elseif (source == aServerTab.WeatherSet) then
local weather = guiComboBoxGetSelected(aServerTab.Weather)
if weather ~= -1 then
triggerServerEvent("aServer", localPlayer, "setweather", gettok(guiComboBoxGetItemText(aServerTab.Weather, weather), 1, 32))
else
triggerServerEvent("aServer", localPlayer, "setweather", 0)
end
elseif (source == aServerTab.WeatherBlend) then
local weather = guiComboBoxGetSelected(aServerTab.Weather)
if weather ~= -1 then
triggerServerEvent("aServer", localPlayer, "blendweather", gettok(guiComboBoxGetItemText(aServerTab.Weather, weather), 1, 32))
else
triggerServerEvent("aServer", localPlayer, "blendweather", 0)
end
elseif (source == aServerTab.TimeSet) then
triggerServerEvent(
"aServer",
localPlayer,
"settime",
guiGetText(aServerTab.TimeH),
guiGetText(aServerTab.TimeM)
)
elseif (source == aServerTab.SpeedSet) then
local speed = guiGetText(aServerTab.Speed)
if tonumber(speed) then
triggerServerEvent("aServer", localPlayer, "setgamespeed", speed)
elseif #speed == 0 then
triggerServerEvent("aServer", localPlayer, "setgamespeed", 1)
guiSetText(aServerTab.Speed, 1)
end
elseif (source == aServerTab.GravitySet) then
local gravity = guiGetText(aServerTab.Gravity)
if tonumber(gravity) then
triggerServerEvent("aServer", localPlayer, "setgravity", gravity)
elseif #gravity == 0 then
triggerServerEvent("aServer", localPlayer, "setgravity", 0.008)
guiSetText(aServerTab.Gravity, 0.008)
end
elseif (source == aServerTab.WavesSet) then
local waves = guiGetText(aServerTab.Waves)
if tonumber(waves) then
triggerServerEvent("aServer", localPlayer, "setwaveheight", waves)
elseif #waves == 0 then
triggerServerEvent("aServer", localPlayer, "setwaveheight", 0)
guiSetText(aServerTab.Waves, 0)
end
elseif (source == aServerTab.BlurSet) then
local blur = guiGetText(aServerTab.Blur)
if tonumber(blur) then
triggerServerEvent("aServer", localPlayer, "setblurlevel", blur)
elseif #blur == 0 then
triggerServerEvent("aServer", localPlayer, "setblurlevel", 36)
guiSetText(aServerTab.Blur, 36)
end
elseif (source == aServerTab.HeatHazeSet) then
local heathaze = guiGetText(aServerTab.HeatHaze)
if tonumber(heathaze) then
triggerServerEvent("aServer", localPlayer, "setheathazelevel", heathaze)
elseif #heathaze == 0 then
triggerServerEvent("aServer", localPlayer, "setheathazelevel", 80)
guiSetText(aServerTab.HeatHaze, 80)
end
elseif (source == aServerTab.FPSSet) then
local fps = guiGetText(aServerTab.FPS)
if tonumber(fps) then
triggerServerEvent("aServer", localPlayer, "setfpslimit", fps)
elseif #fps == 0 then
triggerServerEvent("aServer", localPlayer, "setfpslimit", 36) -- 36 is default
guiSetText(aServerTab.FPS, 36)
end
elseif (source == aServerTab.QuickReload) then
triggerServerEvent(
"aServer",
localPlayer,
"setglitch",
"quickreload",
iif(guiCheckBoxGetSelected(aServerTab.QuickReload), "on", "off")
)
elseif (source == aServerTab.FastMove) then
triggerServerEvent(
"aServer",
localPlayer,
"setglitch",
"fastmove",
iif(guiCheckBoxGetSelected(aServerTab.FastMove), "on", "off")
)
elseif (source == aServerTab.FastFire) then
triggerServerEvent(
"aServer",
localPlayer,
"setglitch",
"fastfire",
iif(guiCheckBoxGetSelected(aServerTab.FastFire), "on", "off")
)
elseif (source == aServerTab.CrouchBug) then
triggerServerEvent(
"aServer",
localPlayer,
"setglitch",
"crouchbug",
iif(guiCheckBoxGetSelected(aServerTab.CrouchBug), "on", "off")
)
elseif (source == aServerTab.HighCloseRangeDamage) then
triggerServerEvent(
"aServer",
localPlayer,
"setglitch",
"highcloserangedamage",
iif(guiCheckBoxGetSelected(aServerTab.HighCloseRangeDamage), "on", "off")
)
elseif (source == aServerTab.HitAnim) then
triggerServerEvent(
"aServer",
localPlayer,
"setglitch",
"hitanim",
iif(guiCheckBoxGetSelected(aServerTab.HitAnim), "on", "off")
)
elseif (source == aServerTab.FastSprint) then
triggerServerEvent(
"aServer",
localPlayer,
"setglitch",
"fastsprint",
iif(guiCheckBoxGetSelected(aServerTab.FastSprint), "on", "off")
)
elseif (source == aServerTab.BadDrivebyHitBox) then
triggerServerEvent(
"aServer",
localPlayer,
"setglitch",
"baddrivebyhitbox",
iif(guiCheckBoxGetSelected(aServerTab.BadDrivebyHitBox), "on", "off")
)
elseif (source == aServerTab.QuickStand) then
triggerServerEvent(
"aServer",
localPlayer,
"setglitch",
"quickstand",
iif(guiCheckBoxGetSelected(aServerTab.QuickStand), "on", "off")
)
elseif (source == aServerTab.HoverCars) then
triggerServerEvent(
"aServer",
localPlayer,
"setworldproperty",
"hovercars",
iif(guiCheckBoxGetSelected(aServerTab.HoverCars), "on", "off")
)
elseif (source == aServerTab.AirCars) then
triggerServerEvent(
"aServer",
localPlayer,
"setworldproperty",
"aircars",
iif(guiCheckBoxGetSelected(aServerTab.AirCars), "on", "off")
)
elseif (source == aServerTab.ExtraBunny) then
triggerServerEvent(
"aServer",
localPlayer,
"setworldproperty",
"extrabunny",
iif(guiCheckBoxGetSelected(aServerTab.ExtraBunny), "on", "off")
)
elseif (source == aServerTab.ExtraJump) then
triggerServerEvent(
"aServer",
localPlayer,
"setworldproperty",
"extrajump",
iif(guiCheckBoxGetSelected(aServerTab.ExtraJump), "on", "off")
)
elseif (source == aServerTab.RandomFoliage) then
triggerServerEvent(
"aServer",
localPlayer,
"setworldproperty",
"randomfoliage",
iif(guiCheckBoxGetSelected(aServerTab.RandomFoliage), "on", "off")
)
elseif (source == aServerTab.SniperMoon) then
triggerServerEvent(
"aServer",
localPlayer,
"setworldproperty",
"snipermoon",
iif(guiCheckBoxGetSelected(aServerTab.SniperMoon), "on", "off")
)
elseif (source == aServerTab.ExtraAirResistance) then
triggerServerEvent(
"aServer",
localPlayer,
"setworldproperty",
"extraairresistance",
iif(guiCheckBoxGetSelected(aServerTab.ExtraAirResistance), "on", "off")
)
elseif (source == aServerTab.UnderWorldWarp) then
triggerServerEvent(
"aServer",
localPlayer,
"setworldproperty",
"underworldwarp",
iif(guiCheckBoxGetSelected(aServerTab.UnderWorldWarp), "on", "off")
)
end
end
end
function aServerTab.onClientChanged()
local actualText = guiGetText(source)
local character = actualText:sub(#actualText, #actualText)
if not tonumber(character) and character ~= '.' then
guiSetText(source, actualText:sub(0, #actualText - 1))
end
end
function aServerTab.onClientSync(type, table)
if (type == SYNC_SERVER) then
guiSetText(aServerTab.Server, "Server: " .. table["name"])
guiSetText(aServerTab.Players, "Players: " .. #getElementsByType("player") .. "/" .. table["players"])
guiSetText(aServerTab.Password, "Password: " .. getSensitiveText(table["password"] or "None"))
guiSetText(aServerTab.GameType, "Game Type: " .. (table["game"] or "None"))
guiSetText(aServerTab.MapName, "Map Name: " .. (table["map"] or "None"))
aServerTab['currentPassword'] = table['password'] or nil
end
end
function aServerTab.onRefresh()
local th, tm = getTime()
guiSetText(
aServerTab.Players,
"Players: " .. #getElementsByType("player") .. "/" .. gettok(guiGetText(aServerTab.Players), 2, 47)
)
guiSetText(aServerTab.TimeCurrent, "Time: " .. string.format("%02d:%02d", th, tm))
guiSetText(aServerTab.GravityCurrent, "Gravitation: " .. string.format("%.3f", getGravity()))
guiSetText(aServerTab.SpeedCurrent, "Game Speed: " .. getGameSpeed())
guiSetText(
aServerTab.WeatherCurrent,
"Weather: " .. getWeather() .. " (" .. getWeatherNameFromID(getWeather()) .. ")"
)
guiSetText(aServerTab.BlurCurrent, "Blur Level: " .. getBlurLevel())
guiSetText(aServerTab.HeatHazeCurrent, "Heat Haze Level: " .. getHeatHaze())
guiSetText(aServerTab.WavesCurrent, "Wave Height: " .. getWaveHeight())
guiSetText(aServerTab.FPSCurrent, "FPS Limit: " .. getFPSLimit())
guiCheckBoxSetSelected(aServerTab.HoverCars, isWorldSpecialPropertyEnabled("hovercars"))
guiCheckBoxSetSelected(aServerTab.AirCars, isWorldSpecialPropertyEnabled("aircars"))
guiCheckBoxSetSelected(aServerTab.ExtraBunny, isWorldSpecialPropertyEnabled("extrabunny"))
guiCheckBoxSetSelected(aServerTab.ExtraJump, isWorldSpecialPropertyEnabled("extrajump"))
guiCheckBoxSetSelected(aServerTab.RandomFoliage, isWorldSpecialPropertyEnabled("randomfoliage"))
guiCheckBoxSetSelected(aServerTab.SniperMoon, isWorldSpecialPropertyEnabled("snipermoon"))
guiCheckBoxSetSelected(aServerTab.ExtraAirResistance, isWorldSpecialPropertyEnabled("extraairresistance"))
guiCheckBoxSetSelected(aServerTab.UnderWorldWarp, isWorldSpecialPropertyEnabled("underworldwarp"))
triggerServerEvent("aServerGlitchRefresh", localPlayer)
end
addEvent("aClientRefresh", true)
addEventHandler("aClientRefresh", localPlayer, function(quickreload, fastmove, fastfire, crouchbug, highcloserangedamage, hitanim, fastsprint, baddrivebyhitbox, quickstand)
guiCheckBoxSetSelected(aServerTab.QuickReload, quickreload)
guiCheckBoxSetSelected(aServerTab.FastMove, fastmove)
guiCheckBoxSetSelected(aServerTab.FastFire, fastfire)
guiCheckBoxSetSelected(aServerTab.CrouchBug, crouchbug)
guiCheckBoxSetSelected(aServerTab.HighCloseRangeDamage, highcloserangedamage)
guiCheckBoxSetSelected(aServerTab.HitAnim, hitanim)
guiCheckBoxSetSelected(aServerTab.FastSprint, fastsprint)
guiCheckBoxSetSelected(aServerTab.BadDrivebyHitBox, baddrivebyhitbox)
guiCheckBoxSetSelected(aServerTab.QuickStand, quickstand)
end)
function getWeatherNameFromID(weather)
return iif(aServerTab.Weathers[weather], aServerTab.Weathers[weather], "Unknown")
end
|
local replicated = game:GetService("ReplicatedStorage").CameraSystem
--// Buttons
script.Parent.Buttons.Blackout.MouseButton1Click:Connect(function()
if (replicated.Shared.BlackoutEnabled.Value == true and replicated.Shared.BlackoutColor.Value ~= Color3.fromRGB(0,0,0)) or replicated.Shared.BlackoutEnabled.Value == false then
replicated.Events.ChangeBlackout:FireServer(true,Color3.fromRGB(0,0,0))
else
replicated.Events.ChangeBlackout:FireServer(false)
end
end)
script.Parent.Buttons.Whiteout.MouseButton1Click:Connect(function()
if (replicated.Shared.BlackoutEnabled.Value == true and replicated.Shared.BlackoutColor.Value ~= Color3.fromRGB(255,255,255)) or replicated.Shared.BlackoutEnabled.Value == false then
replicated.Events.ChangeBlackout:FireServer(true,Color3.fromRGB(255,255,255))
else
replicated.Events.ChangeBlackout:FireServer(false)
end
end)
script.Parent.Buttons.Rainbow.MouseButton1Click:Connect(function()
replicated.Events.ToggleRainbow:FireServer()
end)
script.Parent.Buttons.Bars.MouseButton1Click:Connect(function()
replicated.Events.ToggleBars:FireServer()
end)
replicated.Server.ShowBars.Changed:Connect(function(val)
if val == true then
script.Parent.Buttons.Bars.BackgroundColor3 = Color3.fromRGB(35,167,28)
else
script.Parent.Buttons.Bars.BackgroundColor3 = Color3.fromRGB(0,0,0)
end
end)
replicated.Server.RainbowEnabled.Changed:Connect(function(val)
if val == true then
script.Parent.Buttons.Rainbow.BackgroundColor3 = Color3.fromRGB(35,167,28)
else
script.Parent.Buttons.Rainbow.BackgroundColor3 = Color3.fromRGB(0,0,0)
end
end)
local function updateBlackoutButtons()
local enabled = replicated.Shared.BlackoutEnabled.Value
local color = replicated.Shared.BlackoutColor.Value
if not enabled then
script.Parent.Buttons.Blackout.BackgroundColor3 = Color3.fromRGB(0,0,0)
script.Parent.Buttons.Whiteout.BackgroundColor3 = Color3.fromRGB(0,0,0)
else
if color == Color3.fromRGB(0,0,0) then
script.Parent.Buttons.Blackout.BackgroundColor3 = Color3.fromRGB(35, 167, 28)
script.Parent.Buttons.Whiteout.BackgroundColor3 = Color3.fromRGB(0,0,0)
elseif color == Color3.fromRGB(255,255,255) then
script.Parent.Buttons.Blackout.BackgroundColor3 = Color3.fromRGB(0,0,0)
script.Parent.Buttons.Whiteout.BackgroundColor3 = Color3.fromRGB(35, 167, 28)
else
script.Parent.Buttons.Blackout.BackgroundColor3 = Color3.fromRGB(0,0,0)
script.Parent.Buttons.Whiteout.BackgroundColor3 = Color3.fromRGB(0,0,0)
end
end
end
replicated.Shared.BlackoutColor.Changed:Connect(updateBlackoutButtons)
replicated.Shared.BlackoutEnabled.Changed:Connect(updateBlackoutButtons) |
----------------------------------------------------------------------------------------------------
-- localized English (main) strings
--
--get the AddOn engine
local AddOnName = ...;
--force localization to Spanish (only for testing)
--_G.GAME_LOCALE = "esES"
--prepare locale
local L = LibStub("AceLocale-3.0"):NewLocale(AddOnName, "enUS", true);
if not L then return; end
--main strings
L["LOAD_MESSAGE"] = "%s (version |cff0070de%s|r) loaded, type /%s or /%s for options."
L["CONFIG_WINDOW"] = "%s (version |cff0070de%s|r) by |cffffffffCecile|r - |cff0070deEU|r - |cffff2020Zul'jin|r"
L["MINIMAP_LABEL"] = "%s (|cff0070de%s|r)"
L["MINIMAP_HELP_1"] = "|cFFCFCFCFleft click|r: Open the Configuration"
L["PROFILES"] = "Profiles"
L["ABOUT"] = [[|cff0070deSpecial thanks to:|r
|cff82c5ffLaodice|r.
|cff0070deUsage:|r
This addon will attach an additional item tooltip to any recipe tooltip that produces an item.
That tooltip could show additional information that other addons embed, as an example the auction price.
This addon is compose of several modules that act as a database of items produce by recipes.
Those module are classified by profession and could be disable in the general addon settings within the game.
]] |
local block={}
local function Block(id,meta)
if meta == nil then meta=0 end
return meta * 0x1000 + id
end
local function unBlock(value)
return value % 0x1000, math.floor(value / 0x1000)
end
block.AIR =Block(0)
block.STONE =Block(1)
block.GRASS =Block(2)
block.DIRT =Block(3)
block.COBBLESTONE =Block(4)
block.WOOD_PLANKS =Block(5)
block.SAPLING =Block(6)
block.BEDROCK =Block(7)
block.WATER_FLOWING =Block(8)
block.WATER_STATIONARY =Block(9)
block.LAVA_FLOWING =Block(10)
block.LAVA_STATIONARY =Block(11)
block.SAND =Block(12)
block.GRAVEL =Block(13)
block.GOLD_ORE =Block(14)
block.IRON_ORE =Block(15)
block.COAL_ORE =Block(16)
block.WOOD =Block(17)
block.WOOD2 =Block(162)
block.LEAVES =Block(18)
block.GLASS =Block(20)
block.LAPIS_LAZULI_ORE =Block(21)
block.LAPIS_LAZULI_BLOCK =Block(22)
block.SANDSTONE =Block(24)
block.BED =Block(26)
block.COBWEB =Block(30)
block.GRASS_TALL =Block(31)
block.WOOL =Block(35)
block.FLOWER_YELLOW =Block(37)
block.FLOWER_CYAN =Block(38)
block.MUSHROOM_BROWN =Block(39)
block.MUSHROOM_RED =Block(40)
block.GOLD_BLOCK =Block(41)
block.IRON_BLOCK =Block(42)
block.STONE_SLAB_DOUBLE =Block(43)
block.STONE_SLAB =Block(44)
block.BRICK_BLOCK =Block(45)
block.TNT =Block(46)
block.BOOKSHELF =Block(47)
block.MOSS_STONE =Block(48)
block.OBSIDIAN =Block(49)
block.TORCH =Block(50)
block.FIRE =Block(51)
block.STAIR_WOOD =Block(53)
block.CHEST =Block(54)
block.DIAMOND_ORE =Block(56)
block.DIAMOND_BLOCK =Block(57)
block.CRAFTING_TABLE =Block(58)
block.FARMLAND =Block(60)
block.FURNACE_INACTIVE =Block(61)
block.FURNACE_ACTIVE =Block(62)
block.DOOR_WOOD =Block(64)
block.LADDER =Block(65)
block.STAIR_COBBLESTONE =Block(67)
block.DOOR_IRON =Block(71)
block.REDSTONE_ORE =Block(73)
block.STONE_BUTTON =Block(77)
block.SNOW =Block(78)
block.ICE =Block(79)
block.SNOW_BLOCK =Block(80)
block.CACTUS =Block(81)
block.CLAY =Block(82)
block.SUGAR_CANE =Block(83)
block.FENCE =Block(85)
block.GLOWSTONE_BLOCK =Block(89)
block.BEDROCK_INVISIBLE =Block(95)
block.STAINED_GLASS =Block(95)
block.TRAPDOOR =Block(96)
block.IRON_TRAPDOOR =Block(167)
block.STONE_BRICK =Block(98)
block.GLASS_PANE =Block(102)
block.MELON =Block(103)
block.FENCE_GATE =Block(107)
block.WATERLILY =Block(111)
block.WOOD_SLAB_DOUBLE =Block(125)
block.WOOD_SLAB =Block(126)
block.WOOD_BUTTON =Block(143)
block.REDSTONE_BLOCK =Block(152)
block.QUARTZ_BLOCK =Block(155)
block.HARDENED_CLAY_STAINED=Block(159)
block.SEA_LANTERN =Block(169)
block.CARPET =Block(171)
block.COAL_BLOCK =Block(173)
block.REDSTONE_LAMP_INACTIVE=Block(123)
block.REDSTONE_LAMP_ACTIVE =Block(124)
block.SUNFLOWER =Block(175,0)
block.LILAC =Block(175,1)
block.DOUBLE_TALLGRASS=Block(175,2)
block.LARGE_FERN =Block(175,3)
block.ROSE_BUSH =Block(175,4)
block.PEONY =Block(175,5)
block.WOOL_WHITE=Block(block.WOOL, 0)
block.WOOL_ORANGE=Block(block.WOOL, 1)
block.WOOL_MAGENTA=Block(block.WOOL, 2)
block.WOOL_LIGHT_BLUE=Block(block.WOOL, 3)
block.WOOL_YELLOW=Block(block.WOOL, 4)
block.WOOL_LIME=Block(block.WOOL, 5)
block.WOOL_PINK=Block(block.WOOL, 6)
block.WOOL_GRAY=Block(block.WOOL, 7)
block.WOOL_LIGHT_GRAY=Block(block.WOOL, 8)
block.WOOL_CYAN=Block(block.WOOL, 9)
block.WOOL_PURPLE=Block(block.WOOL, 10)
block.WOOL_BLUE=Block(block.WOOL, 11)
block.WOOL_BROWN=Block(block.WOOL, 12)
block.WOOL_GREEN=Block(block.WOOL, 13)
block.WOOL_RED=Block(block.WOOL, 14)
block.WOOL_BLACK=Block(block.WOOL, 15)
block.CARPET_WHITE=Block(block.CARPET, 0)
block.CARPET_ORANGE=Block(block.CARPET, 1)
block.CARPET_MAGENTA=Block(block.CARPET, 2)
block.CARPET_LIGHT_BLUE=Block(block.CARPET, 3)
block.CARPET_YELLOW=Block(block.CARPET, 4)
block.CARPET_LIME=Block(block.CARPET, 5)
block.CARPET_PINK=Block(block.CARPET, 6)
block.CARPET_GRAY=Block(block.CARPET, 7)
block.CARPET_LIGHT_GRAY=Block(block.CARPET, 8)
block.CARPET_CYAN=Block(block.CARPET, 9)
block.CARPET_PURPLE=Block(block.CARPET, 10)
block.CARPET_BLUE=Block(block.CARPET, 11)
block.CARPET_BROWN=Block(block.CARPET, 12)
block.CARPET_GREEN=Block(block.CARPET, 13)
block.CARPET_RED=Block(block.CARPET, 14)
block.CARPET_BLACK=Block(block.CARPET, 15)
block.STAINED_GLASS_WHITE=Block(block.STAINED_GLASS, 0)
block.STAINED_GLASS_ORANGE=Block(block.STAINED_GLASS, 1)
block.STAINED_GLASS_MAGENTA=Block(block.STAINED_GLASS, 2)
block.STAINED_GLASS_LIGHT_BLUE=Block(block.STAINED_GLASS, 3)
block.STAINED_GLASS_YELLOW=Block(block.STAINED_GLASS, 4)
block.STAINED_GLASS_LIME=Block(block.STAINED_GLASS, 5)
block.STAINED_GLASS_PINK=Block(block.STAINED_GLASS, 6)
block.STAINED_GLASS_GRAY=Block(block.STAINED_GLASS, 7)
block.STAINED_GLASS_LIGHT_GRAY=Block(block.STAINED_GLASS, 8)
block.STAINED_GLASS_CYAN=Block(block.STAINED_GLASS, 9)
block.STAINED_GLASS_PURPLE=Block(block.STAINED_GLASS, 10)
block.STAINED_GLASS_BLUE=Block(block.STAINED_GLASS, 11)
block.STAINED_GLASS_BROWN=Block(block.STAINED_GLASS, 12)
block.STAINED_GLASS_GREEN=Block(block.STAINED_GLASS, 13)
block.STAINED_GLASS_RED=Block(block.STAINED_GLASS, 14)
block.STAINED_GLASS_BLACK=Block(block.STAINED_GLASS, 15)
block.HARDENED_CLAY_STAINED_WHITE=Block(block.HARDENED_CLAY_STAINED, 0)
block.HARDENED_CLAY_STAINED_ORANGE=Block(block.HARDENED_CLAY_STAINED, 1)
block.HARDENED_CLAY_STAINED_MAGENTA=Block(block.HARDENED_CLAY_STAINED, 2)
block.HARDENED_CLAY_STAINED_LIGHT_BLUE=Block(block.HARDENED_CLAY_STAINED, 3)
block.HARDENED_CLAY_STAINED_YELLOW=Block(block.HARDENED_CLAY_STAINED, 4)
block.HARDENED_CLAY_STAINED_LIME=Block(block.HARDENED_CLAY_STAINED, 5)
block.HARDENED_CLAY_STAINED_PINK=Block(block.HARDENED_CLAY_STAINED, 6)
block.HARDENED_CLAY_STAINED_GRAY=Block(block.HARDENED_CLAY_STAINED, 7)
block.HARDENED_CLAY_STAINED_LIGHT_GRAY=Block(block.HARDENED_CLAY_STAINED, 8)
block.HARDENED_CLAY_STAINED_CYAN=Block(block.HARDENED_CLAY_STAINED, 9)
block.HARDENED_CLAY_STAINED_PURPLE=Block(block.HARDENED_CLAY_STAINED, 10)
block.HARDENED_CLAY_STAINED_BLUE=Block(block.HARDENED_CLAY_STAINED, 11)
block.HARDENED_CLAY_STAINED_BROWN=Block(block.HARDENED_CLAY_STAINED, 12)
block.HARDENED_CLAY_STAINED_GREEN=Block(block.HARDENED_CLAY_STAINED, 13)
block.HARDENED_CLAY_STAINED_RED=Block(block.HARDENED_CLAY_STAINED, 14)
block.HARDENED_CLAY_STAINED_BLACK=Block(block.HARDENED_CLAY_STAINED, 15)
block.LEAVES_OAK_DECAYABLE=Block(block.LEAVES, 0)
block.LEAVES_SPRUCE_DECAYABLE=Block(block.LEAVES, 1)
block.LEAVES_BIRCH_DECAYABLE=Block(block.LEAVES, 2)
block.LEAVES_JUNGLE_DECAYABLE=Block(block.LEAVES, 3)
block.LEAVES_SPRUCE_DECAYABLE_CD=Block(block.LEAVES, 9)
block.LEAVES_JUNGLE_DECAYABLE_CD=Block(block.LEAVES, 11)
block.LEAVES_OAK_PERMANENT=Block(block.LEAVES, 4)
block.LEAVES_SPRUCE_PERMANENT=Block(block.LEAVES, 5)
block.LEAVES_BIRCH_PERMANENT=Block(block.LEAVES, 6)
block.LEAVES_JUNGLE_PERMANENT=Block(block.LEAVES, 7)
block.LEAVES_OAK_PERMANENT_CD=Block(block.LEAVES, 12)
block.LEAVES_SPRUCE_PERMANENT_CD=Block(block.LEAVES, 13)
block.LEAVES_BIRCH_PERMANENT_CD=Block(block.LEAVES, 14)
block.LEAVES_JUNGLE_PERMANENT_CD=Block(block.LEAVES, 15)
block.LEAVES2=Block(161)
block.LEAVES_ACACIA_DECAYABLE=Block(block.LEAVES2, 0)
block.LEAVES_DARK_OAK_DECAYABLE=Block(block.LEAVES2, 1)
block.LEAVES_ACACIA_PERMANENT=Block(block.LEAVES2, 4)
block.LEAVES_DARK_OAK_PERMANENT=Block(block.LEAVES2, 5)
block.LEAVES_ACACIA_DECAYABLE_CD=Block(block.LEAVES2, 8)
block.LEAVES_DARK_OAK_DECAYABLE_CD=Block(block.LEAVES2, 9)
block.LEAVES_ACACIA_PERMANENT_CD=Block(block.LEAVES2, 12)
block.LEAVES_DARK_OAK_PERMANENT_CD=Block(block.LEAVES2, 13)
block.OBSIDIAN_GLASS = Block(1001)
block.FENCE_RAIL = Block(1002)
local to_node={}
local from_node={}
local function translate(id, name, param2)
if not param2 then param2=0 end
if not minetest.registered_nodes[name] then
if name.sub(1,14)=="stained_glass:" then
name="default:glass"
else
name="default:stone"
end
end
to_node[id]={name=name,param2=param2}
local key=name.." "..param2
if not from_node[key] then
from_node[key]=id
end
end
translate(block.AIR,"air")
translate(block.STONE,"default:stone")
translate(block.GRASS,"default:dirt_with_grass")
translate(block.DIRT,"default:dirt")
translate(block.COBBLESTONE,"default:cobble")
translate(block.WOOD_PLANKS,"default:wood")
translate(block.SAPLING,"default:sapling")
translate(block.BEDROCK,"default:obsidian")
translate(block.WATER_FLOWING,"default:water_flowing")
translate(block.WATER_STATIONARY,"default:water_source")
translate(block.LAVA_FLOWING,"default:lava_flowing")
translate(block.LAVA_STATIONARY,"default:lava_source")
translate(block.SAND,"default:sand")
translate(block.GRAVEL,"default:gravel")
translate(block.GOLD_ORE,"default:stone_with_gold")
translate(block.IRON_ORE,"default:stone_with_iron")
translate(block.COAL_ORE,"default:stone_with_coal")
translate(block.WOOD,"default:tree")
translate(block.LEAVES,"default:leaves")
translate(block.GLASS,"default:glass")
translate(block.LAPIS_LAZULI_ORE,"wool:blue") -- fix
translate(block.LAPIS_LAZULI_BLOCK,"wool:blue")
translate(block.SANDSTONE,"default:sandstone")
-- translate(block.BED,"default:")
-- translate(block.COBWEB,"default:")
translate(block.GRASS_TALL,"default:junglegrass")
translate(block.WOOL,"wool:white")
translate(block.WATERLILY,"flowers:dandelion_white") --fix
translate(block.FLOWER_YELLOW,"flowers:dandelion_yellow")
translate(block.FLOWER_CYAN,"flowers:geranium")
translate(block.MUSHROOM_BROWN,"flowers:mushroom_brown")
translate(block.MUSHROOM_RED,"flowers:mushroom_red")
translate(block.GOLD_BLOCK,"default:goldblock")
translate(block.IRON_BLOCK,"default:steelblock")
--translate(block.STONE_SLAB_DOUBLE,"default:")
translate(block.BRICK_BLOCK,"default:brick")
translate(block.TNT,"tnt:tnt")
translate(block.BOOKSHELF,"default:bookshelf")
translate(block.MOSS_STONE,"default:mossycobble")
translate(block.OBSIDIAN,"default:obsidian")
translate(block.TORCH,"default:torch")
translate(block.FIRE,"fire:basic_flame")
translate(block.CHEST,"default:chest")
translate(block.DIAMOND_ORE,"default:stone_with_diamond")
translate(block.DIAMOND_BLOCK,"default:diamondblock")
--translate(block.CRAFTING_TABLE,"default:")
translate(block.FARMLAND,"farming:soil")
translate(block.FURNACE_INACTIVE,"default:furnace")
translate(block.FURNACE_ACTIVE,"default:furnace_active")
translate(block.LADDER,"default:ladder")
translate(block.REDSTONE_ORE,"wool:red") -- fix
--translate(block.STONE_BUTTON,"default:")
translate(block.SNOW,"default:snow")
translate(block.ICE,"default:ice")
translate(block.SNOW_BLOCK,"default:snowblock")
translate(block.CACTUS,"default:cactus")
translate(block.CLAY,"default:clay")
translate(block.SUGAR_CANE,"farming:straw") -- fix
translate(block.FENCE,"default:fence_wood")
translate(block.GLOWSTONE_BLOCK,"default:meselamp") -- fix
--translate(block.BEDROCK_INVISIBLE,"default:")
translate(block.STONE_BRICK,"default:stonebrick")
translate(block.GLASS_PANE,"xpanes:pane_flat") -- fix
--translate(block.MELON,"default:")
translate(block.WOOD_SLAB_DOUBLE,"default:wood") --fix
--translate(block.FENCE_GATE,"default:")
--translate(block.WOOD_BUTTON,"default:")
translate(block.REDSTONE_BLOCK,"wool:red") -- fix
translate(block.QUARTZ_BLOCK,"wool:white")
translate(block.HARDENED_CLAY_STAINED,"wool:white") --fix
translate(block.SEA_LANTERN,"default:meselamp")
translate(block.CARPET,"wool:white") -- fix
translate(block.COAL_BLOCK,"default:coalblock")
--translate(block.REDSTONE_LAMP_INACTIVE,"default:")
translate(block.REDSTONE_LAMP_ACTIVE,"default:meselamp")
translate(block.SUNFLOWER,"flowers:tulip")
translate(block.LILAC,"flowers:viola")
translate(block.DOUBLE_TALLGRASS,"default:grass_2") --fix
--translate(block.LARGE_FERN,"default:")
translate(block.ROSE_BUSH,"flowers:rose")
translate(block.PEONY,"flowers:rose") --fix
translate(block.WOOL_WHITE,"wool:white")
translate(block.WOOL_ORANGE,"wool:orange")
translate(block.WOOL_MAGENTA,"wool:magenta")
translate(block.WOOL_LIGHT_BLUE,"wool:cyan") --fix
translate(block.WOOL_YELLOW,"wool:yellow")
translate(block.WOOL_LIME,"wool:green")
translate(block.WOOL_PINK,"wool:pink")
translate(block.WOOL_GRAY,"wool:dark_grey")
translate(block.WOOL_LIGHT_GRAY,"wool:grey")
translate(block.WOOL_CYAN,"wool:cyan")
translate(block.WOOL_PURPLE,"wool:violet")
translate(block.WOOL_BLUE,"wool:blue")
translate(block.WOOL_BROWN,"wool:brown")
translate(block.WOOL_GREEN,"wool:dark_green")
translate(block.WOOL_RED,"wool:red")
translate(block.WOOL_BLACK,"wool:black")
translate(block.CARPET_WHITE,"wool:white")
translate(block.CARPET_ORANGE,"wool:orange")
translate(block.CARPET_MAGENTA,"wool:magenta")
translate(block.CARPET_LIGHT_BLUE,"wool:cyan") --fix
translate(block.CARPET_YELLOW,"wool:yellow")
translate(block.CARPET_LIME,"wool:green")
translate(block.CARPET_PINK,"wool:pink")
translate(block.CARPET_GRAY,"wool:dark_grey")
translate(block.CARPET_LIGHT_GRAY,"wool:grey")
translate(block.CARPET_CYAN,"wool:cyan")
translate(block.CARPET_PURPLE,"wool:violet")
translate(block.CARPET_BLUE,"wool:blue")
translate(block.CARPET_BROWN,"wool:brown")
translate(block.CARPET_GREEN,"wool:dark_green")
translate(block.CARPET_RED,"wool:red")
translate(block.CARPET_BLACK,"wool:black")
translate(block.HARDENED_CLAY_STAINED_WHITE,"wool:white")
translate(block.HARDENED_CLAY_STAINED_ORANGE,"wool:orange")
translate(block.HARDENED_CLAY_STAINED_MAGENTA,"wool:magenta")
translate(block.HARDENED_CLAY_STAINED_LIGHT_BLUE,"wool:cyan") --fix
translate(block.HARDENED_CLAY_STAINED_YELLOW,"wool:yellow")
translate(block.HARDENED_CLAY_STAINED_LIME,"wool:green")
translate(block.HARDENED_CLAY_STAINED_PINK,"wool:pink")
translate(block.HARDENED_CLAY_STAINED_GRAY,"wool:dark_grey")
translate(block.HARDENED_CLAY_STAINED_LIGHT_GRAY,"wool:grey")
translate(block.HARDENED_CLAY_STAINED_CYAN,"wool:cyan")
translate(block.HARDENED_CLAY_STAINED_PURPLE,"wool:violet")
translate(block.HARDENED_CLAY_STAINED_BLUE,"wool:blue")
translate(block.HARDENED_CLAY_STAINED_BROWN,"wool:brown")
translate(block.HARDENED_CLAY_STAINED_GREEN,"wool:dark_green")
translate(block.HARDENED_CLAY_STAINED_RED,"wool:red")
translate(block.HARDENED_CLAY_STAINED_BLACK,"wool:black")
translate(block.STAINED_GLASS_WHITE,"stained_glass:faint_aqua") --fix
translate(block.STAINED_GLASS_ORANGE,"stained_glass:orange")
translate(block.STAINED_GLASS_MAGENTA,"stained_glass:magenta")
translate(block.STAINED_GLASS_LIGHT_BLUE,"stained_glass:faint_blue")
translate(block.STAINED_GLASS_YELLOW,"stained_glass:yellow")
translate(block.STAINED_GLASS_LIME,"stained_glass:lime")
translate(block.STAINED_GLASS_PINK,"stained_glass:faint_red")
translate(block.STAINED_GLASS_GRAY,"stained_glass:dark_blue") --fix
translate(block.STAINED_GLASS_LIGHT_GRAY,"stained_glass:medium_blue") --fix
translate(block.STAINED_GLASS_CYAN,"stained_glass:cyan")
translate(block.STAINED_GLASS_PURPLE,"stained_glass:violet")
translate(block.STAINED_GLASS_BLUE,"stained_glass:blue")
translate(block.STAINED_GLASS_BROWN,"stained_glass:dark_red")
translate(block.STAINED_GLASS_GREEN,"stained_glass:green")
translate(block.STAINED_GLASS_RED,"stained_glass:red")
translate(block.STAINED_GLASS_BLACK,"stained_glass:dark_green") --fix
--translate(block.LEAVES_OAK_DECAYABLE,"default:leaves")
translate(block.LEAVES_SPRUCE_DECAYABLE,"default:pine_needles")
--translate(block.LEAVES_BIRCH_DECAYABLE,"default:leaves")
translate(block.LEAVES_JUNGLE_DECAYABLE,"default:jungleleaves")
translate(block.LEAVES_OAK_PERMANENT,"default:leaves",1)
translate(block.LEAVES_SPRUCE_PERMANENT,"default:pine_needles",1)
translate(block.LEAVES_BIRCH_PERMANENT,"default:leaves",1)
translate(block.LEAVES_SPRUCE_DECAYABLE_CD,"default:pine_needles")
translate(block.LEAVES_JUNGLE_DECAYABLE_CD,"default:jungleleaves")
translate(block.LEAVES_JUNGLE_PERMANENT,"default:jungleleaves",1)
translate(block.LEAVES_OAK_PERMANENT_CD,"default:leaves",1)
translate(block.LEAVES_SPRUCE_PERMANENT_CD,"default:pine_needles",1)
translate(block.LEAVES_BIRCH_PERMANENT_CD,"default:leaves",1)
translate(block.LEAVES_JUNGLE_PERMANENT_CD,"default:jungleleaves",1)
translate(block.LEAVES2,"default:leaves")
translate(block.LEAVES_ACACIA_DECAYABLE,"default:acacia_leaves")
--block.to_node[block.LEAVES_DARK_OAK_DECAYABLE] =
translate(block.LEAVES_ACACIA_PERMANENT,"default:acacia_leaves",1)
translate(block.LEAVES_DARK_OAK_PERMANENT,"default:leaves",1)
translate(block.LEAVES_ACACIA_PERMANENT_CD,"default:acacia_leaves",1)
translate(block.LEAVES_DARK_OAK_PERMANENT_CD,"default:leaves",1)
translate(Block(228),"air")
translate(Block(229),"air")
translate(Block(236),"air")
translate(Block(254),"air")
translate(Block(block.WOOD_SLAB,0),"stairs:slab_wood",0)
translate(Block(block.WOOD_SLAB,8),"stairs:slab_wood",20)
translate(Block(block.WOOD_SLAB,1),"stairs:slab_pine_wood",0)
translate(Block(block.WOOD_SLAB,9),"stairs:slab_pine_wood",20)
translate(Block(block.WOOD_SLAB,2),"stairs:slab_wood",0) -- FIX: birch
translate(Block(block.WOOD_SLAB,10),"stairs:slab_wood",20)
translate(Block(block.WOOD_SLAB,3),"stairs:slab_junglewood",0)
translate(Block(block.WOOD_SLAB,11),"stairs:slab_junglewood",20)
translate(Block(block.WOOD_SLAB,4),"stairs:slab_acacia_wood",0)
translate(Block(block.WOOD_SLAB,12),"stairs:slab_acacia_wood",20)
translate(Block(block.WOOD_SLAB,5),"stairs:slab_wood",0) -- FIX: dark oak
translate(Block(block.WOOD_SLAB,13),"stairs:slab_wood",20)
translate(Block(block.STONE_SLAB,0),"stairs:slab_stone",0)
translate(Block(block.STONE_SLAB,8),"stairs:slab_stone",20)
translate(Block(block.STONE_SLAB,1),"stairs:slab_sandstone",0)
translate(Block(block.STONE_SLAB,9),"stairs:slab_sandstone",20)
translate(Block(block.STONE_SLAB,2),"stairs:slab_wood",0)
translate(Block(block.STONE_SLAB,10),"stairs:slab_wood",20)
translate(Block(block.STONE_SLAB,3),"stairs:slab_cobble",0)
translate(Block(block.STONE_SLAB,11),"stairs:slab_cobble",20)
translate(Block(block.STONE_SLAB,4),"stairs:slab_brick",0)
translate(Block(block.STONE_SLAB,12),"stairs:slab_brick",20)
translate(Block(block.STONE_SLAB,6),"stairs:slab_stonebrick",0)
translate(Block(block.STONE_SLAB,13),"stairs:slab_stonebrick",20)
translate(Block(block.STONE_SLAB,7),"stairs:slab_desert_stonebrick",0) -- FIX: nether brick
translate(Block(block.STONE_SLAB,14),"stairs:slab_desert_stonebrick",20)
translate(Block(block.STONE_SLAB,8),"stairs:slab_desert_stone",0) -- FIX: quartz
translate(Block(block.STONE_SLAB,15),"stairs:slab_desert_stone",20)
translate(Block(block.FENCE,0),"default:fence_wood",0)
translate(Block(block.FENCE,8),"default:fence_wood",20)
translate(Block(block.FENCE,1),"default:fence_pine_wood",0)
translate(Block(block.FENCE,9),"default:fence_pine_wood",20)
translate(Block(block.FENCE,2),"default:fence_wood",0) -- FIX: birch
translate(Block(block.FENCE,10),"default:fence_wood",20)
translate(Block(block.FENCE,3),"default:fence_junglewood",0)
translate(Block(block.FENCE,11),"default:fence_junglewood",20)
translate(Block(block.FENCE,4),"default:fence_acacia_wood",0)
translate(Block(block.FENCE,12),"default:fence_acacia_wood",20)
translate(Block(block.FENCE,5),"default:fence_wood",0) -- FIX: dark oak
translate(Block(block.FENCE,13),"default:fence_wood",20)
translate(Block(block.FENCE_RAIL,0),"default:fence_rail_wood",0)
translate(Block(block.FENCE_RAIL,8),"default:fence_rail_wood",20)
translate(Block(block.FENCE_RAIL,1),"default:fence_rail_pine_wood",0)
translate(Block(block.FENCE_RAIL,9),"default:fence_rail_pine_wood",20)
translate(Block(block.FENCE_RAIL,2),"default:fence_rail_wood",0) -- FIX: birch
translate(Block(block.FENCE_RAIL,10),"default:fence_rail_wood",20)
translate(Block(block.FENCE_RAIL,3),"default:fence_rail_junglewood",0)
translate(Block(block.FENCE_RAIL,11),"default:fence_rail_junglewood",20)
translate(Block(block.FENCE_RAIL,4),"default:fence_rail_acacia_wood",0)
translate(Block(block.FENCE_RAIL,12),"default:fence_rail_acacia_wood",20)
translate(Block(block.FENCE_RAIL,5),"default:fence_rail_wood",0) -- FIX: dark oak
translate(Block(block.FENCE_RAIL,13),"default:fence_rail_wood",20)
translate(block.OBSIDIAN_GLASS,"default:obsidian_glass")
local function defineTrapdoor(base_num,base_name)
translate(Block(base_num,0),base_name,2)
translate(Block(base_num,1),base_name,0)
translate(Block(base_num,2),base_name,1)
translate(Block(base_num,3),base_name,3)
translate(Block(base_num,4+0),base_name.."_open",2)
translate(Block(base_num,4+1),base_name.."_open",0)
translate(Block(base_num,4+2),base_name.."_open",1)
translate(Block(base_num,4+3),base_name.."_open",3)
translate(Block(base_num,8+0),base_name,22)
translate(Block(base_num,8+1),base_name,20)
translate(Block(base_num,8+2),base_name,23)
translate(Block(base_num,8+3),base_name,21)
translate(Block(base_num,4+8+0),base_name.."_open",22)
translate(Block(base_num,4+8+1),base_name.."_open",20)
translate(Block(base_num,4+8+2),base_name.."_open",23)
translate(Block(base_num,4+8+3),base_name.."_open",21)
end
defineTrapdoor(block.TRAPDOOR,"doors:trapdoor")
defineTrapdoor(block.IRON_TRAPDOOR,"doors:trapdoor")
local function defineDoor(base_num,base_name)
translate(Block(base_num,0),base_name.."_b_2")
translate(Block(base_num,1),base_name.."_b_2")
translate(Block(base_num,2),base_name.."_b_2")
translate(Block(base_num,3),base_name.."_b_2")
translate(Block(base_num,4+0),base_name.."_b_2")
translate(Block(base_num,4+1),base_name.."_b_2")
translate(Block(base_num,4+2),base_name.."_b_2")
translate(Block(base_num,4+3),base_name.."_b_2")
translate(Block(base_num,8+0),base_name.."_t_2")
translate(Block(base_num,8+1),base_name.."_t_2")
translate(Block(base_num,8+2),base_name.."_t_2")
translate(Block(base_num,8+3),base_name.."_t_2")
translate(Block(base_num,4+8+0),base_name.."_t_2")
translate(Block(base_num,4+8+1),base_name.."_t_2")
translate(Block(base_num,4+8+2),base_name.."_t_2")
translate(Block(base_num,4+8+3),base_name.."_t_2")
-- lots of fixes to be done!
-- it might not be doable as MC upper doors don't have directional data
end
defineDoor(block.DOOR_WOOD, "doors:door_wood")
defineDoor(block.DOOR_IRON, "doors:door_steel")
local function defineStair(base_num,base_name)
translate(Block(base_num,0),base_name,1)
translate(Block(base_num,1),base_name,3)
translate(Block(base_num,2),base_name,2)
translate(Block(base_num,3),base_name,0)
translate(Block(base_num,4),base_name,17)
translate(Block(base_num,5),base_name,21)
translate(Block(base_num,6),base_name,22)
translate(Block(base_num,7),base_name,20)
end
defineStair(block.STAIR_WOOD, "stairs:stair_wood")
defineStair(block.STAIR_COBBLESTONE, "stairs:stair_cobble")
defineStair(108, "stairs:stair_brick")
defineStair(109, "stairs:stair_stonebrick")
defineStair(114, "stairs:stair_desert_stonebrick") -- fix: nether brick
defineStair(128, "stairs:stair_sandstone")
defineStair(134, "stairs:stair_pine_wood")
defineStair(135, "stairs:stair_wood") -- fix: birch
defineStair(136, "stairs:stair_junglewood")
defineStair(156, "stairs:stair_desert_stone") -- fix: quartz
defineStair(163, "stairs:stair_acacia_wood")
defineStair(164, "stairs:stair_wood") -- fix: dark oak
defineStair(180, "stairs:stair_sandstone") -- fix: red sandstone
defineStair(203, "stairs:stair_wood") -- fix: purpur
local function defineWood(main, subtype, node_name)
translate(Block(main, subtype), node_name)
translate(Block(main, subtype + 1 * 4), node_name, 12)
translate(Block(main, subtype + 2 * 4), node_name, 4)
translate(Block(main, subtype + 3 * 4), node_name) -- fix: all bark
end
defineWood(block.WOOD, 0, "default:tree") -- oak
defineWood(block.WOOD, 1, "default:pine_tree") -- spruce
defineWood(block.WOOD, 2, "default:tree") -- fix: birch
defineWood(block.WOOD, 3, "default:jungletree")
defineWood(block.WOOD2, 0, "default:acacia_tree")
defineWood(block.WOOD2, 1, "default:tree") -- fix: dark oak
function block.node_to_id_meta(node)
if node.name == "air" or node.name == "ignore" then
return 0,0
end
local entry=node.name .. " " .. node.param2
if from_node[entry] then
return unBlock(from_node[entry])
end
entry=node.name .. " 0"
if from_node[entry] then
return unBlock(from_node[entry])
end
return unBlock(block.STONE)
end
function block.id_meta_to_node(id, meta)
if id == 0 then
return {name="air"}
end
local value=Block(id, meta)
if to_node[value] then
return to_node[value]
elseif to_node[id] then
return to_node[id]
else
return {name="stone"}
end
end
return block
|
--
-- centrifuge c1 c2 c3
-- module type s4 s5 s6
-- crafting_speed 58.8 87.6 123.6
-- energy_source.emissions_per_minute 47.55 53.8 60.1
-- energy_usage 13.3MW 15MW 16.8MW
--
require ("func_centrifuge")
local beaconed_fe_centrifuge_1 = {
name = "beaconed-fe-centrifuge-1",
crafting_speed = 58.8,
energy_usage = "13.3MW",
emissions_per_minute = 47.55,
ingredients =
{
{"centrifuge-mk3", 1},
{"beacon-mk3", 7},
{"speed-module-4", 14 }
},
item_order = "e-b-a",
result =
{
{ type = "item", name = "beaconed-fe-centrifuge-1", amount = 1}
},
upgradeable_ingredients =
{
{"centrifuge-mk3", 1},
{"beacon-mk3", 7},
{"speed-module-4", 14 }
},
upgradeable_result =
{
{ type = "item", name = "beaconed-fe-centrifuge-1", amount = 1}
}
}
create_centrifuge(beaconed_fe_centrifuge_1)
local beaconed_fe_centrifuge_2 = {
name = "beaconed-fe-centrifuge-2",
crafting_speed = 87.6,
energy_usage = "15MW",
emissions_per_minute = 53.8,
ingredients =
{
{"centrifuge-mk3", 1},
{"beacon-mk3", 7},
{"speed-module-5", 14 }
},
item_order = "e-b-b",
result =
{
{ type = "item", name = "beaconed-fe-centrifuge-2", amount = 1}
},
upgradeable_ingredients =
{
{"beaconed-fe-centrifuge-1", 1},
{"speed-module-5", 14 }
},
upgradeable_result =
{
{ type = "item", name = "beaconed-fe-centrifuge-2", amount = 1},
{ type = "item", name = "speed-module-4", amount = 14}
}
}
create_centrifuge(beaconed_fe_centrifuge_2)
local beaconed_fe_centrifuge_3 = {
name = "beaconed-fe-centrifuge-3",
crafting_speed = 123.6,
energy_usage = "16.8MW",
emissions_per_minute = 60.1,
ingredients =
{
{"centrifuge-mk3", 1},
{"beacon-mk3", 7},
{"speed-module-6", 14 }
},
item_order = "e-b-c",
result =
{
{ type = "item", name = "beaconed-fe-centrifuge-3", amount = 1}
},
upgradeable_ingredients =
{
{"beaconed-fe-centrifuge-2", 1},
{"speed-module-6", 14 }
},
upgradeable_result =
{
{ type = "item", name = "beaconed-fe-centrifuge-3", amount = 1},
{ type = "item", name = "speed-module-5", amount = 14}
}
}
create_centrifuge(beaconed_fe_centrifuge_3)
|
texts = nil
errored = false
checkedAll = false
data = nil
modslist = {}
index = 1
timer = nil
versionIndex = {}
function init()
local passed, err = pcall(function()
data = root.assetJson("/zb/updateInfoWindow/data.config")
modslist = status.statusProperty("zb_updatewindow_pending", {}) or {}
widget.setButtonEnabled("close", false)
widget.setButtonEnabled("buttonPrevious", false)
if #modslist <= 0 then
checkedAll = true
timer = 0
for mod, _ in pairs(data) do
if mod ~= "Data" then
table.insert(modslist, mod)
end
end
end
if #modslist == 1 then
widget.setButtonEnabled("buttonNext", false)
end
if not timer then
timer = data.Data.minimumUptime
end
displayInfo()
end)
if not passed then
sb.logError("[ZB] UPDATE WINDOW ERRORED")
sb.logError("mods list:\n%s\nError:\n%s", status.statusProperty("zb_updatewindow_pending", {}) or {}, err)
sb.logError("")
errored = true
widget.setText("textScrollBox.text", "An error has occured. Please report this error with a log attached.")
widget.setButtonEnabled("close", true)
widget.setText("close", "Dismiss")
end
end
function update(dt)
if timer then
if timer >= 0 then
timer = timer - dt
widget.setText("close", math.ceil(timer))
else
checkedAll = true
widget.setButtonEnabled("close", true)
widget.setText("close", "Dismiss")
end
end
end
function displayInfo()
texts = root.assetJson(data[modslist[index]].file)
versionIndex[modslist[index]] = texts.version
widget.setButtonEnabled("buttonChangelog", true)
widget.setButtonEnabled("buttonCredits", true)
widget.setButtonEnabled("buttonInfo", true)
widget.setText("textScrollBox.text", "\n"..checkString(texts.welcome, "welcome").."\n\n")
widget.setText("version", texts.version)
if data[modslist[index]].image then
local imageSize = root.imageSize(data[modslist[index]].image)
local widgetPosition = {150, 229}
widgetPosition[1] = widgetPosition[1] - imageSize[1] * 0.5
widgetPosition[2] = widgetPosition[2] - imageSize[2] * 0.5
widget.setPosition("title", widgetPosition)
widget.setImage("title", data[modslist[index]].image)
else
widget.setImage("title", "/assetmissing.png")
end
end
function uninit()
if errored then return end
if not checkedAll then
player.interact("ScriptPane", "/zb/updateInfoWindow/updateInfoWindow.config")
return
else
local pending = status.statusProperty("zb_updatewindow_pending", {}) or {}
local versions = status.statusProperty("zb_updatewindow_versions", {}) or {}
for _, mod in ipairs(pending) do
versions[mod] = versionIndex[mod]
status.setStatusProperty("zb_updatewindow_versions", versions)
end
status.setStatusProperty("zb_updatewindow_pending", nil)
end
end
function close()
pane.dismiss()
end
function checkString(str, req)
local rtn = ""
local passed, err = pcall(function()
local a, b = string.find(str, "#file#")
if a == 1 then
local text = root.assetJson(string.gsub(str, "#file#", ""))
rtn = text[req]
else
rtn = str
end
end)
if passed then
return rtn.."\n\n"
else
sb.logError("[ZB] UPDATE WINDOW ERRORED")
sb.logError("Pending list:\n%s\nError:\n%s", status.statusProperty("zb_updatewindow_pending", {}) or {}, err)
sb.logError("")
errored = true
widget.setText("textScrollBox.text", "An error has occured. Please report this error with a log attached.")
widget.setButtonEnabled("close", true)
widget.setText("close", "Dismiss")
end
end
function buttonInfo()
widget.setText("textScrollBox.text", checkString(texts.info, "info"))
widget.setButtonEnabled("buttonChangelog", true)
widget.setButtonEnabled("buttonCredits", true)
widget.setButtonEnabled("buttonInfo", false)
end
function buttonChangelog()
widget.setText("textScrollBox.text", checkString(texts.changelog, "changelog"))
widget.setButtonEnabled("buttonChangelog", false)
widget.setButtonEnabled("buttonCredits", true)
widget.setButtonEnabled("buttonInfo", true)
end
function buttonCredits()
widget.setText("textScrollBox.text", checkString(texts.credits, "credits"))
widget.setButtonEnabled("buttonChangelog", true)
widget.setButtonEnabled("buttonCredits", false)
widget.setButtonEnabled("buttonInfo", true)
end
function buttonNext()
index = index + 1
if index >= #modslist then
checkedAll = true
widget.setButtonEnabled("close", true)
widget.setButtonEnabled("buttonNext", false)
end
displayInfo()
widget.setButtonEnabled("buttonPrevious", true)
end
function buttonPrevious()
index = index - 1
if index <= 1 then
widget.setButtonEnabled("buttonPrevious", false)
end
displayInfo()
widget.setButtonEnabled("buttonNext", true)
end |
--- A clickable button.
-- @classmod Button
-- @usage -- Create an empty button that prints when it is clicked
-- local button = Button(0, 0, 100, 100)
-- button.onClick = function(component, button)
-- print("Clicked with mouse button " .. button)
-- end
Button = class(Component)
--- The color of the outer border of this button.
Button.outerBorderColor = {0, 0, 0}
--- The color of the inner border of this button.
Button.innerBorderColor = {84, 84, 84}
--- The color of the inner border of this button when the mouse is over it.
Button.innerBorderHoverColor = {147, 147, 147}
--- The color of this button.
Button.color = {38, 38, 38}
--- The color of this button when the mouse is over it.
Button.hoverColor = {84, 84, 84}
--- Constructor
-- @section
--- Constructs a new Button.
--
-- @param x The x coordinate of the new component, relative to its parent.
-- @param y The y coordinate of the new component, relative to its parent.
-- @param width The width of the new component.
-- @param height The height of the new component.
function Button:_init(x, y, width, height)
Component._init(self)
self.mouseOver = false
self.x = x
self.y = y
self.width = width
self.height = height
end
--- @section end
function Button:update(dt)
if self.pressed and not self.mouseOver then
self:setPressed(false)
end
end
function Button:draw(dt)
local startX = self.x + self.offset[1]
local startY = self.y + self.offset[2]
local w = self.width
local h = self.height
local borderPoly = {
{startX + 1, startY + 0.5},
{startX + w - 1, startY + 0.5},
{startX + w - 0.5, startY + 1},
{startX + w - 0.5, startY + h - 1},
{startX + w - 1, startY + h - 0.5},
{startX + 1, startY + h - 0.5},
{startX + 0.5, startY + h - 1},
{startX + 0.5, startY + 1},
}
local innerBorderRect = {
startX + 1, startY + 1, startX + w - 1, startY + h - 1
}
local rectOffset = 1.5
local rect = {
startX + rectOffset, startY + rectOffset, startX + w - rectOffset, startY + h - rectOffset
}
PtUtil.drawPoly(borderPoly, self.outerBorderColor, 1)
if self.mouseOver then
PtUtil.drawRect(innerBorderRect, self.innerBorderHoverColor, 0.5)
PtUtil.fillRect(rect, self.hoverColor)
else
PtUtil.drawRect(innerBorderRect, self.innerBorderColor, 0.5)
PtUtil.fillRect(rect, self.color)
end
end
function Button:setPressed(pressed)
if pressed and not self.pressed then
self.x = self.x + 1
self.y = self.y - 1
self.layout = true
end
if not pressed and self.pressed then
self.x = self.x - 1
self.y = self.y + 1
self.layout = true
end
self.pressed = pressed
end
function Button:clickEvent(position, button, pressed)
if button <= 3 then
if self.onClick and not pressed and self.pressed then
self:onClick(button)
end
self:setPressed(pressed)
return true
end
end
--- Called when this button is clicked.
-- @function onClick
--
-- @param button The mouse button that was used.
|
wait(0.016666666666667)
Effects = {}
local Player = game.Players.localPlayer
local Character = Player.Character
local Humanoid = Character.Humanoid
local mouse = Player:GetMouse()
local m = Instance.new("Model", Character)
m.Name = "WeaponModel"
local LeftArm = Character["Left Arm"]
local RightArm = Character["Right Arm"]
local LeftLeg = Character["Left Leg"]
local RightLeg = Character["Right Leg"]
local Head = Character.Head
local Torso = Character.Torso
local cam = game.Workspace.CurrentCamera
local RootPart = Character.HumanoidRootPart
local RootJoint = RootPart.RootJoint
local equipped = false
local attack = false
local Anim = "Idle"
local idle = 0
local attacktype = 1
local Torsovelocity = RootPart.Velocity * Vector3.new(1, 0, 1).magnitude
local velocity = RootPart.Velocity.y
local sine = 0
local change = 1
local grabbed = false
local cf = CFrame.new
local mr = math.rad
local angles = CFrame.Angles
local ud = UDim2.new
local vt = Vector3.new
local c3 = Color3.new
local mana = 0
local mananum = 0
local it = Instance.new
local NeckCF = cf(0, 1, 0, -1, 0, 0, 0, 0, 1, 0, 1, 0)
local RootCF = CFrame.fromEulerAnglesXYZ(-1.57, 0, 3.14)
local RHCF = CFrame.fromEulerAnglesXYZ(0, 1.6, 0)
local LHCF = CFrame.fromEulerAnglesXYZ(0, -1.6, 0)
xenabled = true
cenabled = true
venabled = true
zenabled = true
RSH = nil
RW = Instance.new("Weld")
LW = Instance.new("Weld")
RH = Torso["Right Hip"]
LH = Torso["Left Hip"]
RSH = Torso["Right Shoulder"]
LSH = Torso["Left Shoulder"]
RSH.Parent = nil
LSH.Parent = nil
RW.Name = "RW"
RW.Part0 = Torso
RW.C0 = cf(1.5, 0.5, 0)
RW.C1 = cf(0, 0.5, 0)
RW.Part1 = RightArm
RW.Parent = Torso
LW.Name = "LW"
LW.Part0 = Torso
LW.C0 = cf(-1.5, 0.5, 0)
LW.C1 = cf(0, 0.5, 0)
LW.Part1 = LeftArm
LW.Parent = Torso
clerp = function(a, b, t)
return a:lerp(b, t)
end
----------------------------------------------------
z = Instance.new("Sound", Character)
z.SoundId = "rbxassetid://428255459"--
z.Looped = true
z.Pitch = 1
z.Volume = 1
wait(.1)
z:Play()
----------------------------------------------------
ArtificialHB = Instance.new("BindableEvent", script)
ArtificialHB.Name = "Heartbeat"
script:WaitForChild("Heartbeat")
frame = 0.016666666666667
tf = 0
allowframeloss = false
tossremainder = false
lastframe = tick()
script.Heartbeat:Fire()
game:GetService("RunService").Heartbeat:connect(function(s, p)
tf = tf + s
if frame <= tf then
if allowframeloss then
script.Heartbeat:Fire()
lastframe = tick()
else
for i = 1, math.floor(tf / frame) do
script.Heartbeat:Fire()
end
lastframe = tick()
end
if tossremainder then
tf = 0
else
tf = tf - frame * math.floor(tf / frame)
end
end
end
)
swait = function(num)
if num == 0 or num == nil then
ArtificialHB.Event:wait()
else
for i = 0, num do
ArtificialHB.Event:wait()
end
end
end
Magik = function(part)
Spawn(function()
local function lerp(a,b,c)
return a+(b-a)*c
end
local function rndRange(rng)
return math.random(-rng*1000,rng*1000)/1000
end
local magik = Instance.new("Part", part)
magik.Anchored = true
magik.Locked = true
magik.Material = "Neon"
magik.FormFactor = "Custom"
magik.Size = Vector3.new(1.2, 1.2, 1.2)
magik.TopSurface = "Smooth"
magik.BottomSurface = "Smooth"
magik.Transparency = 0
magik.CanCollide = false
magik.BrickColor = BrickColor.new("Royal purple")
local mr = math.rad
local rnx,rny,rnz = mr(rndRange(180)),mr(rndRange(180)),mr(rndRange(180))
local cf = part.CFrame * CFrame.new(0, -.8, 0) * CFrame.Angles(rnx,rny,rnz)
magik.CFrame = cf
for i = 0, 1, .05 do
local newTrans = lerp(.8, 1, i)
local ns = lerp(1,1.2,i)
magik.Transparency = newTrans
magik.Size = Vector3.new(ns,ns,ns)
magik.CFrame = cf
wait()
end
magik:Destroy()
wait()
end)
end
----------------------------------------------------
Magik2 = function(part)
Spawn(function()
local function lerp(a,b,c)
return a+(b-a)*c
end
local function rndRange(rng)
return math.random(-rng*1000,rng*1000)/1000
end
local magik2 = Instance.new("Part",part)
magik2.Anchored = true
magik2.Locked = true
magik2.FormFactor = "Custom"
magik2.Size = Vector3.new(1.2, 1.2, 1.2)
magik2.TopSurface = "Smooth"
magik2.BottomSurface = "Smooth"
magik2.Transparency = 0
magik2.Material = "Neon"
magik2.CanCollide = false
magik2.BrickColor = BrickColor.new("Really black")
local mr = math.rad
local rnx,rny,rnz = mr(rndRange(180)),mr(rndRange(180)),mr(rndRange(180))
local cf = part.CFrame * CFrame.new(0, -.8, 0) * CFrame.Angles(rnx,rny,rnz)
magik2.CFrame = cf
for i = 0, 1, .05 do
local newTrans = lerp(.8, 1, i)
local ns = lerp(1,1.2,i)
magik2.Transparency = newTrans
magik2.Size = Vector3.new(ns,ns,ns)
magik2.CFrame = cf
wait()
end
magik2:Destroy()
end)
end
Spawn(function()
while wait(.1) do
Magik(RightArm)
end
end)
Spawn(function()
while wait(.1) do
Magik2(RightArm)
end
end)
FloatPart = function()
local Part = Instance.new('Part',Torso)
Part.CFrame = CFrame.new(Torso.CFrame.X,workspace.Base.CFrame.Y+1,Torso.CFrame.Z) * CFrame.fromEulerAnglesXYZ(86.4,0,87)
Part.Anchored = true
Part.Material = 'Neon'
Part.CanCollide = false
Part.BrickColor = BrickColor.new(PrimaryColor)
local Mesh = Instance.new('SpecialMesh',Part)
Mesh.Scale = Vector3.new(4,4,.2)
Mesh.MeshId = 'http://www.roblox.com/asset/?id=3270017'
Mesh.VertexColor = Vector3.new(0,170,255)
spawn(function()
for i = 1,30 do
Mesh.Scale = Mesh.Scale + Vector3.new(.04,.04,0)
Part.Transparency = Part.Transparency + .035
game["Run Service"].RenderStepped:wait()
end
Part:Destroy()
end)
end;
DubPart = function()
local Part = Instance.new('Part',Torso)
Part.CFrame = CFrame.new(Torso.CFrame.X,workspace.Base.CFrame.Y+1,Torso.CFrame.Z) * CFrame.fromEulerAnglesXYZ(86.4,0,87)
Part.Anchored = true
Part.CanCollide = false
Part.Material = 'Neon'
Part.BrickColor = BrickColor.new(SecondaryColor)
local Mesh = Instance.new('SpecialMesh',Part)
Mesh.Scale = Vector3.new(7,7,.2)
Mesh.MeshId = 'http://www.roblox.com/asset/?id=3270017'
Mesh.VertexColor = Vector3.new(0,170,255)
spawn(function()
for i = 1,30 do
Mesh.Scale = Mesh.Scale + Vector3.new(.04,.04,0)
Part.Transparency = Part.Transparency + .035
game["Run Service"].RenderStepped:wait()
end
Part:Destroy()
end)
end;
Fade = function(Item,t)
spawn(function()
for i = 1,20 do
Item.Transparency = Item.Transparency + .05
if t then
wait(t)
else
wait()
end
end
Item:Destroy()
end)
end
Particle = function(PrimaryColor)
local Part = Instance.new('Part',Torso)
Part.BrickColor = BrickColor.new(PrimaryColor)
Part.Anchored = true
Part.Transparency = .3
Part.CanCollide = false
Part.CFrame = Torso.CFrame * CFrame.new(math.random(-10,10),math.random(-15,15),math.random(-10,10)) * CFrame.fromEulerAnglesXYZ(math.random(),math.random(),math.random())
local Mesh = Instance.new('BlockMesh',Part)
Mesh.Scale = Vector3.new(.05,.1,.1)
spawn(function()
for i = 1,40 do
Part.Transparency = Part.Transparency + .0125
Part.CFrame = Part.CFrame * CFrame.new(0,-.07,0)
game["Run Service"].RenderStepped:wait()
end
Part:Destroy()
end)
end;
--[[spawn(function()
while wait() do
wait(.05)
FloatPart()
wait(.08)
FloatPart()
wait(.05)
DubPart()
wait(.08)
end
end)]]
game["Run Service"].RenderStepped:connect(function(_)
Particle("Royal purple")
Particle("Really black")
--Character['HumanoidRootPart'].C1 = Character['HumanoidRootPart'].C1 * CFrame.new(0,Height+math.sin(tick())/150,0)
end)
particle = function(parent, col1, col2, lightemis, size, texture, transparency, zoffset, accel, drag, ltp, velinher, emisdir, enabled, lifetime, rate, rotation, rotspeed, speed, velspread)
local fp = it("ParticleEmitter")
fp.Parent = parent
fp.Color = cs(col1, col2)
fp.LightEmission = lightemis
fp.Size = size
fp.Texture = texture
fp.Transparency = transparency
fp.ZOffset = zoffset
fp.Acceleration = accel
fp.Drag = drag
fp.LockedToPart = ltp
fp.VelocityInheritance = velinher
fp.EmissionDirection = emisdir
fp.Enabled = enabled
fp.Lifetime = lifetime
fp.Rate = rate
fp.Rotation = rotation
fp.RotSpeed = rotspeed
fp.Speed = speed
fp.VelocitySpread = velspread
return fp
end
local fengui = it("GuiMain")
fengui.Parent = Player.PlayerGui
fengui.Name = "WeaponGUI"
local fenframe1 = it("TextLabel")
fenframe1.Parent = fengui
fenframe1.BackgroundColor3 = Color3.new(0.19607843137255, 0.19607843137255, 0.19607843137255)
fenframe1.BackgroundTransparency = 0.3
fenframe1.BorderSizePixel = 5
fenframe1.BorderColor3 = Color3.new(1, 1, 1)
fenframe1.Size = UDim2.new(0.05, 0, 0.1, 0)
fenframe1.Position = UDim2.new(0.325, 0, 0.7, 0)
fenframe1.Text = "Z"
fenframe1.TextWrapped = true
fenframe1.FontSize = 7
fenframe1.TextColor3 = Color3.new(1, 1, 1)
local fenframe1a = it("TextLabel")
fenframe1a.Parent = fengui
fenframe1a.BackgroundColor3 = Color3.new(0.7843137254902, 0.7843137254902, 0.7843137254902)
fenframe1a.BackgroundTransparency = 0.3
fenframe1a.BorderSizePixel = 5
fenframe1a.BorderColor3 = Color3.new(1, 1, 1)
fenframe1a.Size = UDim2.new(0.05, 0, 0.1, 0)
fenframe1a.Position = UDim2.new(0.325, 0, 0.7, 0)
fenframe1a.Text = ""
local fenframe2 = it("TextLabel")
fenframe2.Parent = fengui
fenframe2.BackgroundColor3 = Color3.new(0.19607843137255, 0.19607843137255, 0.19607843137255)
fenframe2.BackgroundTransparency = 0.3
fenframe2.BorderSizePixel = 5
fenframe2.BorderColor3 = Color3.new(1, 1, 1)
fenframe2.Size = UDim2.new(0.05, 0, 0.1, 0)
fenframe2.Position = UDim2.new(0.425, 0, 0.7, 0)
fenframe2.Text = "X"
fenframe2.TextWrapped = true
fenframe2.FontSize = 7
fenframe2.TextColor3 = Color3.new(1, 1, 1)
local fenframe2a = it("TextLabel")
fenframe2a.Parent = fengui
fenframe2a.BackgroundColor3 = Color3.new(0.7843137254902, 0.7843137254902, 0.7843137254902)
fenframe2a.BackgroundTransparency = 0.3
fenframe2a.BorderSizePixel = 5
fenframe2a.BorderColor3 = Color3.new(1, 1, 1)
fenframe2a.Size = UDim2.new(0.05, 0, 0.1, 0)
fenframe2a.Position = UDim2.new(0.425, 0, 0.7, 0)
fenframe2a.Text = ""
local fenframe3 = it("TextLabel")
fenframe3.Parent = fengui
fenframe3.BackgroundColor3 = Color3.new(0.19607843137255, 0.19607843137255, 0.19607843137255)
fenframe3.BackgroundTransparency = 0.3
fenframe3.BorderSizePixel = 5
fenframe3.BorderColor3 = Color3.new(1, 1, 1)
fenframe3.Size = UDim2.new(0.05, 0, 0.1, 0)
fenframe3.Position = UDim2.new(0.525, 0, 0.7, 0)
fenframe3.Text = "C"
fenframe3.TextWrapped = true
fenframe3.FontSize = 7
fenframe3.TextColor3 = Color3.new(1, 1, 1)
local fenframe3a = it("TextLabel")
fenframe3a.Parent = fengui
fenframe3a.BackgroundColor3 = Color3.new(0.7843137254902, 0.7843137254902, 0.7843137254902)
fenframe3a.BackgroundTransparency = 0.3
fenframe3a.BorderSizePixel = 5
fenframe3a.BorderColor3 = Color3.new(1, 1, 1)
fenframe3a.Size = UDim2.new(0.05, 0, 0.1, 0)
fenframe3a.Position = UDim2.new(0.525, 0, 0.7, 0)
fenframe3a.Text = ""
local fenframe4 = it("TextLabel")
fenframe4.Parent = fengui
fenframe4.BackgroundColor3 = Color3.new(0.19607843137255, 0.19607843137255, 0.19607843137255)
fenframe4.BackgroundTransparency = 0.3
fenframe4.BorderSizePixel = 5
fenframe4.BorderColor3 = Color3.new(1, 1, 1)
fenframe4.Size = UDim2.new(0.05, 0, 0.1, 0)
fenframe4.Position = UDim2.new(0.625, 0, 0.7, 0)
fenframe4.Text = "V"
fenframe4.TextWrapped = true
fenframe4.FontSize = 7
fenframe4.TextColor3 = Color3.new(1, 1, 1)
local fenframe4a = it("TextLabel")
fenframe4a.Parent = fengui
fenframe4a.BackgroundColor3 = Color3.new(0.7843137254902, 0.7843137254902, 0.7843137254902)
fenframe4a.BackgroundTransparency = 0.3
fenframe4a.BorderSizePixel = 5
fenframe4a.BorderColor3 = Color3.new(1, 1, 1)
fenframe4a.Size = UDim2.new(0.05, 0, 0.1, 0)
fenframe4a.Position = UDim2.new(0.625, 0, 0.7, 0)
fenframe4a.Text = ""
fenframe1a.Size = UDim2.new(0, 0, 0.1, 0)
fenframe2a.Size = UDim2.new(0, 0, 0.1, 0)
fenframe3a.Size = UDim2.new(0, 0, 0.1, 0)
fenframe4a.Size = UDim2.new(0, 0, 0.1, 0)
local RbxUtility = LoadLibrary("RbxUtility")
local Create = RbxUtility.Create
RemoveOutlines = function(part)
part.TopSurface = 10
end
CreatePart = function(Parent, Material, Reflectance, Transparency, BColor, Name, Size)
local Part = Create("Part")({Parent = Parent, Reflectance = Reflectance, Transparency = Transparency, CanCollide = false, Locked = true, BrickColor = BrickColor.new(tostring(BColor)), Name = Name, Size = Size, Material = Material})
RemoveOutlines(Part)
return Part
end
CreateMesh = function(Mesh, Part, MeshType, MeshId, OffSet, Scale)
local Msh = Create(Mesh)({Parent = Part, Offset = OffSet, Scale = Scale})
if Mesh == "SpecialMesh" then
Msh.MeshType = MeshType
Msh.MeshId = MeshId
end
return Msh
end
CreateWeld = function(Parent, Part0, Part1, C0, C1)
local Weld = Create("Weld")({Parent = Parent, Part0 = Part0, Part1 = Part1, C0 = C0, C1 = C1})
return Weld
end
Damagefunc = function(Part, hit, minim, maxim, knockback, Type, Property, Delay, HitSound, HitPitch)
if hit.Parent == nil then
return
end
local h = hit.Parent:FindFirstChild("Humanoid")
for _,v in pairs(hit.Parent:children()) do
if v:IsA("Humanoid") then
h = v
end
end
if h ~= nil and hit.Parent.Name ~= Character.Name and hit.Parent:FindFirstChild("Torso") ~= nil then
if hit.Parent:findFirstChild("DebounceHit") ~= nil and hit.Parent.DebounceHit.Value == true then
return
end
local c = Create("ObjectValue")({Name = "creator", Value = game:service("Players").LocalPlayer, Parent = h})
game:GetService("Debris"):AddItem(c, 0.5)
if HitSound ~= nil and HitPitch ~= nil then
CreateSound(HitSound, hit, 1, HitPitch)
end
local Damage = math.random(minim, maxim)
local blocked = false
local block = hit.Parent:findFirstChild("Block")
if block ~= nil and block.className == "IntValue" and block.Value > 0 then
blocked = true
block.Value = block.Value - 1
print(block.Value)
end
if blocked == false then
HitHealth = h.Health
h.Health = h.Health - Damage
if mana < 100 then
mana = mana + math.random(5, 10)
end
if mana > 100 then
mana = 100
end
if HitHealth ~= h.Health and HitHealth ~= 0 and h.Health <= 0 and h.Parent.Name ~= "Lost Soul" then
end
ShowDamage(Part.CFrame * CFrame.new(0, 0, Part.Size.Z / 2).p + Vector3.new(0, 1.5, 0), -Damage, 1.5, Part.BrickColor.Color)
else
h.Health = h.Health - Damage / 2
ShowDamage(Part.CFrame * CFrame.new(0, 0, Part.Size.Z / 2).p + Vector3.new(0, 1.5, 0), -Damage, 1.5, Part.BrickColor.Color)
end
if Type == "Knockdown" then
local hum = hit.Parent.Humanoid
hum.PlatformStand = true
coroutine.resume(coroutine.create(function(HHumanoid)
swait(1)
HHumanoid.PlatformStand = false
end
), hum)
local angle = hit.Position - (Property.Position + Vector3.new(0, 0, 0)).unit
local bodvol = Create("BodyVelocity")({velocity = angle * knockback, P = 5000, maxForce = Vector3.new(8000, 8000, 8000), Parent = hit})
local rl = Create("BodyAngularVelocity")({P = 3000, maxTorque = Vector3.new(500000, 500000, 500000) * 50000000000000, angularvelocity = Vector3.new(math.random(-10, 10), math.random(-10, 10), math.random(-10, 10)), Parent = hit})
game:GetService("Debris"):AddItem(bodvol, 0.5)
game:GetService("Debris"):AddItem(rl, 0.5)
else
do
if Type == "Normal" then
local vp = Create("BodyVelocity")({P = 500, maxForce = Vector3.new(math.huge, 0, math.huge), velocity = Property.CFrame.lookVector * knockback + Property.Velocity / 1.05})
if knockback > 0 then
vp.Parent = hit.Parent.Torso
end
game:GetService("Debris"):AddItem(vp, 0.5)
else
do
if Type == "Up" then
local bodyVelocity = Create("BodyVelocity")({velocity = vt(0, 20, 0), P = 5000, maxForce = Vector3.new(8000, 8000, 8000), Parent = hit})
game:GetService("Debris"):AddItem(bodyVelocity, 0.5)
else
do
if Type == "DarkUp" then
coroutine.resume(coroutine.create(function()
for i = 0, 1, 0.1 do
swait()
BlockEffect(BrickColor.new("Black"), hit.Parent.Torso.CFrame, 5, 5, 5, 1, 1, 1, 0.08, 1)
end
end
))
local bodyVelocity = Create("BodyVelocity")({velocity = vt(0, 20, 0), P = 5000, maxForce = Vector3.new(8000, 8000, 8000), Parent = hit})
game:GetService("Debris"):AddItem(bodyVelocity, 1)
else
do
if Type == "Snare" then
local bp = Create("BodyPosition")({P = 2000, D = 100, maxForce = Vector3.new(math.huge, math.huge, math.huge), position = hit.Parent.Torso.Position, Parent = hit.Parent.Torso})
game:GetService("Debris"):AddItem(bp, 1)
else
do
if Type == "Freeze" then
local BodPos = Create("BodyPosition")({P = 50000, D = 1000, maxForce = Vector3.new(math.huge, math.huge, math.huge), position = hit.Parent.Torso.Position, Parent = hit.Parent.Torso})
local BodGy = Create("BodyGyro")({maxTorque = Vector3.new(400000, 400000, 400000) * math.huge, P = 20000, Parent = hit.Parent.Torso, cframe = hit.Parent.Torso.CFrame})
hit.Parent.Torso.Anchored = true
coroutine.resume(coroutine.create(function(Part)
swait(1.5)
Part.Anchored = false
end
), hit.Parent.Torso)
game:GetService("Debris"):AddItem(BodPos, 3)
game:GetService("Debris"):AddItem(BodGy, 3)
end
do
local debounce = Create("BoolValue")({Name = "DebounceHit", Parent = hit.Parent, Value = true})
game:GetService("Debris"):AddItem(debounce, Delay)
c = Instance.new("ObjectValue")
c.Name = "creator"
c.Value = Player
c.Parent = h
game:GetService("Debris"):AddItem(c, 0.5)
end
end
end
end
end
end
end
end
end
end
end
end
end
ShowDamage = function(Pos, Text, Time, Color)
local Rate = 0.033333333333333
if not Pos then
local Pos = Vector3.new(0, 0, 0)
end
local Text = Text or ""
local Time = Time or 2
if not Color then
local Color = Color3.new(1, 0, 1)
end
local EffectPart = CreatePart(workspace, "Marble", 0, 1, BrickColor.new(Color), "Effect", vt(0, 0, 0))
EffectPart.Anchored = true
local BillboardGui = Create("BillboardGui")({Size = UDim2.new(3, 0, 3, 0), Adornee = EffectPart, Parent = EffectPart})
local TextLabel = Create("TextLabel")({BackgroundTransparency = 1, Size = UDim2.new(1, 0, 1, 0), Text = Text, TextColor3 = Color, TextScaled = true, Font = Enum.Font.ArialBold, Parent = BillboardGui})
game.Debris:AddItem(EffectPart, Time + 0.1)
EffectPart.Parent = game:GetService("Workspace")
delay(0, function()
local Frames = Time / Rate
for Frame = 1, Frames do
wait(Rate)
local Percent = Frame / Frames
EffectPart.CFrame = CFrame.new(Pos) + Vector3.new(0, Percent, 0)
TextLabel.TextTransparency = Percent
end
if EffectPart and EffectPart.Parent then
EffectPart:Destroy()
end
end
)
end
MagniDamage = function(Part, magni, mindam, maxdam, knock, Type)
for _,c in pairs(workspace:children()) do
local hum = c:findFirstChild("Humanoid")
if hum ~= nil then
local head = c:findFirstChild("Torso")
if head ~= nil then
local targ = head.Position - Part.Position
local mag = targ.magnitude
if mag <= magni and c.Name ~= Player.Name then
Damagefunc(head, head, mindam, maxdam, knock, Type, RootPart, 0.1, "http://www.roblox.com/asset/?id=231917784", 1)
end
end
end
end
end
Handle = CreatePart(m, Enum.Material.Marble, 0, 1, "Royal purple", "Handle", Vector3.new(0.200000003, 1.57000017, 0.200000003))
HandleWeld = CreateWeld(m, Character["Right Arm"], Handle, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-0.982839942, 0.146006823, 0.234023571, 0.211453959, -0.977137685, 0.0221185088, -0.0402157828, -0.0313093588, -0.99870044, 0.976560295, 0.210289627, -0.0459168404))
CreateMesh("CylinderMesh", Handle, "", "", Vector3.new(0, 0, 0), Vector3.new(1.5, 1, 1.5))
FakeHandle = CreatePart(m, Enum.Material.Marble, 0, 1, "Royal purple", "FakeHandle", Vector3.new(0.200000003, 1.57000017, 0.200000003))
FakeHandleWeld = CreateWeld(m, Handle, FakeHandle, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0, 0, 0, 1, 3.7252903e-009, 6.4028427e-009, 3.7252903e-009, 1.00000012, 0, 6.4028427e-009, 0, 1.00000012))
Part = CreatePart(m, Enum.Material.Marble, 0, 0, "Black", "Part", Vector3.new(0.200000003, 1, 0.200000003))
PartWeld = CreateWeld(m, FakeHandle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(1.07288361e-006, 0.683865368, -4.76837158e-007, 1, 3.7252903e-009, 6.4028427e-009, 3.7252903e-009, 1.00000012, 0, 6.4028427e-009, 0, 1.00000012))
CreateMesh("CylinderMesh", Part, "", "", Vector3.new(0, 0, 0), Vector3.new(2, 0.5, 2))
Cone = CreatePart(m, Enum.Material.Neon, 0, 0, "Royal purple", "Cone", Vector3.new(1, 1.01999998, 1))
ConeWeld = CreateWeld(m, FakeHandle, Cone, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-3.31791997, -0.975689411, 2.925138, 3.06405127e-006, 0.707111418, 0.707102299, -0.999756992, 0.0155918654, -0.0155877285, -0.0220473036, -0.706930399, 0.706939638))
CreateMesh("SpecialMesh", Cone, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=1778999", Vector3.new(0, 0, 0), Vector3.new(0.200000003, 0.5, 0.200000003))
Part = CreatePart(m, Enum.Material.Marble, 0, 0, "Black", "Part", Vector3.new(1, 0.729999959, 1))
PartWeld = CreateWeld(m, FakeHandle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(1.4692868, -3.70743895, -1.52587891e-005, 0.916809797, -0.399324507, 1.15483999e-006, 0.399324447, 0.916809678, -4.00096178e-006, 5.56348823e-007, 4.12762165e-006, 1))
CreateMesh("CylinderMesh", Part, "", "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 0.200000003))
Cone = CreatePart(m, Enum.Material.Neon, 0, 0, "Royal purple", "Cone", Vector3.new(1, 1.01999998, 1))
ConeWeld = CreateWeld(m, FakeHandle, Cone, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-3.31796861, -0.99111104, 3.62495184, 3.06405127e-006, 0.707111418, 0.707102299, -0.999756992, 0.0155918654, -0.0155877285, -0.0220473036, -0.706930399, 0.706939638))
CreateMesh("SpecialMesh", Cone, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=1778999", Vector3.new(0, 0, 0), Vector3.new(0.200000003, 0.5, 0.200000003))
Cone = CreatePart(m, Enum.Material.Marble, 0, 0, "Royal purple", "Cone", Vector3.new(1, 1.01999998, 1))
ConeWeld = CreateWeld(m, FakeHandle, Cone, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(4.64674854, -0.903340101, -0.354405403, -1.83284283e-006, -1.00000012, 3.39746475e-006, -0.999756992, 1.90362334e-006, 0.0220472421, -0.0220472496, -3.36021185e-006, -0.999756992))
CreateMesh("SpecialMesh", Cone, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=1778999", Vector3.new(0, 0, 0), Vector3.new(0.200000003, 0.5, 0.200000003))
Cone = CreatePart(m, Enum.Material.Neon, 0, 0, "Royal purple", "Cone", Vector3.new(1, 1.01999998, 1))
ConeWeld = CreateWeld(m, FakeHandle, Cone, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-0.0155968666, -0.981806874, 5.01632404, 4.59002331e-006, 1.38655305e-005, 1, -0.999757051, 0.0220471006, 4.27453779e-006, -0.0220471006, -0.999757051, 1.39661133e-005))
CreateMesh("SpecialMesh", Cone, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=1778999", Vector3.new(0, 0, 0), Vector3.new(0.200000003, 0.5, 0.200000003))
Cone = CreatePart(m, Enum.Material.Marble, 0, 0, "Royal purple", "Cone", Vector3.new(1, 1.01999998, 1))
ConeWeld = CreateWeld(m, FakeHandle, Cone, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-0.015683651, -0.99636519, 4.31590414, 4.59002331e-006, 1.38655305e-005, 1, -0.999757051, 0.0220471006, 4.27453779e-006, -0.0220471006, -0.999757051, 1.39661133e-005))
CreateMesh("SpecialMesh", Cone, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=1778999", Vector3.new(0, 0, 0), Vector3.new(0.200000003, 0.5, 0.200000003))
Cone = CreatePart(m, Enum.Material.Neon, 0, 0, "Royal purple", "Cone", Vector3.new(1, 1.01999998, 1))
ConeWeld = CreateWeld(m, FakeHandle, Cone, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(3.2746892, -0.975648642, 2.9260354, 2.64961272e-006, -0.707099259, 0.707114458, -0.999756992, 0.0155881718, 0.0155915832, -0.0220474396, -0.706942558, -0.706927299))
CreateMesh("SpecialMesh", Cone, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=1778999", Vector3.new(0, 0, 0), Vector3.new(0.200000003, 0.5, 0.200000003))
Cone = CreatePart(m, Enum.Material.Marble, 0, 0, "Royal purple", "Cone", Vector3.new(1, 1.01999998, 1))
ConeWeld = CreateWeld(m, FakeHandle, Cone, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(3.27468133, -0.991158009, 3.62575912, 2.64961272e-006, -0.707099259, 0.707114458, -0.999756992, 0.0155881718, 0.0155915832, -0.0220474396, -0.706942558, -0.706927299))
CreateMesh("SpecialMesh", Cone, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=1778999", Vector3.new(0, 0, 0), Vector3.new(0.200000003, 0.5, 0.200000003))
Cone = CreatePart(m, Enum.Material.Neon, 0, 0, "Royal purple", "Cone", Vector3.new(1, 1.01999998, 1))
ConeWeld = CreateWeld(m, FakeHandle, Cone, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-0.0155587196, -1.11407149, 4.663311, 4.59002331e-006, 1.38655305e-005, 1, -0.999757051, 0.0220471006, 4.27453779e-006, -0.0220471006, -0.999757051, 1.39661133e-005))
CreateMesh("SpecialMesh", Cone, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=1778999", Vector3.new(0, 0, 0), Vector3.new(0.550000012, 1, 0.550000012))
Cone = CreatePart(m, Enum.Material.Marble, 0, 0, "Royal purple", "Cone", Vector3.new(1, 1.01999998, 1))
ConeWeld = CreateWeld(m, FakeHandle, Cone, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0.0131573677, 0.00466442108, 4.61167336, -1.74657907e-006, -1.09747052e-005, -1.00000012, 0.764525652, -0.644593418, 5.77419996e-006, -0.644593358, -0.764525771, 9.49576497e-006))
CreateMesh("SpecialMesh", Cone, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=1778999", Vector3.new(0, 0, 0), Vector3.new(0.550000012, 1, 0.550000012))
Cone = CreatePart(m, Enum.Material.Neon, 0, 0, "Royal purple", "Cone", Vector3.new(1, 1.01999998, 1))
ConeWeld = CreateWeld(m, FakeHandle, Cone, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(4.6467495, -0.918762922, 0.345379829, -1.83284283e-006, -1.00000012, 3.39746475e-006, -0.999756992, 1.90362334e-006, 0.0220472421, -0.0220472496, -3.36021185e-006, -0.999756992))
CreateMesh("SpecialMesh", Cone, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=1778999", Vector3.new(0, 0, 0), Vector3.new(0.200000003, 0.5, 0.200000003))
Cone = CreatePart(m, Enum.Material.Marble, 0, 0, "Royal purple", "Cone", Vector3.new(0.200000003, 0.200000003, 0.200000003))
ConeWeld = CreateWeld(m, FakeHandle, Cone, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-0.00376915932, -3.44346094, -0.00172424316, -1.00000012, -1.70432031e-006, 1.69267878e-007, 1.70432031e-006, -1.00000012, -2.12341547e-007, 1.75088644e-007, -2.12341547e-007, 1.00000012))
CreateMesh("SpecialMesh", Cone, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=1778999", Vector3.new(0, 0, 0), Vector3.new(0.200000003, 0.300000012, 0.200000003))
Part = CreatePart(m, Enum.Material.Neon, 0, 0, "Royal purple", "Part", Vector3.new(1, 1, 1))
PartWeld = CreateWeld(m, FakeHandle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-1.31130219e-006, -3.5749507, 0, 1, 3.7252903e-009, 6.4028427e-009, 3.7252903e-009, 1.00000012, 0, 6.4028427e-009, 0, 1.00000012))
CreateMesh("CylinderMesh", Part, "", "", Vector3.new(0, 0, 0), Vector3.new(1, 0.5, 0.400000006))
Part = CreatePart(m, Enum.Material.Neon, 0, 0, "Royal purple", "Part", Vector3.new(0.200000003, 4.57000017, 0.200000003))
PartWeld = CreateWeld(m, FakeHandle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(5.96046448e-007, -1.50000107, 9.53674316e-007, 1, 3.7252903e-009, 6.4028427e-009, 3.7252903e-009, 1.00000012, 0, 6.4028427e-009, 0, 1.00000012))
CreateMesh("CylinderMesh", Part, "", "", Vector3.new(0, 0, 0), Vector3.new(1.5, 1, 1.5))
Part = CreatePart(m, Enum.Material.Marble, 0, 0, "Black", "Part", Vector3.new(1, 1.16999996, 1))
PartWeld = CreateWeld(m, FakeHandle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-4.68149614, -0.0198745728, -1.09672546e-005, 0.0220478568, 0.999756992, -2.0749867e-006, -0.999756932, 0.0220478605, -1.48452818e-006, -1.42678618e-006, 2.10851431e-006, 1.00000012))
CreateMesh("CylinderMesh", Part, "", "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 1))
Part = CreatePart(m, Enum.Material.Neon, 0, 0, "Royal purple", "Part", Vector3.new(1, 0.870000005, 1))
PartWeld = CreateWeld(m, FakeHandle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-4.71543217, -0.0690839291, -9.53674316e-006, 0.19052954, 0.981681645, -1.97067857e-006, -0.981681526, 0.190529525, -1.91386789e-006, -1.49046537e-006, 2.29105353e-006, 1.00000012))
CreateMesh("CylinderMesh", Part, "", "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 0.899999976))
Part22 = CreatePart(m, Enum.Material.Marble, 0, 0, "Black", "Part22", Vector3.new(1, 0.729999959, 1))
PartWeld = CreateWeld(m, FakeHandle, Part22, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-1.51120782, -3.69066477, -7.15255737e-006, 0.911903143, 0.410405785, -3.35276127e-007, -0.410405725, 0.911903143, -1.79186463e-006, -4.35044058e-007, 1.76206231e-006, 1.00000012))
CreateMesh("CylinderMesh", Part, "", "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 0.200000003))
Part = CreatePart(m, Enum.Material.Neon, 0, 0, "Royal purple", "Part", Vector3.new(1, 0.870000005, 1))
PartWeld = CreateWeld(m, FakeHandle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-4.71087646, -0.0231897831, -6.19888306e-006, 0.318961442, 0.947767794, -1.48266554e-006, -0.947767675, 0.318961442, -2.70921737e-006, -2.10118014e-006, 2.26870179e-006, 1.00000012))
CreateMesh("CylinderMesh", Part, "", "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 0.850000024))
Part = CreatePart(m, Enum.Material.Marble, 0, 0, "Black", "Part", Vector3.new(1, 0.769999981, 1))
PartWeld = CreateWeld(m, FakeHandle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-4.68154573, -0.4009372, -5.7220459e-006, 0.516243339, 0.856442034, -8.04662704e-007, -0.856442034, 0.516243339, -4.18536365e-006, -3.15741636e-006, 2.8423965e-006, 1.00000012))
CreateMesh("CylinderMesh", Part, "", "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 0.800000012))
Part = CreatePart(m, Enum.Material.Neon, 0, 0, "Royal purple", "Part", Vector3.new(0.200000003, 2.57999992, 0.200000003))
PartWeld = CreateWeld(m, FakeHandle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(3.4570694e-006, 1.91385686, 4.76837158e-007, 1, 3.7252903e-009, 6.4028427e-009, 3.7252903e-009, 1.00000012, 0, 6.4028427e-009, 0, 1.00000012))
CreateMesh("CylinderMesh", Part, "", "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 1))
Hitbox = CreatePart(m, Enum.Material.Marble, 0, 1, "Black", "Hitbox", Vector3.new(2.4000001, 3.67000008, 0.399999976))
HitboxWeld = CreateWeld(m, FakeHandle, Hitbox, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-1.76720476, 3.04898357, 0.00860214233, -0.699169815, 0.713988841, 0.0371726528, -0.713755548, -0.700063348, 0.0215496495, 0.0414094217, -0.0114653222, 0.999076545))
rayCast = function(Position, Direction, Range, Ignore)
return game:service("Workspace"):FindPartOnRay(Ray.new(Position, Direction.unit * (Range or 999.999)), Ignore)
end
Spawn(function()
while wait() do
Magik(LeftArm)
end
end)
Spawn(function()
while wait() do
Magik2(LeftArm)
end
end)
CreateSound = function(id, parent, vol, pit, looped)
coroutine.resume(coroutine.create(function()
local sou = Instance.new("Sound", parent or workspace)
sou.Volume = vol
sou.Pitch = pit or 1
sou.SoundId = id
sou.Looped = looped
swait()
sou:play()
game:GetService("Debris"):AddItem(sou, 6)
end
))
end
local getclosest = function(obj, distance)
local last, lastx = distance + 1, nil
for i,v in pairs(workspace:GetChildren()) do
if v:IsA("Model") and v ~= Character and v:findFirstChild("Humanoid") and v:findFirstChild("Torso") and v:findFirstChild("Humanoid").Health > 0 then
local t = v.Torso
local dist = t.Position - obj.Position.magnitude
if dist <= distance and dist < last then
last = dist
lastx = v
end
end
end
return lastx
end
BlockEffect = function(brickcolor, cframe, x1, y1, z1, x3, y3, z3, delay, Type)
local prt = CreatePart(workspace, "Marble", 0, 0, brickcolor, "Effect", Vector3.new())
prt.Anchored = true
prt.CFrame = cframe
local msh = CreateMesh("BlockMesh", prt, "", "", Vector3.new(0, 0, 0), Vector3.new(x1, y1, z1))
game:GetService("Debris"):AddItem(prt, 10)
if Type == 1 or Type == nil then
table.insert(Effects, {prt, "Block1", delay, x3, y3, z3, msh})
else
if Type == 2 then
table.insert(Effects, {prt, "Block2", delay, x3, y3, z3, msh})
end
end
end
SphereEffect = function(brickcolor, cframe, x1, y1, z1, x3, y3, z3, delay)
local prt = CreatePart(workspace, "Marble", 0, 0, brickcolor, "Effect", Vector3.new())
prt.Anchored = true
prt.CFrame = cframe
local msh = CreateMesh("SpecialMesh", prt, "Sphere", "", Vector3.new(0, 0, 0), Vector3.new(x1, y1, z1))
game:GetService("Debris"):AddItem(prt, 10)
table.insert(Effects, {prt, "Cylinder", delay, x3, y3, z3, msh})
end
RingEffect = function(brickcolor, cframe, x1, y1, z1, x3, y3, z3, delay)
local prt = CreatePart(workspace, "Marble", 0, 0, brickcolor, "Effect", Vector3.new(0.5, 0.5, 0.5))
prt.Anchored = true
prt.CFrame = cframe * CFrame.new(x1, y1, z1)
local msh = CreateMesh("SpecialMesh", prt, "FileMesh", "rbxassetid://3270017", Vector3.new(0, 0, 0), Vector3.new(x1, y1, z1))
game:GetService("Debris"):AddItem(prt, 10)
table.insert(Effects, {prt, "Cylinder", delay, x3, y3, z3, msh})
end
CylinderEffect = function(brickcolor, cframe, x1, y1, z1, x3, y3, z3, delay)
local prt = CreatePart(workspace, "Marble", 0, 0, brickcolor, "Effect", Vector3.new())
prt.Anchored = true
prt.CFrame = cframe
local msh = CreateMesh("CylinderMesh", prt, "", "", Vector3.new(0, 0, 0), Vector3.new(x1, y1, z1))
game:GetService("Debris"):AddItem(prt, 10)
table.insert(Effects, {prt, "Cylinder", delay, x3, y3, z3, msh})
end
WaveEffect = function(brickcolor, cframe, x1, y1, z1, x3, y3, z3, delay)
local prt = CreatePart(workspace, "Marble", 0, 0, brickcolor, "Effect", Vector3.new())
prt.Anchored = true
prt.CFrame = cframe
local msh = CreateMesh("SpecialMesh", prt, "FileMesh", "rbxassetid://20329976", Vector3.new(0, 0, 0), Vector3.new(x1, y1, z1))
game:GetService("Debris"):AddItem(prt, 10)
table.insert(Effects, {prt, "Cylinder", delay, x3, y3, z3, msh})
end
SpecialEffect = function(brickcolor, cframe, x1, y1, z1, x3, y3, z3, delay)
local prt = CreatePart(workspace, "Marble", 0, 0, brickcolor, "Effect", Vector3.new())
prt.Anchored = true
prt.CFrame = cframe
local msh = CreateMesh("SpecialMesh", prt, "FileMesh", "rbxassetid://24388358", Vector3.new(0, 0, 0), Vector3.new(x1, y1, z1))
game:GetService("Debris"):AddItem(prt, 10)
table.insert(Effects, {prt, "Cylinder", delay, x3, y3, z3, msh})
end
DragonEffect = function(brickcolor, cframe, x1, y1, z1, x3, y3, z3, delay)
local prt = CreatePart(workspace, "Marble", 0, 0, brickcolor, "Effect", Vector3.new())
prt.Anchored = true
prt.CFrame = cframe
local msh = CreateMesh("SpecialMesh", prt, "FileMesh", "rbxassetid://51177741", Vector3.new(0, 0, 0), Vector3.new(x1, y1, z1))
game:GetService("Debris"):AddItem(prt, 10)
table.insert(Effects, {prt, "Cylinder", delay, x3, y3, z3, msh})
end
BreakEffect = function(brickcolor, cframe, x1, y1, z1)
local prt = CreatePart(workspace, "Marble", 0, 0, brickcolor, "Effect", Vector3.new(0.5, 0.5, 0.5))
prt.Anchored = true
prt.CFrame = cframe * CFrame.fromEulerAnglesXYZ(math.random(-50, 50), math.random(-50, 50), math.random(-50, 50))
local msh = CreateMesh("SpecialMesh", prt, "Sphere", "", Vector3.new(0, 0, 0), Vector3.new(x1, y1, z1))
local num = math.random(10, 50) / 1000
game:GetService("Debris"):AddItem(prt, 10)
table.insert(Effects, {prt, "Shatter", num, prt.CFrame, math.random() - math.random(), 0, math.random(50, 100) / 100})
end
attackone = function()
attack = true
for i = 0, 1, 0.1 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0) * angles(math.rad(0), math.rad(0), math.rad(-80)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(0), math.rad(0), math.rad(80)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(0), math.rad(-50), math.rad(90)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, 0) * angles(math.rad(0), math.rad(0), math.rad(-80)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(-50), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
FakeHandleWeld.C0 = clerp(FakeHandleWeld.C0, cf(0, 0, 0) * angles(math.rad(190), math.rad(0), math.rad(-100)), 0.2)
end
local con = Hitbox.Touched:connect(function(hit)
Damagefunc(Hitbox, hit, 10, 15, math.random(1, 5), "Normal", RootPart, 0.2, "rbxassetid://199149221", 0.8)
end
)
CreateSound("http://www.roblox.com/asset/?id=234365549", Torso, 1, 1)
for i = 0, 1, 0.1 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0) * angles(math.rad(0), math.rad(0), math.rad(100)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(0), math.rad(0), math.rad(-100)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(0), math.rad(30), math.rad(90)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, 0) * angles(math.rad(0), math.rad(30), math.rad(-80)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(-50), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
FakeHandleWeld.C0 = clerp(FakeHandleWeld.C0, cf(0, 0, 0) * angles(math.rad(190), math.rad(0), math.rad(-150)), 0.2)
end
con:disconnect()
attack = false
end
Deathwish = function()
attack = true
CreateSound("http://www.roblox.com/asset/?id=231917970", RootPart, 1, 1)
for i = 0, 1, 0.05 do
swait()
WaveEffect(BrickColor.new("Black"), RootPart.CFrame * cf(0, -2.5, 0), 5, 2, 5, 1, 0.1, 1, 0.09)
BlockEffect(BrickColor.new("Black"), LeftArm.CFrame * cf(0, -1, 0), 5, 5, 5, 0.5, 0.5, 0.5, 0.08, 1)
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0) * angles(math.rad(0), math.rad(0), math.rad(-80)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(2 * math.cos(sine / 5)), math.rad(-4 * math.cos(sine / 25)), math.rad(80)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(10 * math.cos(sine / 25)), math.rad(0), math.rad(190)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, 0) * angles(math.rad(0), math.rad(0), math.rad(-90)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
FakeHandleWeld.C0 = clerp(FakeHandleWeld.C0, cf(0, 0, 0) * angles(math.rad(0), math.rad(60), math.rad(100)), 0.2)
end
MagniDamage(RootPart, 5599, 1099, 1599, 0, "DarkUp")
CreateSound("http://www.roblox.com/asset/?id=192410089", RootPart, 1, 1)
BlockEffect(BrickColor.new("Black"), LeftArm.CFrame * cf(0, -1, 0), 5, 5, 5, 5, 5, 5, 0.06, 1)
WaveEffect(BrickColor.new("Black"), RootPart.CFrame * cf(0, -2.5, 0), 5, 2, 5, 2, 0.1, 2, 0.07)
for i = 0, 1, 0.05 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0) * angles(math.rad(0), math.rad(0), math.rad(-80)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(2 * math.cos(sine / 5)), math.rad(-4 * math.cos(sine / 25)), math.rad(80)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(10 * math.cos(sine / 25)), math.rad(0), math.rad(190)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, 0) * angles(math.rad(0), math.rad(0), math.rad(-190)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
FakeHandleWeld.C0 = clerp(FakeHandleWeld.C0, cf(0, 0, 0) * angles(math.rad(0), math.rad(60), math.rad(100)), 0.2)
end
for i = 0, 1, 0.1 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0) * angles(math.rad(0), math.rad(0), math.rad(-110)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(2 * math.cos(sine / 5)), math.rad(-4 * math.cos(sine / 25)), math.rad(100)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(10 * math.cos(sine / 25)), math.rad(0), math.rad(190)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, 0) * angles(math.rad(0), math.rad(-80), math.rad(-90)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
FakeHandleWeld.C0 = clerp(FakeHandleWeld.C0, cf(0, 0, 0) * angles(math.rad(0), math.rad(60), math.rad(100)), 0.2)
end
MagniDamage(RootPart, 55, 5, 10, -70, "Knockdown")
CreateSound("http://www.roblox.com/asset/?id=192410089", RootPart, 1, 1.2)
SphereEffect(BrickColor.new("Black"), LeftArm.CFrame * cf(0, -1, 0), 5, 5, 5, 10, 10, 10, 0.06)
BlockEffect(BrickColor.new("Black"), LeftArm.CFrame * cf(0, -1, 0), 5, 5, 5, 5, 5, 5, 0.06, 1)
WaveEffect(BrickColor.new("Black"), RootPart.CFrame * cf(0, -2.5, 0), 5, 2, 5, 0.5, 1, 0.5, 0.07)
for i = 0, 1, 0.1 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0) * angles(math.rad(0), math.rad(0), math.rad(-50)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(2 * math.cos(sine / 5)), math.rad(-4 * math.cos(sine / 25)), math.rad(50)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(10 * math.cos(sine / 25)), math.rad(0), math.rad(190)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, 0) * angles(math.rad(0), math.rad(0), math.rad(-90)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
FakeHandleWeld.C0 = clerp(FakeHandleWeld.C0, cf(0, 0, 0) * angles(math.rad(0), math.rad(60), math.rad(100)), 0.2)
end
attack = false
end
ChaosDriver = function()
attack = true
for i = 0, 1, 0.05 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0) * angles(math.rad(0), math.rad(0), math.rad(-80)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(0), math.rad(0), math.rad(80)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(0), math.rad(-50), math.rad(90)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, 0) * angles(math.rad(0), math.rad(0), math.rad(-80)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(-50), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
FakeHandleWeld.C0 = clerp(FakeHandleWeld.C0, cf(0, 0, 0) * angles(math.rad(190), math.rad(0), math.rad(-100)), 0.2)
end
CreateSound("http://www.roblox.com/asset/?id=234365549", Torso, 1, 1)
coroutine.resume(coroutine.create(function()
for i = 1, 5 do
swait()
local ef = CreatePart(workspace, "Marble", 0, 1, BrickColor.new("Black"), "Effect", vt())
ef.Anchored = true
ef.CFrame = RootPart.CFrame * cf(0, 0, -10 * i)
MagniDamage(ef, 17, 10, 15, 1, "DarkUp")
game:GetService("Debris"):AddItem(ef, 0.5)
CreateSound("http://www.roblox.com/asset/?id=231917784", ef, 1, 0.7)
DragonEffect(BrickColor.new("Black"), RootPart.CFrame * cf(0, 0, -10 * i) * angles(math.rad(math.random(50, 90)), 0, math.rad(math.random(50, 90))), 5, 170, 5, 0, -10, 0, 0.07)
DragonEffect(BrickColor.new("Magenta"), RootPart.CFrame * cf(0, 0, -10 * i) * angles(math.rad(math.random(50, 90)), 0, math.rad(math.random(50, 90))), 5, 150, 5, 0, -10, 0, 0.07)
SpecialEffect(BrickColor.new("Really black"), Torso.CFrame, 5, 5, 5, 3, 3, 3, 0.08)
SpecialEffect(BrickColor.new("Magenta"), Torso.CFrame, 2, 2, 2, 3, 3, 3, 0.07)
SpecialEffect(BrickColor.new("Really black"), Hitbox.CFrame, 5, 5, 5, 3, 3, 3, 0.08)
SpecialEffect(BrickColor.new("Magenta"), Hitbox.CFrame, 2, 2, 2, 3, 3, 3, 0.07)
end
end
))
for i = 0, 1, 0.1 do
swait()
BlockEffect(BrickColor.new("Really black"), Hitbox.CFrame, 5, 5, 5, 3, 3, 3, 0.08, 1)
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0) * angles(math.rad(0), math.rad(0), math.rad(100)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(0), math.rad(0), math.rad(-100)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(0), math.rad(30), math.rad(90)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, 0) * angles(math.rad(0), math.rad(30), math.rad(-80)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(-50), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
FakeHandleWeld.C0 = clerp(FakeHandleWeld.C0, cf(0, 0, 0) * angles(math.rad(190), math.rad(0), math.rad(-150)), 0.2)
end
attack = false
end
attacktwo = function()
attack = true
soundn = true
for i = 0, 1, 0.1 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0) * angles(math.rad(-20), math.rad(0), math.rad(-80)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(20), math.rad(0), math.rad(80)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(0), math.rad(-50), math.rad(180)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, 0) * angles(math.rad(0), math.rad(0), math.rad(-30)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1.2, 0) * RHCF * angles(math.rad(-10), math.rad(-50), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
FakeHandleWeld.C0 = clerp(FakeHandleWeld.C0, cf(0, 0, 0) * angles(math.rad(200), math.rad(-100), math.rad(0)), 0.2)
end
local con = Hitbox.Touched:connect(function(hit)
Damagefunc(Hitbox, hit, 10, 15, math.random(1, 5), "Normal", RootPart, 0.2, "rbxassetid://199149221", 0.8)
end
)
CreateSound("http://www.roblox.com/asset/?id=234365573", Torso, 1, 1)
coroutine.resume(coroutine.create(function()
while soundn do
wait(0.3)
CreateSound("http://www.roblox.com/asset/?id=234365573", Torso, 1, 1)
end
end
))
for i = 0, 1, 0.1 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0) * angles(math.rad(0), math.rad(0), math.rad(0 + 360 * i)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(0), math.rad(0), math.rad(-100)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(0), math.rad(30), math.rad(90)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, 0) * angles(math.rad(0), math.rad(50), math.rad(-30)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(-50), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
FakeHandleWeld.C0 = clerp(FakeHandleWeld.C0, cf(0, 0, 0) * angles(math.rad(190), math.rad(0), math.rad(-100)), 0.2)
end
con:disconnect()
soundn = false
attack = false
end
local soundn = false
attackthree = function()
attack = true
soundn = true
for i = 0, 1, 0.1 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0) * angles(math.rad(-20), math.rad(0), math.rad(-80)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(20), math.rad(0), math.rad(80)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(0), math.rad(-50), math.rad(180)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, 0) * angles(math.rad(0), math.rad(0), math.rad(-30)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1.2, 0) * RHCF * angles(math.rad(-10), math.rad(-50), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
FakeHandleWeld.C0 = clerp(FakeHandleWeld.C0, cf(0, 0, 0) * angles(math.rad(200), math.rad(-100), math.rad(0)), 0.2)
end
local con = Hitbox.Touched:connect(function(hit)
Damagefunc(Hitbox, hit, 10, 15, math.random(1, 5), "Normal", RootPart, 0.2, "rbxassetid://199149221", 0.8)
end
)
CreateSound("http://www.roblox.com/asset/?id=234365573", Torso, 1, 1)
coroutine.resume(coroutine.create(function()
while soundn do
wait(0.3)
CreateSound("http://www.roblox.com/asset/?id=234365573", Torso, 1, 1)
end
end
))
for i = 0, 1, 0.1 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0) * angles(math.rad(0), math.rad(0), math.rad(0 + 360 * i)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(0), math.rad(0), math.rad(-100)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(0), math.rad(30), math.rad(90)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, 0) * angles(math.rad(0), math.rad(50), math.rad(-30)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(-50), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
FakeHandleWeld.C0 = clerp(FakeHandleWeld.C0, cf(0, 0, 0) * angles(math.rad(190), math.rad(0), math.rad(-100)), 0.2)
end
con:disconnect()
soundn = false
attack = false
end
ThanatosDriver = function()
attack = true
for i = 0, 1, 0.1 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0) * angles(math.rad(-20), math.rad(0), math.rad(-80)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(20), math.rad(0), math.rad(80)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(0), math.rad(-90), math.rad(180)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, 0) * angles(math.rad(0), math.rad(-90), math.rad(-100)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1.2, 0) * RHCF * angles(math.rad(-10), math.rad(-50), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
FakeHandleWeld.C0 = clerp(FakeHandleWeld.C0, cf(0, 0, 0) * angles(math.rad(200), math.rad(-100), math.rad(0)), 0.2)
end
local con = Hitbox.Touched:connect(function(hit)
Damagefunc(Hitbox, hit, 30, 30, 50, "Knockdown", RootPart, 0.2, "rbxassetid://199149221", 0.8)
end
)
CreateSound("http://www.roblox.com/asset/?id=231917871", Torso, 1, 0.7)
for i = 0, 1, 0.1 do
swait()
BlockEffect(BrickColor.new("Really black"), Hitbox.CFrame, 5, 5, 5, 3, 3, 3, 0.08, 1)
BlockEffect(BrickColor.new("Magenta"), Hitbox.CFrame, 3, 3, 3, 3, 3, 3, 0.08, 2)
DragonEffect(BrickColor.new("Black"), Hitbox.CFrame * cf(0, 0, -2) * angles(math.rad(90), math.rad(-90), math.rad(90)), 1, 1, 1, 0.2, 0.5, 0.2, 0.08)
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0) * angles(math.rad(20), math.rad(0), math.rad(100)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(20), math.rad(0), math.rad(-80)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(0), math.rad(-20), math.rad(30)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, 0) * angles(math.rad(0), math.rad(90), math.rad(0)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1.2, 0) * RHCF * angles(math.rad(-10), math.rad(-50), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
FakeHandleWeld.C0 = clerp(FakeHandleWeld.C0, cf(0, 0, 0) * angles(math.rad(200), math.rad(-100), math.rad(170)), 0.2)
end
con:disconnect()
attack = false
end
LastResort = function()
attack = true
soundn = true
CreateSound("http://www.roblox.com/asset/?id=233096557", Torso, 1, 1)
MagniDamage(RootPart, 10, 5, 10, 0, "Knockdown")
SpecialEffect(BrickColor.new("Really black"), Torso.CFrame, 5, 5, 5, 3, 3, 3, 0.08)
SpecialEffect(BrickColor.new("Magenta"), Torso.CFrame, 2, 2, 2, 3, 3, 3, 0.07)
SpecialEffect(BrickColor.new("Really black"), Hitbox.CFrame, 5, 5, 5, 3, 3, 3, 0.08)
SpecialEffect(BrickColor.new("Magenta"), Hitbox.CFrame, 2, 2, 2, 3, 3, 3, 0.07)
RootPart.CFrame = RootPart.CFrame * cf(0, 0, 20)
for i = 0, 1, 0.1 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0) * angles(math.rad(-20), math.rad(0), math.rad(-80)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(20), math.rad(0), math.rad(80)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(0), math.rad(-90), math.rad(180)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, 0) * angles(math.rad(0), math.rad(-90), math.rad(-100)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1.2, 0) * RHCF * angles(math.rad(-10), math.rad(-50), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
FakeHandleWeld.C0 = clerp(FakeHandleWeld.C0, cf(0, 0, 0) * angles(math.rad(200), math.rad(-100), math.rad(0)), 0.2)
end
CreateSound("http://www.roblox.com/asset/?id=231917871", Torso, 1, 1)
coroutine.resume(coroutine.create(function()
while soundn do
wait(0.5)
CreateSound("http://www.roblox.com/asset/?id=231917871", Torso, 1, 1)
end
end
))
for i = 0, 1, 0.1 do
swait()
MagniDamage(RootPart, 10, 5, 10, 0, "Normal")
Torso.Velocity = RootPart.CFrame.lookVector * 100
BlockEffect(BrickColor.new("Really black"), Hitbox.CFrame, 5, 5, 5, 3, 3, 3, 0.08, 1)
BlockEffect(BrickColor.new("Magenta"), Hitbox.CFrame, 3, 3, 3, 3, 3, 3, 0.08, 2)
DragonEffect(BrickColor.new("Black"), Hitbox.CFrame * cf(0, 0, -2) * angles(math.rad(90), math.rad(90), math.rad(90)), 1, 1, 1, 0.2, 0.5, 0.2, 0.08)
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0) * angles(math.rad(0), math.rad(0), math.rad(0 + 360 * i)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(0), math.rad(0), math.rad(-100)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(0), math.rad(30), math.rad(90)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, 0) * angles(math.rad(0), math.rad(50), math.rad(-30)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(-50), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
FakeHandleWeld.C0 = clerp(FakeHandleWeld.C0, cf(0, 0, 0) * angles(math.rad(190), math.rad(0), math.rad(-100)), 0.2)
end
for i = 0, 1, 0.1 do
swait()
MagniDamage(RootPart, 10, 3, 3, 0, "Normal")
Torso.Velocity = RootPart.CFrame.lookVector * 100
BlockEffect(BrickColor.new("Really black"), Hitbox.CFrame, 5, 5, 5, 3, 3, 3, 0.08, 1)
BlockEffect(BrickColor.new("Magenta"), Hitbox.CFrame, 3, 3, 3, 3, 3, 3, 0.08, 2)
DragonEffect(BrickColor.new("Black"), Hitbox.CFrame * cf(0, 0, -2) * angles(math.rad(90), math.rad(90), math.rad(90)), 1, 1, 1, 0.2, 0.5, 0.2, 0.08)
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0) * angles(math.rad(0), math.rad(0), math.rad(0 + 360 * i)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(0), math.rad(0), math.rad(-100)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(0), math.rad(30), math.rad(90)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, 0) * angles(math.rad(0), math.rad(50), math.rad(-30)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(-50), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
FakeHandleWeld.C0 = clerp(FakeHandleWeld.C0, cf(0, 0, 0) * angles(math.rad(190), math.rad(0), math.rad(-100)), 0.2)
end
soundn = false
attack = false
end
ob1u = function()
end
ob1d = function()
if attack == false and attacktype == 1 then
attacktype = 2
attackone()
else
if attack == false and attacktype == 2 then
attacktype = 3
attacktwo()
else
if attack == false and attacktype == 3 then
attacktype = 1
attackthree()
end
end
end
end
key = function(k)
k = k:lower()
if attack == false and k == "z" and zenabled == true then
zenabled = false
coroutine.resume(coroutine.create(function()
for i = 1, 0, -0.02 do
swait()
fenframe1a.Size = UDim2.new(0.05 * i, 0, 0.1, 0)
end
zenabled = true
fenframe1a.Size = UDim2.new(0, 0, 0.1, 0)
end
))
ThanatosDriver()
else
if attack == false and k == "x" and xenabled == true then
xenabled = false
coroutine.resume(coroutine.create(function()
for i = 1, 0, -0.005 do
swait()
fenframe2a.Size = UDim2.new(0.05 * i, 0, 0.1, 0)
end
xenabled = true
fenframe2a.Size = UDim2.new(0, 0, 0.1, 0)
end
))
LastResort()
else
if attack == false and k == "c" and cenabled == true then
cenabled = false
coroutine.resume(coroutine.create(function()
for i = 1, 0, -0.0025 do
swait()
fenframe3a.Size = UDim2.new(0.05 * i, 0, 0.1, 0)
end
cenabled = true
fenframe3a.Size = UDim2.new(0, 0, 0.1, 0)
end
))
ChaosDriver()
else
if attack == false and k == "v" and venabled == true then
venabled = false
coroutine.resume(coroutine.create(function()
for i = 1, 0, -0.0005 do
swait()
fenframe4a.Size = UDim2.new(0.05 * i, 0, 0.1, 0)
end
venabled = true
fenframe4a.Size = UDim2.new(0, 0, 0.1, 0)
end
))
Deathwish()
end
end
end
end
end
s = function(mouse)
mouse.Button1Down:connect(function()
ob1d(mouse)
end
)
mouse.Button1Up:connect(function()
ob1u(mouse)
end
)
mouse.KeyDown:connect(key)
end
s(mouse)
rs = game:GetService'RunService'
plrs = game:GetService'Players'
lp = plrs.LocalPlayer
c = lp.Character
root = lp.Character.HumanoidRootPart
human = c.Humanoid
FPS = 0
inf = 0
opos1 = Vector3.new()
opos2 = Vector3.new()
opos3 = Vector3.new()
waves = Instance.new("Model", c)
res = Instance.new("Model", c)
local function b()
local t=tick();
local l=t%1*3;
local t=.5*math.pi*(l%1);
if l<1 then
return Color3.new(47,0,32);
elseif l<2 then
return Color3.new(47,0,35);
else
return Color3.new(0,0,0);
end;
end;
speedParts = function()
for i = 1, 4 do
local pos = Vector3.new(math.sin(math.rad(inf + 360 * i)) * 2, math.sin(math.rad(inf + 260 * i) + math.pi / 2) * 2, -Hitbox.Velocity / 5) * (math.sin(tick()) + 2)
local CFramepos = Hitbox.CFrame:toWorldSpace(CFrame.new(pos)).p
local opos
if i == 1 then
opos = opos1
elseif i == 2 then
opos = opos2
else
opos = opos3
end
local e
if #res:children() <= 3 then
e = Instance.new("Part")
else
e = res:FindFirstChild("Trail")
end
e.Parent = waves
e.Anchored = false
e.CanCollide = false
e.Transparency = 0
e.Material = "Neon"
e.Name = "Trail"
e.Color = b(); --Color = a();
e.Size = Vector3.new(.01, (CFramepos - opos).magnitude, .01)
e.CFrame = CFrame.new((CFramepos + opos) / 2, opos) * CFrame.Angles(math.pi / 2, 0, 0)
if i == 1 then
opos1 = CFramepos
elseif i == 2 then
opos2 = CFramepos
else
opos3 = CFramepos
end
end
end
rs.RenderStepped:connect(function()
FPS = 1 / rs.RenderStepped:wait()
for i, v in pairs (waves:children()) do
v.Transparency = v.Transparency + .05 / (FPS / 400)
if v.Transparency >= .98 then
v.Transparency = 1
v.Parent = res
end
end
inf = inf + (30 + root.Velocity.magnitude / 15) / (FPS / 400)
speedParts()
end)
while 1 do
swait()
Torsovelocity = RootPart.Velocity * Vector3.new(1, 0, 1).magnitude
velocity = RootPart.Velocity.y
sine = sine + change
local hit, pos = rayCast(RootPart.Position, CFrame.new(RootPart.Position, RootPart.Position - Vector3.new(0, 1, 0)).lookVector, 4, Character)
if equipped == true or equipped == false then
if 1 < RootPart.Velocity.y and hit == nil then
Anim = "Jump"
if attack == false then
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0) * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(0), math.rad(-4 * math.cos((sine) / 25)), math.rad(-30)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(10 * math.cos((sine) / 25)), math.rad(0), math.rad(190)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, 0) * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
end
else
if RootPart.Velocity.y < -1 and hit == nil then
Anim = "Fall"
if attack == false then
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0) * angles(math.rad(0), math.rad(0), math.rad(30)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(30), math.rad(-4 * math.cos((sine) / 25)), math.rad(-30)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(10 * math.cos((sine) / 25)), math.rad(0), math.rad(190)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, 0) * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
FakeHandleWeld.C0 = clerp(FakeHandleWeld.C0, cf(0, 0, 0) * angles(math.rad(0), math.rad(60), math.rad(100)), 0.2)
end
else
if Torsovelocity.x < 1 and Torsovelocity.z < 1 and hit ~= nil then
Anim = "Idle"
if attack == false then
change = 1
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, -0.2 - 0.1 * math.cos((sine) / 9)) * angles(math.rad(20), math.rad(-20), math.rad(-80)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(-10 + 1 * math.cos((sine) / 9)), math.rad(-10 + 1 * math.cos((sine) / 9)), math.rad(80)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.3, 0.2, -0.5) * angles(math.rad(50), math.rad(0), math.rad(-30)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1, 0.5, -1) * angles(math.rad(0), math.rad(0), math.rad(50)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1.2 + 0.1 * math.cos((sine) / 9), 0) * RHCF * angles(math.rad(0), math.rad(-30), math.rad(20)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1.3, -1 + 0.1 * math.cos((sine) / 9), 0) * LHCF * angles(math.rad(0), math.rad(30), math.rad(-20)), 0.3)
FakeHandleWeld.C0 = clerp(FakeHandleWeld.C0, cf(0, 0, 0) * angles(math.rad(60), math.rad(70 - 1 * math.cos((sine) / 9)), math.rad(70)), 0.3)
end
else
if Torsovelocity.x > 2 and Torsovelocity.z > 2 and hit ~= nil then
Anim = "Walk"
if attack == false then
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, -0.2 - 0.1 * math.cos((sine) / 9)) * angles(math.rad(10), math.rad(-5), math.rad(-30)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(-5 + 1 * math.cos((sine) / 9)), math.rad(-10 + 1 * math.cos((sine) / 9)), math.rad(30)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.3, 0.2, 0) * angles(math.rad(50), math.rad(0), math.rad(-10)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-0.5, 0.5, -1) * angles(math.rad(0), math.rad(0), math.rad(50)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0 + 0.5 * math.cos((sine) / 5)) * RHCF * angles(math.rad(0), math.rad(0), math.rad(10 - 50 * math.cos((sine) / 5))), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, -0.5 - 0.5 * math.cos((sine) / 5)) * LHCF * angles(math.rad(0), math.rad(0), math.rad(-10 - 50 * math.cos((sine) / 5))), 0.3)
FakeHandleWeld.C0 = clerp(FakeHandleWeld.C0, cf(0, 0, 0) * angles(math.rad(60), math.rad(50 - 1 * math.cos((sine) / 9)), math.rad(120)), 0.3)
end
end
end
end
end
end
if 0 < #Effects then
for e = 1, #Effects do
if Effects[e] ~= nil then
local Thing = Effects[e]
if Thing ~= nil then
local Part = Thing[1]
local Mode = Thing[2]
local Delay = Thing[3]
local IncX = Thing[4]
local IncY = Thing[5]
local IncZ = Thing[6]
if Thing[1].Transparency <= 1 then
if Thing[2] == "Block1" then
Thing[1].CFrame = Thing[1].CFrame * CFrame.fromEulerAnglesXYZ(math.random(-50, 50), math.random(-50, 50), math.random(-50, 50))
Mesh = Thing[1].Mesh
Mesh.Scale = Mesh.Scale + Vector3.new(Thing[4], Thing[5], Thing[6])
Thing[1].Transparency = Thing[1].Transparency + Thing[3]
else
if Thing[2] == "Block2" then
Thing[1].CFrame = Thing[1].CFrame
Mesh = Thing[7]
Mesh.Scale = Mesh.Scale + Vector3.new(Thing[4], Thing[5], Thing[6])
Thing[1].Transparency = Thing[1].Transparency + Thing[3]
else
if Thing[2] == "Cylinder" then
Mesh = Thing[1].Mesh
Mesh.Scale = Mesh.Scale + Vector3.new(Thing[4], Thing[5], Thing[6])
Thing[1].Transparency = Thing[1].Transparency + Thing[3]
else
if Thing[2] == "Blood" then
Mesh = Thing[7]
Thing[1].CFrame = Thing[1].CFrame * Vector3.new(0, 0.5, 0)
Mesh.Scale = Mesh.Scale + Vector3.new(Thing[4], Thing[5], Thing[6])
Thing[1].Transparency = Thing[1].Transparency + Thing[3]
else
if Thing[2] == "Elec" then
Mesh = Thing[1].Mesh
Mesh.Scale = Mesh.Scale + Vector3.new(Thing[7], Thing[8], Thing[9])
Thing[1].Transparency = Thing[1].Transparency + Thing[3]
else
if Thing[2] == "Disappear" then
Thing[1].Transparency = Thing[1].Transparency + Thing[3]
else
if Thing[2] == "Shatter" then
Thing[1].Transparency = Thing[1].Transparency + Thing[3]
Thing[4] = Thing[4] * CFrame.new(0, Thing[7], 0)
Thing[1].CFrame = Thing[4] * CFrame.fromEulerAnglesXYZ(Thing[6], 0, 0)
Thing[6] = Thing[6] + Thing[5]
end
end
end
end
end
end
end
else
Part.Parent = nil
table.remove(Effects, e)
end
end
end
end
end
end |
local stabilize = require "stabilize"
stabilize.setup {
force = true, -- stabilize window even when current cursor position will be hidden behind new window
forcemark = nil, -- set context mark to register on force event which can be jumped to with '<forcemark>
ignore = { -- do not manage windows matching these file/buftypes
filetype = { "help", "list", "Trouble" },
buftype = { "terminal", "quickfix", "loclist" },
},
nested = nil, -- comma-separated list of autocmds that will trigger the plugins window restore function
}
|
-- Helper module for testing intel_mp driver receive
module(..., package.seeall)
local intel = require("apps.intel_mp.intel_mp")
local basic = require("apps.basic.basic_apps")
local ffi = require("ffi")
local C = ffi.C
function test(pciaddr, qno, vmdq, poolno, macaddr, vlan)
local c = config.new()
if vmdq then
config.app(c, "nic", intel.Intel,
{ pciaddr=pciaddr,
macaddr=macaddr,
vlan=vlan,
vmdq=true,
poolnum=poolno,
rxq = qno,
rxcounter = qno+1,
wait_for_link=true })
else
config.app(c, "nic", intel.Intel,
{ pciaddr=pciaddr,
rxq = qno,
rxcounter = qno+1,
wait_for_link=true })
end
config.app(c, "sink", basic.Sink)
if os.getenv("SNABB_RECV_EXPENSIVE") then
local filter = require("apps.packet_filter.pcap_filter")
local count = 10
config.link(c, "nic.output -> filter0.input")
for i=0,count do
local n = tostring(i)
local s = "filter"..n
config.app(c, s, filter.PcapFilter, { filter = [[ not dst host 10.2.29.1 and not dst host 10.2.50.1 ]]})
end
for i=1,count do
local m = tostring(i-1)
local n = tostring(i)
local s = "filter"..m..".output -> filter"..n..".input"
config.link(c, s)
end
config.app(c, "sane", filter.PcapFilter, { filter = [[ src host 172.16.172.3 and dst net 1.2.0.0/16 and ip proto 0 ]] })
config.link(c, "filter"..tostring(count)..".output -> sane.input")
config.link(c, "sane.output -> sink.input")
else
config.link(c, "nic.output -> sink.input")
end
engine.configure(c)
local spinup = os.getenv("SNABB_RECV_SPINUP")
if spinup then
engine.main({duration = spinup})
end
local counters = {
Intel82599 = { "GPRC", "RXDGPC" },
Intel1g = { "GPRC", "RPTHC" }
}
local duration = os.getenv("SNABB_RECV_DURATION") or 2
local before = {}
local nic = engine.app_table.nic
local master = nic.master
if master then
for _,v in pairs(counters[nic.driver]) do
before[v] = nic.r[v]()
end
end
if os.getenv("SNABB_RECV_DEBUG") then
for _=1,duration do
engine.main({duration = 1})
nic:debug()
end
else
engine.main({duration = duration})
end
if master then
for _,v in pairs(counters[nic.driver]) do
print(string.format("%s %d", v, tonumber(nic.r[v]() - before[v])/duration))
end
end
main.exit(0)
end
|
local config = require('__shared/config')
require('parachute-events')
local isChecking = false
local sinceLastCheck = 0
function startChecking()
isChecking = true
end
function stopChecking()
isChecking = false
end
Events:Subscribe('LocalPlayer:FreefallBegin', startChecking)
Events:Subscribe('LocalPlayer:ParachuteBegin', stopChecking)
Events:Subscribe('LocalPlayer:ParachuteEnd', stopChecking)
Events:Subscribe('UpdateManager:Update', function(deltaTime, updatePass)
if updatePass ~= UpdatePass.UpdatePass_PreSim then
return
end
sinceLastCheck = sinceLastCheck + deltaTime
-- skip if not enough time has passed
if not isChecking or sinceLastCheck < config.raycastEverySec then
return
end
local player = PlayerManager:GetLocalPlayer()
-- stop checking if player disappeared
if player == nil or player.soldier == nil then
stopChecking()
return
end
-- reset timer
sinceLastCheck = 0
-- raycast to check if soldier is at <= min height from the ground
local from = player.soldier.transform.trans
local to = from - Vec3(0, config.parachuteOpenDistance, 0)
local hit = RaycastManager:Raycast(from, to, RayCastFlags.CheckDetailMesh | RayCastFlags.DontCheckWater | RayCastFlags.DontCheckCharacter | RayCastFlags.DontCheckRagdoll)
-- if there's a hit then open the parachute
if hit ~= nil then
NetEvents:SendLocal('OpenParachute')
end
end)
|
local mod = get_mod("rwaon_talents")
------------------------------------------------------------------------------
--[[mod:add_talent("dr_ironbreaker", 2, 3, "rwaon_bardin_ironbreaker_movespeed_on_charged_attacks", {
num_ranks = 1,
description_values = {
{
value_type = "percent",
value = 0.10,
},
{
value = 5,
},
{
value = 15,
}
},
requirements = {},
buffs = {
"rwaon_bardin_ironbreaker_movespeed_on_charged_attacks_cooldown",
"rwaon_sienna_scholar_embodiment_of_aqshy_overcharge",
},
})
mod:add_talent_buff("dwarf_ranger", "rwaon_bardin_ironbreaker_movespeed_on_charged_attacks_cooldown", {
duration = 15,
buff_after_delay = true,
max_stacks = 1,
refresh_durations = true,
is_cooldown = true,
icon = "victor_zealot_passive_invulnerability",
delayed_buff_name = "rwaon_bardin_ironbreaker_gain_movespeed_on_charged_attacks"
})
mod:add_talent_buff("dwarf_ranger", "rwaon_bardin_ironbreaker_gain_movespeed_on_charged_attacks", {
max_stacks = 1,
event_buff = true,
event = "on_hit",
icon = "victor_zealot_passive_invulnerability",
buff_func = function (player, buff, params)
local player_unit = player.player_unit
local hit_unit = params[1]
local attack_type = params[2]
local buff_extension = ScriptUnit.extension(player_unit, "buff_system")
if attack_type ~= "heavy_attack" then
return
end
if Unit.alive(player_unit) then
buff_extension:add_buff("rwaon_bardin_ironbreaker_movespeed_on_charged_attacks", buff_params)
end
if Unit.alive(player_unit) then
local buff_1 = buff_extension:add_buff("rwaon_bardin_ironbreaker_gain_movespeed_on_charged_attacks", {attacker_unit = player_unit})
if buff_extension:has_buff_type("rwaon_bardin_ironbreaker_gain_movespeed_on_charged_attacks") then
buff_extension:remove_buff(buff_1)
end
end
end,
})
mod:add_talent_buff("dwarf_ranger", "rwaon_bardin_ironbreaker_movespeed_on_charged_attacks", {
max_stacks = 1,
icon = "victor_zealot_passive_invulnerability",
apply_buff_func = "apply_movement_buff",
multiplier = 1.25, -- 1.5
refresh_durations = false,
remove_buff_func = "remove_movement_buff",
duration = 5,
path_to_movement_setting_to_modify = {
"move_speed"
},
buff_after_delay = true,
delayed_buff_name = "rwaon_bardin_ironbreaker_movespeed_on_charged_attacks_cooldown",
})]]
------------------------------------------------------------------------------
--[[mod:add_talent("dr_ironbreaker", 3, 1, "melee_weapon_heal_proc_light", {
description_values = {
{
value_type = "percent",
value = 0.1
}
},
buffs = {
"melee_weapon_heal_proc_light"
},
})
mod:add_talent_buff("dwarf_ranger", "melee_weapon_heal_proc_light", {
name = "regrowth",
event_buff = true,
event = "on_hit",
perk = "ninja_healing",
bonus = 5,
stat_buff = ProcFunctions.heal_permanent_proc,
attack_wanted = "charged",
proc_chance = 0.1,
})
mod:add_talent("dr_ironbreaker", 4, 1, "ranged_weapon_heal_proc", {
description_values = {
{
value_type = "percent",
value = 0.12
}
},
buffs = {
"ranged_weapon_heal_proc"
},
})
mod:add_talent_buff("dwarf_ranger", "ranged_weapon_heal_proc", {
name = "regrowth",
event_buff = true,
event = "on_hit",
perk = "ninja_healing",
bonus = 5,
stat_buff = ProcFunctions.heal_permanent_proc,
attack_wanted = "RANGED",
proc_chance = 0.12,
})]]
------------------------------------------------------------------------------
mod:add_talent("dr_ironbreaker", 5, 3, "rwaon_bardin_ironbreaker_uninterruptible_attacks", {
num_ranks = 1,
})
mod:add_talent_buff("dwarf_ranger", "rwaon_bardin_ironbreaker_uninterruptible_attacks", {
max_stacks = 1,
perk = "uninterruptible",
refresh_durations = true,
duration = 10,
icon = "icons_placeholder",
}) |
AddCSLuaFile()
SWEP.Base = "weapon_prop_powerup_base"
SWEP.Name = "Stack"
SWEP.PrintName = "Stack"
SWEP.AbilityUsableBeforeHuntersReleaed = true
SWEP.AbilityDescription = "Stack the Prop you're hold on top of you for better hiding."
function SWEP:Ability()
if CLIENT then return end
local ply = self:GetOwner()
local prop = GetViewEntSv(ply)
if !IsValid(prop) then
return "Not looking at anything"
end
local _, playerPropHBMax = PropHitbox(ply)
local propHBMin, _ = GetHitBoxInModelCoordinates(prop)
prop:SetAngles(Angle(0, math.random(-180, 180), 0))
prop:SetPos(Vector(
ply:GetPos().x,
ply:GetPos().y,
ply:GetPos().z + playerPropHBMax.z - propHBMin.z + 1
))
end |
local SP_URL = 'https://localhost'
return {
key_attribute_name = "EmailAddress",
redirect = {
url_after_login = "/",
url_after_logout = "/"
},
request = {
idp_dest_url = "https://idp.ssocircle.com:443/sso/SSORedirect/metaAlias/publicidp",
sp_entity_id = SP_URL .. '/sso',
sp_saml_finish_url = SP_URL .. "/sso/finish-login",
urls_before_login = {
dict_name = "sso_redirect_urls",
expire_seconds = 180
}
},
response = {
xmlsec_command = "/usr/local/bin/xmlsec1",
idp_cert_filename = ngx.config.prefix() .. "/idp.crt"
},
session = {
cookie = {
name = "sso_session_id",
path = "/",
secure = true
},
store = {
dict_name = "sso_sessions",
expire_seconds = 600
}
}
}
|
-- Lua调用C++
local mod = require('mylua')
print(mod.add(1, 2))
local obj = mod.Object()
obj:setName('paoqi')
obj:setSum(648)
content = string.format('Name: %s, Sum: %d', obj:getName(), obj:getSum())
print(content)
|
death_watch_bloodguard = Creature:new {
objectName = "@mob/creature_names:mand_bunker_dthwatch_red",
randomNameType = NAME_GENERIC,
randomNameTag = true,
socialGroup = "death_watch",
faction = "",
level = 121,
chanceHit = 4,
damageMin = 745,
damageMax = 1200,
baseXp = 11390,
baseHAM = 50000,
baseHAMmax = 50000,
armor = 2,
resists = {55,55,70,60,30,30,100,40,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY,
creatureBitmask = KILLER,
optionsBitmask = AIENABLED,
diet = HERBIVORE,
scale = 1.15,
templates = {"object/mobile/dressed_death_watch_red.iff"},
lootGroups = {
{
groups = {
{group = "wearables_uncommon", chance = 10000000}
},
lootChance = 5000000
},
{
groups = {
{group = "death_watch_bunker_commoners", chance = 6000000},
{group = "death_watch_bunker_lieutenants", chance = 4000000}
},
lootChance = 5000000
},
{
groups = {
{group = "death_watch_bunker_commoners", chance = 10000000}
},
lootChance = 5000000
},
{
groups = {
{group = "death_watch_bunker_lieutenants", chance = 10000000}
},
lootChance = 5000000
},
{
groups = {
{group = "wearables_common", chance = 10000000}
},
lootChance = 5000000
},
{
groups = {
{group = "jetpack_base", chance = 10000000}
},
lootChance = 5000000
},
{
groups = {
{group = "death_watch_bunker_commoners", chance = 10000000}
},
lootChance = 5000000
},
{
groups = {
{group = "junk", chance = 10000000}
},
lootChance = 5000000
},
{
groups = {
{group = "black_suns", chance = 10000000}
},
lootChance = 100000
},
},
weapons = {"pirate_weapons_heavy"},
conversationTemplate = "",
attacks = merge(bountyhuntermaster,marksmanmaster,brawlermaster,tkamaster)
}
CreatureTemplates:addCreatureTemplate(death_watch_bloodguard, "death_watch_bloodguard")
|
-- mod-version:2 -- lite-xl 2.0
local core = require "core"
local config = require "core.config"
local command = require "core.command"
local common = require "core.common"
local console = require "plugins.console"
local keymap = require "core.keymap"
-- This plugin requires the console plugin to work. It can be found at:
--
-- https://github.com/lite-xl/console
--
-- Before using this plugin add in your user's config file something like:
--
-- config.texcompile = {
-- latex_command = "pdflatex",
-- view_command = "evince",
-- }
--
-- as long as the commands are in your PATH.
--
-- Options can be passed as part of the command for example like in:
--
-- latex_command = "latex -pdf -pdflatex -c".
--
-- On Windows, if the commands are not in your PATH, you may use the full path
-- of the executable like, for example:
--
-- config.texcompile = {
-- latex_command = [[C:\miktex\miktex\bin\x64\pdflatex.exe]],
-- view_command = [[C:\Program^ Files\SumatraPDF\SumatraPDF.exe]],
-- }
--
-- Note that in the example we have used "^ " for spaces that appear in the path.
-- It is required on Windows for path or file names that contains space characters.
command.add("core.docview", {
["texcompile:tex-compile"] = function()
-- The current (La)TeX file and path
local texname = core.active_view:get_name()
local texpath = common.dirname(core.active_view:get_filename())
local pdfname = texname:gsub("%.tex$", ".pdf")
-- LaTeX compiler as configured in config.texcompile
local texcmd = config.texcompile and config.texcompile.latex_command
local viewcmd = config.texcompile and config.texcompile.view_command
if not texcmd then
core.log("No LaTeX compiler provided in config.")
else
core.log("LaTeX compiler is %s, compiling %s", texcmd, texname)
console.run {
command = string.format("%s %s && %s %s", texcmd, texname, viewcmd, pdfname),
cwd = texpath,
on_complete = function() core.log("Tex compiling command terminated.") end
}
end
end,
})
keymap.add { ["ctrl+shift+t"] = "texcompile:tex-compile" }
|
require "ffi".cdef [[
typedef uint16_t LuaGBAddress;
// graphics/palette
typedef uint8_t LuaGBPaletteColor[4];
typedef struct _LuaGBPalette {
LuaGBPaletteColor dmg_colors[4];
LuaGBPaletteColor bg[4], obj0[4], obj1[4];
LuaGBPaletteColor color_bg[8][4];
uint8_t color_bg_raw[64], color_obj_raw[64];
uint8_t color_bg_index, color_obj_index;
bool color_bg_auto_increment, color_obj_auto_increment;
LuaGBPaletteColor color_obj[8][4];
void (*set_dmg_colors)(LuaGBPaletteColor, LuaGBPaletteColor, LuaGBPaletteColor, LuaGBPaletteColor);
void (*reset)();
} LuaGBPalette;
// graphics/cache
typedef struct _LuaGBTileAttribute {
LuaGBPaletteColor *palette;
uint8_t bank;
bool horizontal_flip, vertical_flip, priority;
} LuaGBTileAttritbute,
*LuaGBTileAttritbutePtr,
(*LuaGBTileAttritbuteMapPtr)[32],
LuaGBTileAttributeMap[32][32];
typedef uint8_t LuaGBTile,
*LuaGBTileList,
(*LuaGBTileList2)[8],
(*LuaGBTileListMapPtr)[8][8],
LuaGBTileListMap[768][8][8],
(*LuaGBTileMapPtr)[32][8][8],
LuaGBTileMap[32][32][8][8];
typedef struct _LuaGBOAMEntry {
uint8_t x;
uint8_t y;
LuaGBTileList2 tile, upper_tile, lower_tile;
bool bg_priority, horizontal_flip, vertical_flip;
LuaGBPaletteColor palette[4];
} LuaGBOAMEntry, LuaGBOAM[40];
typedef struct _LuaGBTileCache {
LuaGBTileListMap tiles;
LuaGBTileListMap tiles_h_flipped;
LuaGBTileMap map_0;
LuaGBTileMap map_1;
LuaGBTileAttributeMap map_0_attr;
LuaGBTileAttributeMap map_1_attr;
LuaGBOAM oam;
void (*reset)();
void (*refreshOamEntry)(uint8_t);
void (*refreshAttributes)(LuaGBTileAttritbuteMapPtr, uint8_t, uint8_t, LuaGBAddress);
void (*refreshTile)(LuaGBAddress, uint8_t);
void (*refreshTiles)();
void (*refreshTileIndex)(uint8_t, uint8_t, LuaGBAddress, LuaGBTileMap, LuaGBTileAttributeMap);
void (*refreshTileMap)(LuaGBAddress, LuaGBTileMap, LuaGBTileAttributeMap);
void (*refreshTileMaps)();
void (*refreshTileAttributes)();
void (*refreshAll)();
void (*reset)();
} LuaGBTileCache;
// graphics/registers
typedef struct _LuaGBGraphicRegisterStatus {
uint8_t mode;
bool lyc_interrupt_enabled,
oam_interrupt_enabled,
vblank_interrupt_enabled,
hblank_interrupt_enabled;
void (*SetMode)(uint8_t);
} LuaGBGraphicRegisterStatus;
typedef struct _LuaGBGraphicRegisters {
LuaGBGraphicRegisterStatus status;
bool display_enabled;
LuaGBTileMapPtr window_tilemap,
background_tilemap;
LuaGBTileAttritbuteMapPtr window_attr,
background_attr;
bool window_enabled, background_enabled;
LuaGBAddress tile_select;
bool large_sprites,
sprites_enabled,
background_enabled,
oam_priority;
} LuaGBGraphicRegisters;
//graphics/init
typedef struct _LuaGBGraphicsScanlineData {
uint8_t x,
bg_tile_x,
bg_tile_y,
sub_x,
sub_y;
LuaGBTileMapPtr current_map;
LuaGBTileAttritbuteMapPtr current_map_attr;
bool window_active;
LuaGBTileList2 active_tile;
LuaGBTileAttritbutePtr active_attr;
uint8_t bg_index[160];
bool bg_priority[160];
} LuaGBGraphicsScanlineData;
typedef struct _LuaGBGraphics {
LuaGBGraphicsScanlineData scanline_data;
uint64_t vblank_count;
uint32_t last_edge;
uint32_t next_edge;
bool lcdstat;
uint8_t vram[0x8000];
uint8_t vram_bank;
uint8_t oam[0xA0];
LuaGBPaletteColor game_screen[144 * 160];
LuaGBGraphicRegisters registers;
LuaGBPalette palette;
LuaGBTileCache cache;
} LuaGBGraphics;
]] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.