content
stringlengths 5
1.05M
|
|---|
io.stdout:setvbuf('no') --console output at run
love.graphics.setDefaultFilter("nearest") --no anti aliasing
--[[
Love2d ZOOM and DRAG with mouse library _____________________________________________________________________________
code inspired by javidx9 (one lone coder)
https://youtu.be/ZQ8qtAizis4
made by me cr1m3 for love2d in Lua
_________________________________________________________________________________________________________
The symbolic concept is that you have multiple dimensions, like parallel dimensions in this program.
Since we are in 2D here, i will replace the word "dimension" by "space",
to avoid confusion between two dimensions (2D) and parallel dimension.
Here, we have basically the screen and the world spaces, both have an horizontal x and vertical y axis (2 dimensions).
We create some function to make a portal between screen and world spaces.
The portal is the function and the link between spaces is the offset.
--]]
--VARIABLES________________________________________________________
-- background image
local imgBckgd = love.graphics.newImage("Cave.png")
local offsetX = 0 -- screen to world offset
local offsetY = 0
local mousePosX = 0
local mousePosY = 0
local startMoveX = 0
local startMoveY = 0
local mouseWorldBeforeZoomX = 0
local mouseWorldBeforeZoomY = 0
local mouseWorldAfterZoomX = 0
local mouseWorldAfterZoomY = 0
local zoomX = 1.0 -- zoom default value
local zoomY = 1.0
--OBJECTS_______________________________________________________________
local screen = {}
screen.x = 0 -- screen pos (= window's up left corner)
screen.y = 0
local world = {} -- grid
world.x = 0
world.y = 0
world.width = 1024
world.height = 768
world.cell = 128 -- grid cell size
--______________________________________________________________________
-- screen space will be converted to world space then divided by the zoom factor and add the screen to world offset
function screenToWorld(screenX, screenY)
worldX = (screenX / zoomX) + offsetX
worldY = (screenY / zoomY) + offsetY
return worldX, worldY
end
function catchMousePosBeforeMove() --happens only once when btn is pressed
startMoveX = mousePosX -- capture mouse pos when clicking before moving
startMoveY = mousePosY
end
function love.update()
mousePosX = love.mouse.getX()
mousePosY = love.mouse.getY()
if love.mouse.isDown(1) then
offsetX = offsetX + (mousePosX - startMoveX) / zoomX -- modify the offset while moving
offsetY = offsetY + (mousePosY - startMoveY) / zoomY
startMoveX = mousePosX -- capture the mouse until the end of moving
startMoveY = mousePosY
end
end
function love.draw()
--add offset to objects that are a part of the world including the world grid
love.graphics.push() --describe briefly
love.graphics.scale(zoomX,zoomY) -- love2d zoom function
--draw image background
love.graphics.draw(imgBckgd, 0 + offsetX, 0 + offsetY)
--draw world grid
for yLines = 0, world.height, world.cell do
love.graphics.line(offsetX, yLines + offsetY, world.width + offsetX, yLines + offsetY)
for xLines = 0, world.width, world.cell do
love.graphics.line(xLines + offsetX, offsetY, xLines + offsetX, world.height + offsetY)
end
end
--draw rectangular object
love.graphics.setColor(1,0,0.2)
love.graphics.rectangle("fill", 260 + offsetX, 256 + offsetY, 30, 50)
love.graphics.setColor(1,1,1)
love.graphics.pop()
--show zoom factor
love.graphics.setColor(0,1,0.2)
love.graphics.print("zoomX = " .. zoomX, 20,50)
love.graphics.setColor(1,1,1)
end
function love.wheelmoved(x, y)
--zoom in and out
mouseWorldBeforeZoomX, mouseWorldBeforeZoomY = screenToWorld(mousePosX, mousePosY) -- mouse to world transformation, before zoom
if y > 0 then --wheelMouseUp
zoomX = zoomX * 1.101 --odd float number to prevent by zero division (multiply scale, not add to)
zoomY = zoomY * 1.101
elseif y < 0 then --wheelMouseDown
zoomX = zoomX * 0.901 --odd float number to prevent by zero division
zoomY = zoomY * 0.901
end
mouseWorldAfterZoomX, mouseWorldAfterZoomY = screenToWorld(mousePosX, mousePosY) -- mouse to world transformation, after zoom
--correct offset while zooming
offsetX = offsetX - (mouseWorldBeforeZoomX - mouseWorldAfterZoomX) -- minus correction
offsetY = offsetY - (mouseWorldBeforeZoomY - mouseWorldAfterZoomY)
end
-- callback functions
function love.mousepressed(x, y, button, istouch)
if button == 1 then
catchMousePosBeforeMove() --happens only once when btn is pressed
end
end
--restart game
function love.keypressed(key)
if key == "escape" then
love.event.quit("restart")
end
end
|
-- Binding for defold which includes file loading and json parsing
-- Usage is the same except the load() function accepts a string file location.
local Dialogger = require("dialogger")
local M = {}
M.TNODE_TEXT = "Text"
M.TNODE_NODE = "Node"
M.TNODE_CHOICE = "Choice"
M.TNODE_SET = "Set"
M.TNODE_BRANCH = "Branch"
-- dl_save_json is a string with dialogger game save string contents
function M.load(file)
local data = sys.load_resource(file)
if data == nil then
error("The dialogue file does not exist. Is the file path correct? "..file)
end
local nodes = json.decode(data)
return Dialogger.load(nodes)
end
--create a tree_execution that steps through the dialogue tree.
-- parameters is the tree table from load
-- game_context is the client interface for callbacks to show text, choices, and set/get variables
-- game_context should have four methods,
-- get(var_name)
-- set(var_name, string_value)
-- choice(choice_list)
-- visit(node_table) -- called just before any node is executed
-- text(text_node_name)
function M.begin(tree, game_context)
return Dialogger.begin(tree, game_context)
end
-- usage: do .. while not M.finished(tree_execution)
function M.finished(tree_execution)
return Dialogger.finished(tree_execution)
end
--choice_selection is an optional string if the tree is expecting a choice to be made. It is the string id or the table
function M.next(tree_execution, choice_selection_idstr_or_table)
return Dialogger.next(tree_execution, choice_selection_idstr_or_table)
end
-- Returns an empty game context with a variablestate setup and returned as second return value
function M.new_game_context()
return Dialogger.new_game_context()
end
return M
|
if not modules then modules = { } end modules ['meta-fnt'] = {
version = 1.001,
comment = "companion to meta-fnt.mkiv",
author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright = "PRAGMA ADE / ConTeXt Development Team",
license = "see context related readme files"
}
local next = next
local concat = table.concat
local format = string.format
local formatters = string.formatters
local chardata = characters.data
local fontdata = fonts.hashes.identifiers
local vffonts = fonts.handlers.vf
local mpfonts = fonts.mp or { }
fonts.mp = mpfonts
mpfonts.version = mpfonts.version or 1.20
mpfonts.inline = true
mpfonts.cache = containers.define("fonts", "mp", mpfonts.version, true)
metapost.fonts = metapost.fonts or { }
local function unicodetoactualtext(...)
unicodetoactualtext = backends.codeinjections.unicodetoactualtext
return unicodetoactualtext(...)
end
-- a few glocals
local characters, descriptions = { }, { }
local factor, code, slot, width, height, depth, total, variants, bbox, llx, lly, urx, ury = 100, { }, 0, 0, 0, 0, 0, 0, true, 0, 0, 0, 0
local flusher = {
startfigure = function(_chr_,_llx_,_lly_,_urx_,_ury_)
code = { }
slot = _chr_
llx = _llx_
lly = _lly_
urx = _urx_
ury = _ury_
width = urx - llx
height = ury
depth = -lly
total = total + 1
inline = mpfonts.inline
end,
flushfigure = function(t)
for i=1,#t do
code[#code+1] = t[i]
end
end,
stopfigure = function()
local cd = chardata[n]
local code = unicodetoactualtext(slot,concat(code," ")) or ""
descriptions[slot] = {
-- unicode = slot,
name = cd and cd.adobename,
width = width * 100,
height = height * 100,
depth = depth * 100,
boundingbox = { llx, lly, urx, ury },
}
if inline then
characters[slot] = {
commands = {
{ "pdf", "origin", code },
}
}
else
characters[slot] = {
commands = {
{
"image",
{
stream = code,
bbox = { 0, -depth * 65536, width * 65536, height * 65536 }
},
},
}
}
end
code = nil -- no need to keep that
end
}
local function process(mpxformat,name,instances,scalefactor)
local filename = resolvers.findfile(name)
local attributes = filename and lfs.isfile(filename) and lfs.attributes(filename)
if attributes then
statistics.starttiming(metapost.fonts)
scalefactor = scalefactor or 1
instances = instances or metapost.fonts.instances or 1 -- maybe store in liost too
local fontname = file.removesuffix(file.basename(name))
local modification = attributes.modification
local filesize = attributes.size
local hash = file.robustname(formatters["%s %05i %03i"](fontname,scalefactor*1000,instances))
local lists = containers.read(mpfonts.cache,hash)
if not lists or lists.modification ~= modification or lists.filesize ~= filesize or lists.instances ~= instances or lists.scalefactor ~= scalefactor then
statistics.starttiming(flusher)
local data = io.loaddata(filename)
metapost.reset(mpxformat)
metapost.setoutercolor(2) -- no outer color and no reset either
lists = { }
for i=1,instances do
characters = { }
descriptions = { }
metapost.process(
mpxformat,
{
formatters["randomseed := %s ;"](i*10),
formatters["charscale := %s ;"](scalefactor),
data,
},
false,
flusher,
false,
false,
"all"
)
lists[i] = {
characters = characters,
descriptions = descriptions,
parameters = {
designsize = 655360,
slant = 0,
space = 333 * scalefactor,
space_stretch = 166.5 * scalefactor,
space_shrink = 111 * scalefactor,
x_height = 431 * scalefactor,
quad = 1000 * scalefactor,
extra_space = 0,
},
properties = {
name = formatters["%s-%03i"](hash,i),
virtualized = true,
spacer = "space",
}
}
end
lists.version = metapost.variables.fontversion or "1.000"
lists.modification = modification
lists.filesize = filesize
lists.instances = instances
lists.scalefactor = scalefactor
metapost.reset(mpxformat) -- saves memory
lists = containers.write(mpfonts.cache, hash, lists)
statistics.stoptiming(flusher)
end
variants = variants + #lists
statistics.stoptiming(metapost.fonts)
return lists
else
return { }
end
end
metapost.fonts.flusher = flusher
metapost.fonts.instances = 1
metapost.fonts.process = process
local function build(g,v)
local size = g.specification.size
local data = process(v[2],v[3],v[4],size/655360,v[6])
local list = { }
local t = { }
for d=1,#data do
t = fonts.constructors.scale(data[d],-1000)
local id = font.nextid()
t.fonts = { { id = id } }
fontdata[id] = t
if v[5] then
vffonts.helpers.composecharacters(t)
end
list[d] = font.define(t)
end
for k, v in next, t do -- last t
g[k] = v -- kind of replace, when not present, make nil
end
g.properties.virtualized = true
g.variants = list
end
vffonts.combiner.commands.metapost = build
vffonts.combiner.commands.metafont = build
statistics.register("metapost font generation", function()
if total > 0 then
local time = statistics.elapsedtime(flusher)
if total > 0 then
return format("%i glyphs, %.3f seconds runtime, %.1f glyphs/second", total, time, total/time)
else
return format("%i glyphs, %.3f seconds runtime", total, time)
end
end
end)
statistics.register("metapost font loading",function()
if variants > 0 then
local time = statistics.elapsedtime(metapost.fonts)
if variants > 0 then
return format("%.3f seconds, %i instances, %.3f instances/second", time, variants, variants/time)
else
return format("%.3f seconds, %i instances", time, variants)
end
end
end)
-- fonts.definers.methods.install( "bidi", {
-- {
-- "metapost", -- method
-- "metafun", -- format
-- "fontoeps.mp", -- filename
-- 1, -- instances
-- false, -- compose
-- },
-- } )
local report = logs.reporter("metapost","fonts")
function metapost.fonts.define(specification)
local fontname = specification.fontname or ""
local filename = specification.filename or ""
local format = specification.format or "metafun"
if fontname == "" then
report("no fontname given")
return
end
if filename == "" then
report("no filename given for %a",fontname)
return
end
local fullname = resolvers.findfile(filename)
if fullname == "" then
report("unable to locate file %a",filename)
return
end
report("generating font %a using format %a and file %a",fontname,format,filename)
fonts.definers.methods.install(fontname, {
{
specification.engine or "metapost",
format,
filename,
specification.instances or 1,
specification.compose or false,
},
} )
end
interfaces.implement {
name = "definemetafont",
actions = metapost.fonts.define,
arguments = {
{
{ "fontname" },
{ "filename" },
}
}
}
-- metapost.fonts.define {
-- fontname = "bidi",
-- filename = "bidi-symbols.mp",
-- }
|
--- @module Event.test
-- Tests for Event class
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Modules = ReplicatedStorage:WaitForChild("Modules")
local Event = require(Modules:WaitForChild("Event"))
local EventTests = {}
EventTests["test_Event"] = function ()
-- Utility
local myFunctionDidRun = false
local function myFunction()
myFunctionDidRun = true
end
-- Event.new
local event = Event.new()
assert(type(event) ~= "nil")
-- Event:connect
local connection = event:connect(myFunction)
assert(type(connection) ~= "nil", "Event:connect should return a connection")
-- Event:fire
event:fire()
assert(myFunctionDidRun, "Event:fire should run connected functions")
-- Connection:disconnect()
myFunctionDidRun = false
connection:disconnect()
connection = nil
event:fire()
assert(not myFunctionDidRun, "Event:fire should not run disconnected functions")
-- Event:cleanup
event:cleanup()
event = nil
end
return EventTests
|
answ = {"on the line and show the length of it.", "on the same side as the line.", " on different sides of the line." }
|
--[[
################################################################################
#
# Copyright (c) 2014-2018 Ultraschall (http://ultraschall.fm)
#
# 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.
#
################################################################################
]]
-- little helpers
-- 2. Eine Aktion “set next planned Marker”
-- Sucht sich den Marker mit grünem Farbwert und kleinstem Zeitstempel,
-- und setzt ihn auf die aktuelle Aufnahmezeit/Editposition und stellt den
-- Farbwert auf das normale Grau.
-- little helpers
local info = debug.getinfo(1,'S');
script_path = info.source:match[[^@?(.*[\/])[^\/]-$]]
dofile(script_path .. "ultraschall_helper_functions.lua")
reaper.Undo_BeginBlock()
a,A=ultraschall.GetUSExternalState("ultraschall_follow", "state")
function get_position()
if reaper.GetPlayState() == 0 or reaper.GetPlayState() == 2 then -- 0 = Stop, 2 = Pause
current_position = reaper.GetCursorPosition() -- Position of edit-cursor
else
if A~="0" then -- follow mode is active
current_position = reaper.GetPlayPosition() -- Position of play-cursor
-- elseif reaper.GetPlayState()~=0 then
-- current_position = reaper.GetCursorPosition() -- Position of play-cursor
else
current_position = reaper.GetCursorPosition() -- Position of edit-cursor
end
end
return current_position
end
play_pos=get_position()
num_markers=reaper.CountProjectMarkers(0) -- number of markers + regions!
PlannedColor = ultraschall.ConvertColor(100,255,0) -- color of all planned markers
for i=0, num_markers-1 do
retval, isrgnOut, posOut, rgnendOut, nameOut, markrgnindexnumberOut, colorOut = reaper.EnumProjectMarkers3(0, i)
if isrgnOut==false and colorOut==PlannedColor then -- green and not a region
-- move to play_pos and change color to grey
runcommand("_Ultraschall_Center_Arrangeview_To_Cursor") -- scroll to cursor if not visible
reaper.SetProjectMarker4(0, markrgnindexnumberOut, false, play_pos, 0, nameOut, 0x666666|0x1000000, 0)
break
end
end
ultraschall.RenumerateMarkers(0x666666|0x1000000, 1)
reaper.Undo_EndBlock("Ultraschall: Set next planned marker.",0)
|
-- scaffold geniefile for xxHash
xxHash_script = path.getabsolute(path.getdirectory(_SCRIPT))
xxHash_root = path.join(xxHash_script, "xxHash")
xxHash_includedirs = {
path.join(xxHash_script, "config"),
xxHash_root,
}
xxHash_libdirs = {}
xxHash_links = {}
xxHash_defines = {}
----
return {
_add_includedirs = function()
includedirs { xxHash_includedirs }
end,
_add_defines = function()
defines { xxHash_defines }
end,
_add_libdirs = function()
libdirs { xxHash_libdirs }
end,
_add_external_links = function()
links { xxHash_links }
end,
_add_self_links = function()
links { "xxHash" }
end,
_create_projects = function()
project "xxHash"
kind "StaticLib"
language "C++"
flags {}
includedirs {
xxHash_includedirs,
}
defines {}
files {
path.join(xxHash_script, "config", "**.h"),
path.join(xxHash_root, "**.h"),
path.join(xxHash_root, "**.cpp"),
}
end, -- _create_projects()
}
---
|
return {
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "oxyAtkDuration",
number = 4.5
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "oxyAtkDuration",
number = 5.2
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "oxyAtkDuration",
number = 6
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "oxyAtkDuration",
number = 7
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "oxyAtkDuration",
number = 7.7
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "oxyAtkDuration",
number = 8.5
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "oxyAtkDuration",
number = 9.5
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "oxyAtkDuration",
number = 10.2
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "oxyAtkDuration",
number = 11
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "oxyAtkDuration",
number = 12
}
}
}
},
time = 0,
name = "水面作战",
init_effect = "jinengchufablue",
color = "blue",
picture = "",
desc = "",
stack = 1,
id = 3520,
icon = 3520,
last_effect = "",
blink = {
0,
0.7,
1,
0.3,
0.3
},
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "oxyAtkDuration",
number = 4.5
}
}
}
}
|
object_tangible_furniture_decorative_campfire = object_tangible_furniture_decorative_shared_campfire:new {
}
ObjectTemplates:addTemplate(object_tangible_furniture_decorative_campfire, "object/tangible/furniture/decorative/campfire.iff")
|
-- Copyright 2012 by Malte Skambath
--
-- This file may be distributed an/or modified
--
-- 1. under the LaTeX Project Public License and/or
-- 2. under the GNU Public License
--
-- See the file doc/generic/pgf/licenses/LICENSE for more information
--
local key = require 'pgf.gd.doc'.key
local documentation = require 'pgf.gd.doc'.documentation
local summary = require 'pgf.gd.doc'.summary
local example = require 'pgf.gd.doc'.example
--------------------------------------------------------------------
key "animated tree layout"
summary "This layout uses the Reingold--Tilform method for drawing trees."
documentation
[[
A method to create layouts for evolving graphs as an SVG animation.The Reingold--Tilford method is a standard method for drawing
trees. It is described in:
The algorithm, which is based on the Reingold--Tilford algorithm and
its implementation in |graphdrawing.trees|, is introduced in my Masthesis:
%
\begin{itemize}
\item
M.\ Skambath,
\newblock Algorithmic Drawing of Evolving Trees, Masterthesis, 2016
\end{itemize}
You can use the same known graph macros as for other graph drawing
algorithms in Ti\emph{k}Z. In addition all keys and features that
are available for the static tree algorithm can be used:
%
\begin{codeexample}[animation list={1,1.5,2,2.5,3,3.5,4}]
\tikz \graph[animated binary tree layout,
nodes={draw,circle}, auto supernode,
] {
{[when=1] 15 -> {10 -> { ,11}, 20 }},
{[when=2] 15 -> {10 -> {3,11}, 20 }},
{[when=3] 15 -> {10 -> {3, }, 20 }},
{[when=4] 15 -> {10 -> {3, }, 20 -> 18 }},
};
\end{codeexample}
]]
example
[[
\tikz[animated binary tree layout]
\graph[nodes={draw,circle}, auto supernode] {
{[when=1] 15 -> {10 -> { ,11}, 20 }},
{[when=2] 15 -> {10 -> {3,11}, 20 }},
{[when=3] 15 -> {10 -> {3, }, 20 }},
{[when=4] 15 -> {10 -> {3, }, 20 -> 18 }},
};
]]
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
key "animated binary tree layout"
summary
[[ A layout based on the Reingold--Tilford method for drawing
binary trees.
]]
documentation
[[
This key executes:
%
\begin{enumerate}
\item |animated tree layout|, thereby selecting the Reingold--Tilford method,
\item |minimum number of children=2|, thereby ensuring the all nodes
have (at least) two children or none at all, and
\end{enumerate}
]]
example
[[
]]
example
[[
]]
--------------------------------------------------------------------
--------------------------------------------------------------------
key "extended animated binary tree layout"
summary
[[ This algorithm is similar to |animated binary tree layout|, only the
option \texttt{missing nodes get space} is executed and the
\texttt{significant sep} is zero.
]]
example
[[
]]
--------------------------------------------------------------------
|
-- After the map has loaded all entities
hook.Add("InitPostEntity", "Minigolf.CountHolesAndMarkPhysboxesForCustomPhys", function()
NUM_HOLES = 0
Minigolf.Holes.All = Minigolf.Holes.All or {}
-- Maybe we decide to have multiple starts to a single hole, anyways lets then just count the unique hole names
for _, hole in ipairs(ents.FindByClass("minigolf_hole_start")) do
local uniqueHoleName = hole:GetUniqueHoleName()
if(not Minigolf.Holes.All[uniqueHoleName])then
Minigolf.Holes.All[uniqueHoleName] = hole
NUM_HOLES = NUM_HOLES + 1
end
end
for _, physBox in ipairs(ents.FindByClass("func_physbox")) do
physBox:SetCustomCollisionCheck(true)
end
end)
|
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
local voices = {
{ text = "Ahhhh!" },
{ text = "Have mercy!" },
{ text = "I admit! I admit!" },
{ text = "I repent!" },
{ text = "Noooooo!" },
{ text = "Please! I beg you to stop!" },
{ text = "Take it away! Please!" }
}
npcHandler:addModule(VoiceModule:new(voices))
npcHandler:addModule(FocusModule:new())
|
local i, tmpEntityNum;
while true do
if memory.readbyte(0x03000964) == 255 or memory.readbyte(0x03000964) == 0 then
gui.text(16,0,"Running", 0xFFFF0000, topleft)
else
tmpEntityNum = 0
i = 0
for i=0, 64, 1 do
if memory.readbyte(0x03000964 + 3 * i) == 255 then
break
end
tmpEntityNum = tmpEntityNum + 1
end
i = 0
while(i < tmpEntityNum) do
local entityid = memory.readbyte(0x0300011b + i * 0x2C)
if entityid == 21 then -- if this entity is a rock, perhaps I should add gem bubble into the if-statement
memory.write_u8(0x03000105 + i * 0x2C, 1)
end
i = i + 1
end
end
emu.frameadvance()
end
|
--
-- Copyright (c) 2020 Tom Hancocks
--
local scene = Scene.current()
-- ----------------------------------------------------------------------------
local brickSize = Size(100, 20)
local gridSize = Size(10, 10)
local gridWidth = (gridSize.width * brickSize.width)
local gridPosition = Point(52, 50)
local ballVelocity = Vec2(2, 2)
local ballSprite = SpriteSheet.load(Resource.id(129))
local ball = ballSprite:spawnEntity(Vec2(520, 400))
-- ----------------------------------------------------------------------------
-- Brick
Brick = {}
Brick.__index = Brick
setmetatable(Brick, {
__call = function (cls, ...)
local self = setmetatable({}, cls)
self:__init(...)
return self
end
})
function Brick:__init(brickNumber)
-- Load the brick sprites
local color = math.floor((brickNumber / gridSize.width) / 2.0)
local sprite = MacintoshPicture.load(Resource.id(128 + color))
sprite:setSpriteSize(Size(100, 20))
local gridX = math.floor(brickNumber % gridSize.width) * (brickSize.width + 4)
local gridY = math.floor(brickNumber / gridSize.width) * (brickSize.height + 4)
local entity = sprite:spawnEntity(Vec2(gridPosition.x + gridX, gridPosition.y + gridY))
self.entity = entity
self.destroyed = false
end
function Brick:draw()
self.entity:draw()
end
function Brick:handleBallCollision()
if self.entity:intersects(ball) then
ballVelocity.y = -ballVelocity.y
self.destroyed = true
end
end
local bricks = {}
for i = 1, 100 do
bricks[i] = Brick(i - 1)
end
-- ----------------------------------------------------------------------------
-- Paddle
Paddle = {}
Paddle.__index = Paddle
setmetatable(Paddle, {
__call = function (cls, ...)
local self = setmetatable({}, cls)
self:__init(...)
return self
end
})
function Paddle:__init()
-- Load the paddle sprite
local sprite = SpriteSheet.load(Resource.id(128))
self.entity = sprite:spawnEntity(Vec2(520, 760))
-- Configure
self.speed = 20
end
function Paddle:move(x)
local x = self.entity.position.x + (x * self.speed)
if x > 50 and x < 980 then
self.entity.position = Vec2(x, 760)
end
end
function Paddle:draw()
self.entity:draw()
end
function Paddle:handleBallCollision()
if self.entity:intersects(ball) then
ballVelocity.y = -ballVelocity.y
end
end
local paddle = Paddle()
-- ----------------------------------------------------------------------------
scene:render(function()
-- Update the game state
ball.position = ball.position:add(ballVelocity)
paddle:handleBallCollision()
-- Draw the sprites
for i = 1, 100 do
if not bricks[i].destroyed then
bricks[i]:draw()
bricks[i]:handleBallCollision()
end
end
paddle:draw()
ball:draw()
-- Edge detection
if ball.position.x < 0 or ball.position.x > 1040 then
ballVelocity.x = -ballVelocity.x
end
if ball.position.y < 0 or ball.position.y > 800 then
ballVelocity.y = -ballVelocity.y
end
end)
scene:onKeyEvent(function(event)
if event.keycode == 263 or event.keycode == 65 then
paddle:move(-1)
elseif event.keycode == 262 or event.keycode == 68 then
paddle:move(1)
end
end)
|
return function(doc, meta, to)
return doc + 3
end
|
-- Place Bison -- Author: Neirai -- DateCreated: 5/12/2014 9:35:31 AM
function buildACow(pPlayer, pCity)
for pCityPlot = 1, pCity:GetNumCityPlots() - 1, 1 do
local pSpecificPlot = pCity:GetCityIndexPlot(pCityPlot)
if
pSpecificPlot:GetTerrainType() == TerrainTypes.TERRAIN_GRASS then
if pSpecificPlot:GetFeatureType() == (-1) and not pSpecificPlot:IsMountain() then
if pSpecificPlot:GetResourceType(-1) == (-1) then
pSpecificPlot:SetResourceType(GameInfoTypes.RESOURCE_COW, 1)
pSpecificPlot:SetImprovementType(GameInfoTypes.IMPROVEMENT_PASTURE)
print("Cow Placed on Grasslands")
return true
end
end
elseif
pSpecificPlot:GetTerrainType() == TerrainTypes.TERRAIN_PLAINS then
if pSpecificPlot:GetFeatureType() == (-1) and not pSpecificPlot:IsMountain() then
if pSpecificPlot:GetResourceType(-1) == (-1) then
pSpecificPlot:SetResourceType(GameInfoTypes.RESOURCE_COW, 1)
pSpecificPlot:SetImprovementType(GameInfoTypes.IMPROVEMENT_PASTURE)
print("Cow Placed on Plains")
return true
end
end
end
end
return false
end
function PutCowSomewhere(player, city, building)
print(building)
print(GameInfoTypes.BUILDING_BULLRING)
if building == GameInfoTypes.BUILDING_3UC_BULLRING then
local pPlayer = Players[player]
local pCity = pPlayer:GetCityByID(city)
if buildACow(pPlayer, pCity) == false then
print("No place to place a Cow.")
end
end
end
GameEvents.CityConstructed.Add(PutCowSomewhere)
|
hook.Add("Initialize", "TTT Wheel i12n", function()
if (GAMEMODE.Name != "Trouble in Terrorist Town") then return end;
include("tttwheel/sh_init.lua")
if (SERVER) then
AddCSLuaFile();
AddCSLuaFile("tttwheel/cl_init.lua");
AddCSLuaFile("tttwheel/sh_init.lua");
include("tttwheel/sv_init.lua");
else
include("tttwheel/cl_init.lua");
end
end);
|
if not _ACTION then
-- Docs: http://industriousone.com/command-line-arguments
error("No target specified, e.g. vs2010 or xcode4")
end
--
-- Try to read the options user options.
-- This contains a table "user".
--
local user_config_options = '../user.lua'
if ( io.open(user_config_options) ) then
print("Reading user options")
dofile(user_config_options)
else
print("No user options. Writing defaults.")
local fh = io.open(user_config_options,'w')
fh:write([[
-- User overrides. Comment in to use, otherwise ignored.
user = {
--- User include/lib paths. E.g. look for dependencies
--- Note: Use "/" for Windows, not "\".
--includes = { "/my/path" }, -- User include paths.
--libs = { "/my/path" }, -- User lib paths.
--- Options. These are ignored if not applicable.
--macports = true, -- Use Macports on OSX.
--al_monolithic = true, -- Link to monolithic lib for Alllegro5.
}
]])
fh:close()
dofile(user_config_options)
end
local c_platform = os.get()
print("Platform: " .. c_platform)
dofile( c_platform .. ".lua" )
function DefineRenderer( name, filetable )
project ( "Renderer-"..name )
files( filetable )
flags( { "Symbols" } )
kind( "StaticLib" )
if ( os.get() == "macosx" ) then
if user.macports then
includedirs { "/opt/local/include" }
end
end
if ( user.includes ) then
includedirs(user.includes)
end
configuration( "Release" )
targetname( "GWEN-Renderer-"..name )
configuration( "Debug" )
targetname( "GWEND-Renderer-"..name )
end
function DefineSample(opt)
-- options: name, files, links(d), defs
local prjname = "Sample-" .. opt.name
print("Adding " .. prjname)
project( prjname )
targetdir ( "../bin" )
if ( debugdir ) then
debugdir ( "../bin" )
end
if ( opt.defs ) then defines( opt.defs ) end
files { opt.files }
kind "WindowedApp"
if ( os.get() == "macosx" ) then
-- C++11 libs
linkoptions { "-stdlib=libc++" }
if user.macports then
-- Add Macports for dependencies
includedirs { "/opt/local/include" }
libdirs { "/opt/local/lib" }
end
end
if ( user.includes ) then
includedirs(user.includes)
end
if ( user.libs ) then
libdirs(user.libs)
end
configuration( "Release" )
targetname( opt.name .. "Sample" )
links( opt.links )
configuration "Debug"
targetname( opt.name .. "Sample_D" )
links( opt.linksd or opt.links )
end
|
--[[
Author: Tinywan
Mail: Overcome.wan@Gmail.com
Date: 2017/3/12
Github: https://github.com/Tinywan
Description: 这是一个配置文件信息包
--]]
local M = {}
local redis = {}
redis['host'] = '127.0.0.1'
redis['port'] = 6379
redis['pwd'] = 'tinywanredis'
redis['prefix'] = 'url_server:'
redis['info'] = 'info_ad:'
redis['count'] = 'count_ad:'
local err_msg = {}
err_msg[42] = 'URL is invalid'
err_msg[51] = 'Redis is out of service'
err_msg[52] = 'Getting data error'
local default = {}
default['url'] = 'http://127.0.0.1/url'
M['redis'] = redis
M['err_msg'] = err_msg
M['default'] = default
return M
|
local M = { }
local T = require("PackageToolkit").module
local windows = T.import(..., "_windows").windows
M.path = function(env)
if windows() then
if env == "HOME" then
return string.format("C:%s", os.getenv("HOMEPATH"))
else
return ""
end
else
if env == "HOME" then
return os.getenv("HOME")
else
return ""
end
end
end
return M
|
Config = {}
Config.Price = 10
-- EDIT THIS ONLY IF YOU KNOW WHATE YOU ARE DOING!!!
Config.Machines = { -- EDIT THIS ONLY IF YOU KNOW WHATE YOU ARE DOING!!!
"prop_vend_coffe_01" -- EDIT THIS ONLY IF YOU KNOW WHATE YOU ARE DOING!!!
} -- EDIT THIS ONLY IF YOU KNOW WHATE YOU ARE DOING!!!
-- EDIT THIS ONLY IF YOU KNOW WHATE YOU ARE DOING!!!
|
if GetLocale() ~= "ptBR" then return end
if not DBM_GUI_Translations then DBM_GUI_Translations = {} end
local L = DBM_GUI_Translations
L.MainFrame = "Deadly Boss Mods"
L.TranslationBy = "GlitterStorm @ Azralon"
L.OTabBosses = "Chefes"
L.OTabOptions = "Opções"
L.TabCategory_Options = "Opções Gerais"
L.TabCategory_WOD = "Warlords of Draenor"
L.TabCategory_MOP = "Mists of Pandaria"
L.TabCategory_CATA = "Cataclysm"
L.TabCategory_WOTLK = "Wrath of the Lich King"
L.TabCategory_BC = "The Burning Crusade"
L.TabCategory_CLASSIC = "Wow Vanilla"
L.TabCategory_PVP = "PVP"
L.TabCategory_OTHER = "Outros módulos"
L.BossModLoaded = "%s estatísticas"
L.BossModLoad_now = [[Esse módulo não está carregado.
Ele será carregado quando você entrar na instância.
Você também pode clicar no botão para carregar o módulo manualmente.]]
L.PosX = 'Posição X'
L.PosY = 'Posição Y'
L.MoveMe = 'Mova-me'
L.Button_OK = 'OK'
L.Button_Cancel = 'Cancelar'
L.Button_LoadMod = 'Carregar AddOn'
L.Mod_Enabled = "Habilitar módulo"
L.Mod_Reset = "Carregar opções padrão"
L.Reset = "Resetar"
L.Enable = "Habilitar"
L.Disable = "Desabilitar"
L.NoSound = "Sem som"
L.IconsInUse = "Ícones utilizados por esse módulo"
-- Tab: Boss Statistics
L.BossStatistics = "Estatísticas do Chefe"
L.Statistic_Kills = "Vitórias:"
L.Statistic_Wipes = "Derrotas:"
L.Statistic_Incompletes = "Incompletos:"--Para cenários, TODO, encontrar um jeito limpo de substituir derrotas por estatística incompleto para mods de cenário
L.Statistic_BestKill = "Melhor tempo:"
-- Tab: General Core Options
L.General = "Opções gerais do DBM"
L.EnableMiniMapIcon = "Exibir botão no mini-mapa"
L.UseMasterVolume = "Utilizar canal principal de áudio para reproduzir arquivos de som."
L.Latency_Text = "Definir latência máxima de sincronização: %d"
-- Tab: General Timer Options
L.TimerGeneral = "Opções gerais do temporizador do DBM"
L.SKT_Enabled = "Sempre mostrar um temporizador de sua vitória recorde (Sobrepõe a opção do chefe específico)"
L.CRT_Enabled = "Mostrar um temporizador para a próxima carga de ressureição em combate(apenas nas dificuldades 6.x)"
L.ChallengeTimerOptions = "Colocar opção para temporizador de melhor tempo em modo desafio"
L.ChallengeTimerPersonal = "Pessoal"
L.ChallengeTimerRealm = "Reino"
L.ModelOptions = "Opções do Visualizador de Modelos 3D"
L.EnableModels = "Habilitar modelos 3D nas opções de chefe"
L.ModelSoundOptions = "Definir opção de som para o visualizador de modelos"
L.ModelSoundShort = "Curto"
L.ModelSoundLong = "Longo"
L.Button_RangeFrame = "Exibir/esconder quadro de distância"
L.Button_RangeRadar = "Exibir/esconder radar de distância" -- Não existe no en.lua
L.Button_InfoFrame = "Exibir/esconder quadro de informações"
L.Button_TestBars = "Iniciar barras de teste"
-- Tab: Raidwarning
L.Tab_RaidWarning = "Avisos de Raid"
L.RaidWarning_Header = "Opções de Avisos de Raid"
L.RaidWarnColors = "Cores dos Avisos de Raid"
L.RaidWarnColor_1 = "Cor 1"
L.RaidWarnColor_2 = "Cor 2"
L.RaidWarnColor_3 = "Cor 3"
L.RaidWarnColor_4 = "Cor 4"
L.InfoRaidWarning = [[Você pode especificar a cor e posição do quadro de avisos de raid.
Esse quadro é utilizado para mensagens como "Jogador X está sob efeito de Y".]]
L.ColorResetted = "As opções de cor desse campo foram resetadas."
L.ShowWarningsInChat = "Exibir avisos na janela de chat."
L.ShowFakedRaidWarnings = "Exibir avisos como mensagens falsas de aviso de raid."
L.WarningIconLeft = "Mostrar ícone do lado esquerdo."
L.WarningIconRight = "Mostrar ícone do lado direito."
L.WarningIconChat = "Mostrar ícones no chat"
-- estavam faltando as linhas abaixo
L.Warn_FontType = "Escolha fonte"
L.Warn_FontStyle = "Bandeira de fonte (flags)"
L.Warn_FontShadow = "Sombra da fonte"
L.Warn_FontSize = "Tamanho da fonte: %d"
L.Warn_Duration = "duração do aviso: %d seg"
L.None = "nada"
L.Outline = "Contorno"
L.ThickOutline = "Espessura do contorno"
L.MonochromeOutline = "Contorno Monocromático"
L.MonochromeThickOutline = "Espessura do contorno Monocromático"
L.RaidWarnSound = "toque som no aviso de raid"
-- não existem no en.lua
L.RaidWarnMessage = "Obrigado por utilizar o Deadly Boss Mods" -- não existe no en.lua
L.BarWhileMove = "Aviso de Raid móvel" -- não existe no en.lua
L.RaidWarnSound = "Tocar som junto com o aviso na raid" -- não existe no en.lua
-- Tab: Generalwarnings
L.Tab_GeneralMessages = "Mensagens em geral"
L.CoreMessages = "Opções de mensagens principais"
L.ShowPizzaMessage = "Exibir mensagens ao receber cronógrafos no quadro de chat"
L.ShowAllVersions = "exibir a versão da mod para todos os membros no chat"
L.CombatMessages = "Opções de mensagens de combate"
L.ShowEngageMessage = "Exibir mensagens ao iniciar combate no quadro de chat"
L.ShowDefeatMessage = "Exibir mensagens ao vencer chefes no quadro de chat"
L.ShowGuildMessages = "Exibir mensagens de puxada/vitória/derrota no quadro de chat"
L.WhisperMessages = "Opções de mensagens de sussurro"
L.AutoRespond = "Responder automaticamente a sussurros durante a luta"
L.EnableStatus = "Responder a sussurros de 'status'"
L.WhisperStats = "Incluir estatísticas de derrotas/vitórias nas respostas a sussurros"
-- Tab: Barsetup
L.BarSetup = "Configurações da barra"
L.BarTexture = "Textura da barra"
L.BarStyle = "Estilo da barra"
L.BarDBM = "DBM"
L.BarSimple = "Simple (sem animação)"
L.BarStartColor = "Cor inicial"
L.BarEndColor = "Cor final"
L.Bar_Font = "Fonte utilizada na barra"
L.Bar_FontSize = "Tamanho da fonte"
L.Bar_Height = "Altura da barra: %d"
L.Slider_BarOffSetX = "Deslocamento X: %d"
L.Slider_BarOffSetY = "Deslocamento Y: %d"
L.Slider_BarWidth = "Largura da barra: %d"
L.Slider_BarScale = "Escala da barra: %0.2f"
L.AreaTitle_BarSetup = "Opções gerais de barra"
L.AreaTitle_BarSetupSmall = "Opções da barra pequena"
L.AreaTitle_BarSetupHuge = "Opções da barra grande"
L.EnableHugeBar = "Habilitar barra grande (aka Barra 2)"
L.BarIconLeft = "Ícone da esq."
L.BarIconRight = "Ícone da dir."
L.ExpandUpwards = "Expandir para cima"
L.FillUpBars = "Barras enchem"
L.ClickThrough = "Desabilitar eventos de mouse (permite clicar através das barras)"
L.Bar_Decimal = "Exibir porcentagens abaixo do temporizador: %d"
L.Bar_DBMOnly = "As opções abaixo só funcionam com o estilo de barra \"DBM\" ."
L.Bar_EnlargeTime = "Barras aumentam abaixo deste tempo: %d"
L.Bar_EnlargePercent = "Barras aumentam abaixo desta porcentagem: %0.1f%%"
L.BarSpark = "Barra faísca"
L.BarFlash = "Barra pisca quando estiver para expirar"
L.BarSort = "selecionar pelo tempo restante"
-- Tab: Spec Warn Frame
L.Panel_SpecWarnFrame = "Avisos Especiais"
L.Area_SpecWarn = "Opções de Avisos Especiais"
L.ShowSWarningsInChat = "Exibir avisos especiais no quadro de chat"
L.SpecWarn_FlashFrame = "Brilhar tela em avisos especiais"
L.SpecWarn_FlashFrameRepeat = "Repetir %d vezes (se habilitado)"
L.SpecWarn_Font = "Fonte utilizada para avisos especiais"
L.SpecWarn_FontSize = "Tamanho da fonte"
L.SpecWarn_FontColor = "Cor da fonte"
L.SpecWarn_FontType = "Selecionar fonte"
L.SpecWarn_FlashRepeat = "Repetir piscada"
L.SpecWarn_FlashColor = "Cor pisca"
L.SpecWarn_FlashDur = "Duração da piscada: %0.1f"
L.SpecWarn_FlashAlpha = "Alfa da piscada: %0.1f"
L.SpecWarn_DemoButton = "Mostrar exemplo"
L.SpecWarn_MoveMe = "Definir posição"
L.SpecWarn_ResetMe = "Redefinir padrões"
L.SpecialWarnSound = "Definir som para aviso especial afetando você ou sua função na raid"
L.SpecialWarnSound2 = "Definir som para aviso especial afetando todos na raid"
L.SpecialWarnSound3 = "Definir som para aviso especial MUITO IMPORTANTE"
L.SpecialWarnSound4 = "Definir som para aviso especial se sair correndo"
-- Tab: Spoken Alerts Frame
L.Panel_SpokenAlerts = "Avisos falados"
L.Area_VoiceSelection = "seleção de vozes"
L.CountdownVoice = "Definir voz primaria para sons de contagem"
L.CountdownVoice2 = "Definir voz secundaria para sons de contagem"
L.CountdownVoice3 = "Definir voz terciária para sons de contagem"
L.VoicePackChoice = "Definir pacote de vozes para avisos falados"
L.Area_CountdownOptions = "opções de contagens"
L.ShowCountdownText = "Exibir texto de contagem durante contagens primarias"
L.Area_VoicePackOptions = "Opções de pacotes de vozes (Pacotes de vozes de terceiros)"
L.SpecWarn_NoSoundsWVoice = "Filtrar avisos sonoros especiais para avisos que contem avisos falados ..."
L.SWFNever = "Nunca"
L.SWFDefaultOnly = "Quando avisos especiais usarem som padrão ( permitir que sons customizados ainda toquem)."
L.SWFAll = "Quando sons especiais usarem qualquer som"
L.SpecWarn_AlwaysVoice = "Sempre tocar todos os avisos falados (Substitui opções especificas dos chefes. Útil para lideres de raids)"
--TODO, maybe add URLS right to GUI panel on where to acquire 3rd party voice packs? talvez ...
-- Tab: HealthFrame
L.Panel_HPFrame = "Quadro de Vida"
L.Area_HPFrame = "Opções do Quadro de Vida"
L.HP_Enabled = "Sempre exibir quadro de vida (Sobrepõe opção específica por chefe)"
L.HP_GrowUpwards = "Expandir quadro de vida para cima"
L.HP_ShowDemo = "Exibir quadro de vida"
L.BarWidth = "Largura da barra: %d"
-- Tab: Global Filter
L.Panel_SpamFilter = "DBM Desligamentos globais & filtros"
L.Area_SpamFilter_Outgoing = "DBM opções de desligamentos globais & filtros"
L.SpamBlockNoShowAnnounce = "Não exibir anúncios ou tocar avisos sonoros"
L.SpamBlockNoSetIcon = "Não marcar jogadores com ícones"
L.SpamBlockNoRangeFrame = "Não exibir quadro de distancia"
L.SpamBlockNoInfoFrame = "Não exibir quadro de informação"
L.SpamBlockNoHudMap = "Não mostrar mapas HudMap (heads up display Map)"
L.SpamBlockNoHealthFrame = "Não exibir quadros de vida"
L.SpamBlockNoCountdowns = "Não tocar sons de contagem regressiva"
L.SpamBlockNoIconRestore = "Não guardar estado dos ícones e restaura-los ao fim do combate"
L.SpamBlockNoRangeRestore = "Não restaurar o quadro de distancia para o estado anterior ( show/hide ) quando a mod pedir hide'"
-- Tab: Spam Filter
L.Panel_SpamFilter = "Filtros Global e de Spam"
L.Area_SpamFilter = "Opções do filtro Global"
L.DontShowFarWarnings = "Não exibir anúncios/temporizadores para eventos que estão longe"
L.StripServerName = "Tira com nome do reino em avisos e temporizadores"
L.SpamBlockBossWhispers = "Filtra <DBM> avisos de sussurro enquanto estiver lutando"
L.BlockVersionUpdateNotice = "Desabilitar popup de notificação de atualização (Não recomendado)"
L.Area_SpecFilter = "Opções de especialização"
L.FilterTankSpec = "Filtrar mensagens designadas para tank role quando não for tank. (Nota: Desabilitar esta função não é recomendado para a maioria dos usuários já que avisos de 'taunt' ( insultos ) estão habilitados por definição.)"
L.FilterInterrupts = "Filtrar avisos para habilidades passivas de cortes ( interrupts ) se o alvo não for o seu target ou focus ( Não se aplica para magias criticas que resultaram em derrota caso não seja interrompida)"
L.FilterDispels = "Filtrar avisos para magias dissipáveis se a seu dissipar estiver em recarga."
L.FilterSelfHud = "Filtrar a si mesmo no HudMap (Exclui funções de hud baseadas na distância)"
L.Area_PullTimer = "Opções de Filtros de Puxada, pausa, Combate, & Temporizador customizados"
L.DontShowPTNoID = "Bloquear o temporizador de Puxada se não foi enviado na mesma zona que você"
L.DontShowPT = "Não exibir a barra de puxada"
L.DontShowPTText = "Não exibir texto de anúncio do temporizador de puxada"
L.DontPlayPTCountdown = "Não tocar o áudio da contagem regressiva de puxada/combate/customizado"
L.DontShowPTCountdownText = "Não exibir o texto da contagem regressiva de puxada/combate/customizado"
L.PT_Threshold = "Não exibir o texto da contagem regressiva de puxada/combate/customizado acima de: %d"
L.Panel_HideBlizzard = "Esconder Blizzard"
L.Area_HideBlizzard = "Esconder Opções da Blizzard"
L.HideBossEmoteFrame = "Esconder o quadro de emote do chefe de raid durante as lutas"
L.HideWatchFrame = "Esconder/acompanhar quadros (de objetivos) durante as lutas contra os chefes, caso nenhuma conquista esteja sendo acompanhada. No modo desafio, cria uma medalha temporária na luta de chefes enquanto o quadro estiver escondido"
L.HideGarrisonUpdates = "Esconde o quadro de missão completada da guarnição enquanto estiver lutando com algum chefe"
L.HideGuildChallengeUpdates = "Esconde o quadro de desafio de guilda durante a luta contra algum chefe"
L.HideTooltips = "Esconder as dicas durante as lutas contra os chefes"
L.DisableSFX = "Desativa o canal de efeitos sonoros durante lutas contra chefes"
L.SpamBlockSayYell = "Esconder os anúncios de balões de chat do quadro de chat"
L.DisableCinematics = "Esconder as cinematics in-game"
L.AfterFirst = "Depois que o vídeo for assistido uma vez"
L.Panel_ExtraFeatures = "Características Extra"
L.Area_ChatAlerts = "Opções de alerta do Chat"
L.RoleSpecAlert = "Exibir mensagem de alerta quando sua especialização de saque não corresponder à sua especialização atual ao entrar na raid"
L.CheckGear = "envia um mensagem de alerta quando o seu ilvl equipado for muito menor do que o ilvl nas bolsas(40+)"
L.WorldBossAlert = "Exibir mensagem de alerta quando um chefe do mundo possivelmente for atacado no seu reino por membros da sua guilda ou amigos (inaccurate if sender is CRZed)"
L.Area_SoundAlerts = "Opções de Som de Alerta"
L.LFDEnhance = "Tocar o som de TodosProntos para checagem de papéis & CB/LDG no canal de áudio principal(I.E. sons funcionam mesmo que os efeitos sonoros estejam desligados e são geralmente mais altos)"
L.WorldBossNearAlert = "Tocar o som de TodosProntos quando chefes do mundo perto de você que você precisa estiverem sendo atacados (Sobrepõe opção específica de chefe)"
L.AFKHealthWarning = "Tocar som de alerta quando você estiver perdendo vida enquanto estiver LDT"
L.Area_AutoLogging = "opções de relatórios automáticos"
L.AutologBosses = "Gravar automaticamente o relatório de encontro com os chefes utilizando o relatório de combate da Blizzard(Requer que seja usado /dbm pull antes do chefe <a href=\"http://www.warcraftlogs.com\">|cff3588ffwarcraftlogs.com|r</a> compatibilidade)"
L.AdvancedAutologBosses = "Gravar automaticamente o encontro com o chefe utilizando o Transcritor"
L.LogOnlyRaidBosses = "Só gravar encontros com chefes de raid (exclui Localizador de Raids/Grupos/Cenários)"
L.Area_3rdParty = "opções de add0ns de terceiros"
L.ShowBBOnCombatStart = "Fazer checagem de Buff com Big Brother no início do combate"
L.BigBrotherAnnounceToRaid = "Anunciar resultados do Big Brother para a raid"
L.Area_Invite = "Opções de convite"
L.AutoAcceptFriendInvite = "Aceitar convites de amigos automaticamente"
L.AutoAcceptGuildInvite = "Aceitar convites de membros da guilda automaticamente"
L.Area_Advanced = "Opções avançadas"
L.FakeBW = "Fingir ser BigWigs em checagens de versão ao invés de ser DBM ( útil para guildas que forçam o uso de BigWigs )"
L.PizzaTimer_Headline = 'Criar um "Cronógrafo para Pizza"'
L.PizzaTimer_Title = 'Nome (e.g. "Pizza!")'
L.PizzaTimer_Hours = "Horas"
L.PizzaTimer_Mins = "Min"
L.PizzaTimer_Secs = "Seg"
L.PizzaTimer_ButtonStart = "Iniciar cronógrafo"
L.PizzaTimer_BroadCast = "Transmitir para raid"
L.Panel_Profile = "Perfil"
L.Area_CreateProfile = "Criação de perfil"
L.EnterProfileName = "entre com o nome do perfil"
L.CreateProfile = "Criar perfil para opções do núcleo do BDM"
L.Area_ApplyProfile = "definir o perfil ativo para o núcleo do DBM"
L.SelectProfileToApply = "selecionar o perfil a aplicar"
L.Area_CopyProfile = "Copiar o perfil de opções do núcleo do DBM"
L.SelectProfileToCopy = "Escolha o perfil à ser copiado"
L.Area_DeleteProfile = "Remover o perfil de opções do núcleo do DBM"
L.SelectProfileToDelete = "Escolha o perfil à ser removido"
L.Area_DualProfile = "Opções de perfil da mod de chefes"
L.DualProfile = "Habilite suporte para outras mods de chefes de acordo com a especialização. (O gerenciamento de perfis de mods de chefes é feito da tela de mods de chefes carregados)"
L.Area_ModProfile = "Copia as preferencias da mod para outros personagens/ especializações ou deleta a customização efetuada"
L.ModAllReset = "reseta todas as opções da mod"
L.ModAllStatReset = "Reseta todos os stats da mod"
L.SelectModProfileCopy = "Copia todas as preferencias de"
L.SelectModProfileCopySound = "Copia apenas as preferencias sonoras de"
L.SelectModProfileDelete = "apaga as opções da mod de"
-- Misc
L.FontHeight = 16
|
require "/scripts/util.lua"
function update(_,_, shiftHeld)
self.containerId = config.getParameter("containerId")
self.swapItem = config.getParameter("swapItem")
if shiftHeld and self.containerId and world.entityExists(self.containerId) then
local status, result = pcall(eatItems)
end
if self.swapItem then player.setSwapSlotItem(self.swapItem)
else item.setCount(0) end
end
function eatItems()
local items = world.containerItems(self.containerId)
if items then
for offset, item in pairs(items) do
lootItem(item, offset)
end
player.cleanupItems()
end
end
function lootItem(item, offset)
player.giveItem(item)
world.containerConsumeAt(self.containerId, offset - 1, item.count)
end
|
-- LOCAL
local main = require(game.Nanoblox)
local TimeService = {
remotes = {
grabLocalDate = main.modules.Remote.new("grabLocalDate"),
grabLocalTime = main.modules.Remote.new("grabLocalTime"),
}
}
local Promise = main.modules.Promise
-- METHODS
function TimeService.grabLocalDateAsync(player, dateTime)
local newDateTime = dateTime or os.time()
local returnDate = os.date("*t", newDateTime)
local returnMonth = os.date("%B", newDateTime)
local promise = TimeService.remotes.grabLocalDate:invokeClient(player, newDateTime)
:timeout(3)
:andThen(function(clientDate, clientMonth)
returnDate = (typeof(clientDate) == "table" and clientDate) or returnDate
returnMonth = tostring(clientMonth)
end)
promise:await()
return returnDate, returnMonth
end
return TimeService
|
local LibEvent = LibStub:GetLibrary("LibEvent.7000")
local AFK = AFK
local DND = DND
local PVP = PVP
local LEVEL = LEVEL
local OFFLINE = FRIENDS_LIST_OFFLINE
local FACTION_HORDE = FACTION_HORDE
local FACTION_ALLIANCE = FACTION_ALLIANCE
local addon = TinyTooltip
local function strip(text)
return (text:gsub("%s+([|%x%s]+)<trim>", "%1"))
end
local function ColorBorder(tip, config, raw)
if (config.coloredBorder and addon.colorfunc[config.coloredBorder]) then
local r, g, b = addon.colorfunc[config.coloredBorder](raw)
LibEvent:trigger("tooltip.style.border.color", tip, r, g, b)
elseif (type(config.coloredBorder) == "string" and config.coloredBorder ~= "default") then
local r, g, b = addon:GetRGBColor(config.coloredBorder)
if (r and g and b) then
LibEvent:trigger("tooltip.style.border.color", tip, r, g, b)
end
else
LibEvent:trigger("tooltip.style.border.color", tip, unpack(addon.db.general.borderColor))
end
end
local function ColorBackground(tip, config, raw)
local bg = config.background
if not bg then return end
if (bg.colorfunc == "default" or bg.colorfunc == "" or bg.colorfunc == "inherit") then
local r, g, b, a = unpack(addon.db.general.background)
a = bg.alpha or a
LibEvent:trigger("tooltip.style.background", tip, r, g, b, a)
return
end
if (addon.colorfunc[bg.colorfunc]) then
local r, g, b = addon.colorfunc[bg.colorfunc](raw)
local a = bg.alpha or 0.8
LibEvent:trigger("tooltip.style.background", tip, r, g, b, a)
end
end
local function GrayForDead(tip, config, unit)
if (config.grayForDead and UnitIsDeadOrGhost(unit)) then
local line, text
LibEvent:trigger("tooltip.style.border.color", tip, 0.6, 0.6, 0.6)
LibEvent:trigger("tooltip.style.background", tip, 0.1, 0.1, 0.1)
for i = 1, tip:NumLines() do
line = _G[tip:GetName() .. "TextLeft" .. i]
text = (line:GetText() or ""):gsub("|cff%x%x%x%x%x%x", "|cffaaaaaa")
line:SetTextColor(0.7, 0.7, 0.7)
line:SetText(text)
end
end
end
local function ShowBigFactionIcon(tip, config, raw)
if (config.elements.factionBig and config.elements.factionBig.enable and tip.BigFactionIcon and (raw.factionGroup=="Alliance" or raw.factionGroup == "Horde")) then
tip.BigFactionIcon:Show()
tip.BigFactionIcon:SetTexture("Interface\\Timer\\".. raw.factionGroup .."-Logo")
tip:Show()
tip:SetMinimumWidth(tip:GetWidth() + 20)
end
end
local function PlayerCharacter(tip, unit, config, raw)
local data = addon:GetUnitData(unit, config.elements, raw)
addon:HideLines(tip, 2, 3)
addon:HideLine(tip, "^"..LEVEL)
addon:HideLine(tip, "^"..FACTION_ALLIANCE)
addon:HideLine(tip, "^"..FACTION_HORDE)
addon:HideLine(tip, "^"..PVP)
for i, v in ipairs(data) do
addon:GetLine(tip,i):SetText(strip(table.concat(v, " ")))
end
ColorBorder(tip, config, raw)
ColorBackground(tip, config, raw)
GrayForDead(tip, config, unit)
ShowBigFactionIcon(tip, config, raw)
end
local function NonPlayerCharacter(tip, unit, config, raw)
local levelLine = addon:FindLine(tip, "^"..LEVEL)
if (levelLine or tip:NumLines() > 1) then
local data = addon:GetUnitData(unit, config.elements, raw)
local titleLine = addon:GetNpcTitle(tip)
local increase = 0
for i, v in ipairs(data) do
if (i == 1) then
addon:GetLine(tip,i):SetText(table.concat(v, " "))
end
if (i == 2) then
if (config.elements.npcTitle.enable and titleLine) then
titleLine:SetText(addon:FormatData(titleLine:GetText(), config.elements.npcTitle, raw))
increase = 1
end
i = i + increase
addon:GetLine(tip,i):SetText(table.concat(v, " "))
elseif ( i > 2) then
i = i + increase
addon:GetLine(tip,i):SetText(table.concat(v, " "))
end
end
end
addon:HideLine(tip, "^"..LEVEL)
addon:HideLine(tip, "^"..PVP)
ColorBorder(tip, config, raw)
ColorBackground(tip, config, raw)
GrayForDead(tip, config, unit)
ShowBigFactionIcon(tip, config, raw)
end
LibEvent:attachTrigger("tooltip:unit", function(self, tip, unit)
local raw = addon:GetUnitInfo(unit)
if (UnitIsPlayer(unit)) then
PlayerCharacter(tip, unit, addon.db.unit.player, raw)
else
NonPlayerCharacter(tip, unit, addon.db.unit.npc, raw)
end
end)
addon.ColorUnitBorder = ColorBorder
addon.ColorUnitBackground = ColorBackground
|
local Proxy = module("vrp", "lib/Proxy")
local vRP = Proxy.getInterface("vRP")
async(function()
vRP.loadScript("vrp_drugstonpc", "server")
end)
|
--***********************************************************
--** ROBERT JOHNSON **
--***********************************************************
require "TimedActions/ISBaseTimedAction"
---@class ISCutHair : ISBaseTimedAction
ISCutHair = ISBaseTimedAction:derive("ISCutHair");
function ISCutHair:isValid()
return true;
end
function ISCutHair:update()
if self.item then
self.item:setJobDelta(self:getJobDelta());
end
end
function ISCutHair:start()
if self.item then
self.item:setJobType(getText("ContextMenu_CutHair"));
self.item:setJobDelta(0.0);
end
-- self:setActionAnim(CharacterActionAnims.Shave)
-- self:setOverrideHandModels("DisposableRazor", nil)
end
function ISCutHair:stop()
if self.item then
self.item:setJobDelta(0.0);
end
ISBaseTimedAction.stop(self);
end
function ISCutHair:perform()
if self.item then
self.item:setJobDelta(0.0);
end
local newHairStyle = getHairStylesInstance():FindMaleStyle(self.hairStyle)
if self.character:isFemale() then
newHairStyle = getHairStylesInstance():FindFemaleStyle(self.hairStyle)
end
-- if we're attaching our hair we need to set the non attached model, or if we untie, we reset our model
if newHairStyle:isAttachedHair() and not self.character:getHumanVisual():getNonAttachedHair() then
self.character:getHumanVisual():setNonAttachedHair(self.character:getHumanVisual():getHairModel());
end
if self.character:getHumanVisual():getNonAttachedHair() and not newHairStyle:isAttachedHair() then
self.character:getHumanVisual():setNonAttachedHair(nil);
end
self.character:getHumanVisual():setHairModel(self.hairStyle);
self.character:resetModel();
self.character:resetHairGrowingTime();
-- reduce hairgel for mohawk
if newHairStyle:getName():contains("Mohawk") and newHairStyle:getName() ~= "MohawkFlat" then
local hairgel = self.character:getInventory():getItemFromType("Hairgel", true, true);
if hairgel then
hairgel:Use();
end
end
triggerEvent("OnClothingUpdated", self.character)
-- needed to remove from queue / start next.
ISBaseTimedAction.perform(self);
end
function ISCutHair:new(character, hairStyle, item, time)
local o = {}
setmetatable(o, self)
self.__index = self
o.character = character;
o.hairStyle = hairStyle or "";
o.stopOnWalk = true;
o.stopOnRun = true;
o.item = item;
o.maxTime = time;
if o.character:isTimedActionInstant() then
o.maxTime = 1;
end
return o;
end
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:25' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
ZO_Banking_Shared = ZO_InitializingObject:Subclass()
function ZO_Banking_Shared:Initialize(control)
local bankFilterTargetDescriptor =
{
[BACKGROUND_LIST_FILTER_TARGET_BAG_SLOT] =
{
searchFilterList =
{
BACKGROUND_LIST_FILTER_TYPE_NAME,
},
primaryKeys =
{
BAG_BACKPACK,
BAG_BANK,
BAG_SUBSCRIBER_BANK,
}
},
}
TEXT_SEARCH_MANAGER:SetupContextTextSearch("playerBankTextSearch", bankFilterTargetDescriptor)
local houseBankFilterTargetDescriptor =
{
[BACKGROUND_LIST_FILTER_TARGET_BAG_SLOT] =
{
searchFilterList =
{
BACKGROUND_LIST_FILTER_TYPE_NAME,
},
primaryKeys = function()
local bankingBag = GetBankingBag()
if IsHouseBankBag(bankingBag) then
return { BAG_BACKPACK, bankingBag }
end
return {}
end,
},
}
TEXT_SEARCH_MANAGER:SetupContextTextSearch("houseBankTextSearch", houseBankFilterTargetDescriptor)
local guildBankFilterTargetDescriptor =
{
[BACKGROUND_LIST_FILTER_TARGET_BAG_SLOT] =
{
searchFilterList =
{
BACKGROUND_LIST_FILTER_TYPE_NAME,
},
primaryKeys =
{
BAG_BACKPACK,
BAG_GUILDBANK,
}
},
}
TEXT_SEARCH_MANAGER:SetupContextTextSearch("guildBankTextSearch", guildBankFilterTargetDescriptor)
end
ZO_BANKING_SHARED = ZO_Banking_Shared:New()
|
local guai = {
Attack1 = {
operation = {
[15] = {
move_speed = 4,
},
[20] = {
melee_attack = true
},
[38] = {
move_speed = 0
},
[40] = {
melee_attack = false
}
},
},
}
return guai
|
require "classes.constants.screen"
require "classes.list.model.DataAllTopicList"
Controller={}
function Controller:new(view, model)
local this = display.newGroup()
local public = this
local private = {}
local widget = require("widget")
local currentTopic
local currentScreen
function private.Controller()
view.onRowRender = public.onRowRender
view.onRowTouch = public.onRowTouch
view.onButtonBack = public.onButtonBack
private.showTopic()
Runtime:addEventListener("key", private.onBackHardwareKey)
end
function public.onRowRender(event)
local row = event.row
local rowTitle = display.newText(row, " " .. model.getData()[row.index].title, 0, 0, "CommodorePixelized", 15)
rowTitle.x = row.contentWidth*0.5
rowTitle.y = row.contentHeight*0.5
rowTitle.anchorX = 0.78
rowTitle:setFillColor(255/255, 255/255, 255/255)
if currentTopic.hasBackButton then
view.getButtonBack().alpha = 1
else
view.getButtonBack().alpha = 0
end
return true
end
function public.onRowTouch(event)
local row = event.target
if event.phase == "press" then
elseif event.phase == "swipeLeft" then
print("Swiped left.")
elseif event.phase == "swipeRight" then
print( "Swiped right." )
elseif event.phase == "tap" then
print("tap")
if currentTopic.isList then
timer.performWithDelay(50, function() private.showTopic(currentTopic[event.target.index]) end) --trick for avoid event propagation
return true
end
elseif event.phase == "release" then
print("release")
--print(event.target.index)
if currentTopic.isList then
timer.performWithDelay(50, function() private.showTopic(currentTopic[event.target.index]) end) --trick for avoid event propagation
return true
end
end
return true
end
function public.onButtonBack(event)
currentTopic = currentTopic.goBack()
view.getTableView():deleteAllRows()
model.setData(currentTopic)
for i = 1, #model.getData() do
local rowColor = {28/255, 142/255, 255/255, 0.2}
if i%2 == 0 then rowColor = {128/255, 255/255, 255/255, 0} end
view.getTableView():insertRow({
isCategory = false,
rowHeight = 49,
rowColor = {
default = rowColor,
over = {28/255, 142/255, 255/255, 0.5},
},
lineColor = {220/255, 220/255, 220/255,0},
})
end
end
function private.showTopic(clickedTarget)
if clickedTarget ~= nil then
local goBack =currentTopic.goCurrent
currentTopic = clickedTarget.execute()
view.getTableView():deleteAllRows()
if currentTopic.isList then
model.setData(currentTopic)
goBack=nil
else
currentTopic:addEventListener("touch", function() return true end)
currentTopic:addEventListener("tap", function() return true end)
currentScreen:insert(currentTopic)
view.getTableView():deleteAllRows()
view.getTableView().alpha=0
model.setData(currentTopic)
currentTopic.hasBackButton = true
currentTopic.goBack = function()
view.getTableView().alpha=1
currentScreen:remove(currentTopic)
currentTopic:destroy()
currentTopic = nil
return goBack()--> currentTopic.goCurrent()-->DataGettingStarted().goCurrent()-->DataGettingStartedList:new()
end
view:toFront()
end
else
currentTopic = DataAllTopicList:new()
view.getButtonBack().alpha = 0
if currentTopic.isList then
view.getTableView():deleteAllRows()
model.setData(currentTopic)
end
end
for i = 1, #model.getData() do
local rowColor = {28/255, 142/255, 255/255, 0.2}
if i%2 == 0 then rowColor = {128/255, 255/255, 255/255, 0} end
view.getTableView():insertRow({
isCategory = false,
rowHeight = 49,
rowColor = {
default = rowColor,
over = {28/255, 142/255, 255/255, 0.5},
},
lineColor = {220/255, 220/255, 220/255,0},
})
end
return true
end
function public.setCurrentScreen(newScreen)
currentScreen = newScreen
end
function private.onBackHardwareKey(event)
if event.phase == "up" and event.keyName == "back" then
if currentTopic.hasBackButton then
public.onButtonBack(event)
return true
end
end
end
function public:destroy()
this:removeSelf()
this = nil
end
private.Controller()
return this
end
return Controller
|
local maxResults = 200
local module = {}
local TweenService = game:GetService("TweenService")
local tweenInfo = TweenInfo.new(0.3)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local AuthorDirectory = require(ReplicatedStorage.AuthorDirectory)
local List = require(ReplicatedStorage.Utilities.List)
local ObjectList = require(ReplicatedStorage.Utilities.ObjectList)
local Books = require(ReplicatedStorage.BooksClient)
local books = Books:GetBooks()
local gui = ReplicatedStorage.Guis.BookSearch
gui.Enabled = false
local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
gui.Parent = localPlayer.PlayerGui
local searchFrame = gui.Search
local resultsFrame = searchFrame.Results
local results -- list of book
local entry = resultsFrame.Entry
entry.Parent = nil
local entries = {entry}
for i = 2, maxResults do
entries[i] = entry:Clone()
entries[i].LayoutOrder = i
end
local shrunk = false
local entrySizeY = entry.Size.Y.Offset
local origSize = resultsFrame.Size
local shrinkSize = UDim2.new(resultsFrame.Size.X, UDim.new(0, entrySizeY))
local origPos = resultsFrame.Position
local shrinkPos = UDim2.new(resultsFrame.Position.X, resultsFrame.Position.Y)
local tween
local function newTween(props, instant)
if tween then tween:Cancel() end
if instant then
for k, v in pairs(props) do
resultsFrame[k] = v
end
else
tween = TweenService:Create(resultsFrame, tweenInfo, props)
tween:Play()
end
end
local function shrink(toIndex)
shrunk = true
local targetY = (toIndex - 1) * (entrySizeY + 1) - 1 -- +1 for padding, -1 because first entry doesn't have padding
newTween({
Position = shrinkPos,
Size = shrinkSize,
CanvasPosition = Vector2.new(0, targetY),
})
coroutine.wrap(function() -- CanvasPosition doesn't end up in correct spot, so fix it when the tween finishes:
if tween.Completed:Wait() == Enum.PlaybackState.Completed then
resultsFrame.CanvasPosition = Vector2.new(0, targetY)
end
end)
end
local function expand(instant)
shrunk = false
newTween({
Position = origPos,
Size = origSize,
}, instant)
end
-- todo pathfind functions -> dif module
local PathfindingService = game:GetService("PathfindingService")
local reachedDist = 5
local recalcDist = 8
local nodeExtraHeight = Vector3.new(0, 2, 0)
--local nodeTweenHeight = 0.5 -- todo implement
--local nodeTweenTime = 1
local RunService = game:GetService("RunService")
local nodeFolder = Instance.new("Folder")
nodeFolder.Name = "Pathfind Nodes"
nodeFolder.Parent = workspace
local node = Instance.new("Part")
node.Size = Vector3.new(1, 1, 1)
node.TopSurface = Enum.SurfaceType.Smooth
node.BottomSurface = Enum.SurfaceType.Smooth
node.Shape = Enum.PartType.Ball
node.Anchored = true
node.CanCollide = false
node.Material = Enum.Material.SmoothPlastic
node.BrickColor = BrickColor.Green()
local nodes = ObjectList.new(function() return node:Clone() end, 200, function(n) n.Parent = nil end)
local nodeIndex = 1
local scanning = false
local function setNextNodeIndex(index)
for i = nodeIndex, index - 1 do
nodes:Get(i).Parent = nil
end
nodeIndex = index
end
local highlightedBook
local boxTweenInfo = TweenInfo.new(0.7)
local boxTween
local boxStartColor, boxEndColor = Color3.new(1, 1, 1), Color3.fromRGB(170, 120, 255)
local boxHandles = ObjectList.new(function()
local boxHandle = Instance.new("BoxHandleAdornment")
boxHandle.Transparency = 0.5
boxHandle.AlwaysOnTop = false
return boxHandle
end):SetAdaptFunc(function(boxHandle, model)
boxHandle.Color3 = boxStartColor
boxHandle.Size = model.Size + Vector3.new(0, 0, 0.25)
if boxTween then boxTween:Cancel() boxTween = nil end
boxHandle.Adornee = model
boxHandle.Parent = model
end)
local function highlightBook(book)
if highlightedBook == book then return end
boxHandles:AdaptToList(book.Models)
coroutine.wrap(function()
local nextColor = boxEndColor
while boxHandles:Count() > 0 do
boxHandles:ForEach(function(i, boxHandle)
local tween = TweenService:Create(boxHandle, boxTweenInfo, {Color3 = nextColor})
if i == 1 then boxTween = tween end
tween:Play()
end)
if boxTween.Completed:Wait() == Enum.PlaybackState.Cancelled then return end
nextColor = nextColor == boxEndColor and boxStartColor or boxEndColor
end
end)()
highlightedBook = book
end
local function unhighlightBook()
if boxTween then boxTween:Cancel() end
boxHandles:EmptyList()
highlightedBook = nil
end
local function clearPathfind()
unhighlightBook()
for i = nodeIndex, nodes:Count() do
nodes:Get(i).Parent = nil
end
nodeIndex = nodes:Count() + 1
end
local pathfindTarget, pathfindTargetBook
local function stopScanning()
if scanning then
scanning:Disconnect()
scanning = false
pathfindTarget, pathfindTargetBook = nil, nil
end
end
local pathfindTo
local function repathfind()
local targetBook = pathfindTargetBook
stopScanning()
pathfindTo(targetBook)
end
local function startScanning()
if scanning then return end
scanning = RunService.Heartbeat:Connect(function()
local root = localPlayer.Character and localPlayer.Character:FindFirstChild("HumanoidRootPart")
if not root then return end
local node1, node2 = nodes:Get(nodeIndex), nodes:Get(nodeIndex + 1)
if node1 then
local m1 = (node1.Position - root.Position).Magnitude
if m1 <= reachedDist or (node2 and (node2.Position - root.Position).Magnitude <= m1) then
setNextNodeIndex(nodeIndex + 1)
elseif m1 >= recalcDist then
repathfind()
end
elseif (pathfindTarget.Position - root.Position).Magnitude >= recalcDist then
repathfind()
end
end)
end
local pathfindTargetFromBookModel do -- raycasting setup
local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Whitelist
local list = {}
local function search(folder)
for _, c in ipairs(folder:GetDescendants()) do
if c.ClassName == "Model" and c.Name == "Floor" then
list[#list + 1] = c
end
end
end
for _, obj in ipairs(workspace:GetChildren()) do
if obj.Name:find("Hall") then
search(obj)
end
end
raycastParams.FilterDescendantsInstances = list
pathfindTargetFromBookModel = function(bookModel)
local result = workspace:Raycast(bookModel.Position, Vector3.new(0, -15, 0), raycastParams)
return result and result.Position + Vector3.new(0, 2, 0) or bookModel.Position
end
end
local path = PathfindingService:CreatePath()
local function acceptableWaypoints(waypoints, targetPos)
local n = waypoints and #waypoints
return n and n > 0 and waypoints[n].Position.Y <= targetPos.Y + 1 -- if position.Y > targetPos.Y then pathfinding went to the floor above
end
local cfTranslationAttempt, numCFTranslationAttempts do
local key = {"RightVector", "RightVector", "UpVector", "LookVector", "LookVector"}
local dist = 4
local multiplier = {2, dist, -dist, -dist, dist}
numCFTranslationAttempts = #key
-- RightVector * 2 will work for books whose spine faces outward
-- UpVector * -2 will work for books whose front cover faces outward
-- LookVector * +/-2 will work for books that are lying down
cfTranslationAttempt = function(cf, i)
return cf[key[i]] * multiplier[i]
end
end
local function getBookModelForPathfinding(book, root)
-- Choose model nearest to player character position
local models = book.Models
local best = models[1]
if #models > 1 then
local bestDist = (best.Position - root.Position).Magnitude
for i = 2, #models do
local model = models[i]
local dist = (model.Position - root.Position).Magnitude
if dist < bestDist then
bestDist = dist
best = models[i]
end
end
end
return best
end
pathfindTo = function(book)
pathfindTargetBook = book
highlightBook(book)
local root = localPlayer.Character and localPlayer.Character:FindFirstChild("HumanoidRootPart")
if not root then return end
local bookModel = getBookModelForPathfinding(book, root)
pathfindTarget = bookModel
local targetPos = pathfindTargetFromBookModel(bookModel)
local waypoints
local function try(pos)
path:ComputeAsync(root.Position, pos)
waypoints = path:GetWaypoints()
return acceptableWaypoints(waypoints, targetPos)
end
local success = try(targetPos)
if not success then -- try to get a lower down position away from the shelf
local cf = bookModel.CFrame
local down = targetPos - Vector3.new(0, 3.9, 0)
for i = 1, numCFTranslationAttempts do
local translation = cfTranslationAttempt(cf, i)
success = math.abs(translation.Y) < 0.2 and try(down + translation)
if success then break end
end
end
if success then
nodes:AdaptToList(waypoints, function(node, waypoint)
node.Position = waypoint.Position + nodeExtraHeight
node.Parent = nodeFolder
end)
nodeIndex = 1
startScanning()
else
print("Failed to find a path to", bookModel:GetFullName())
end
end
for i, entry in ipairs(entries) do
entry.Activated:Connect(function()
if shrunk then
clearPathfind()
expand()
return
end
local book = results[i]
if not book then return end
pathfindTo(book)
shrink(i)
end)
end
local function shouldKeepResult(book)
return not table.find(book.Genres, "Secret") -- todo make customizable without changing this script
end
local desiredResults = 200
local function titleSearch(value)
value = value:lower()
local results = {}
for _, book in ipairs(books) do
if Books:BookTitleContains(book, value) then
if shouldKeepResult(book) then
results[#results + 1] = book
end
end
end
return results
end
local function newAuthorResults()
local self = {}
function self:ConsiderAdd(book)
if self[book] or not shouldKeepResult(book) then return end
self[#self + 1] = book
self[book] = true
end
return self
end
local function extendResultsAuthorIdsSearch(results, authorIds)
-- results:AuthorResults
for _, book in ipairs(books) do
local lookup = Books:GetAuthorIdLookup(book)
for _, authorId in ipairs(authorIds) do
if lookup[authorId] then
results:ConsiderAdd(book)
break
end
end
end
end
local function authorSearch(value)
--[[
If 'value' refers to a player in the server, use their UserId, otherwise find all UserIds that this may refer to
Go through all books and see if any of the UserIds are found
After this, if insufficient results, see if any partial matches for 'value' exist in any book
After this, if insufficient results, see if any partial matches for past usernames turn up any more ids.
]]
value = value:lower()
local results = newAuthorResults()
local authorIds
local authorId = tonumber(value)
if not authorId then -- see if the specified username is a player in the server
for _, player in ipairs(Players:GetPlayers()) do
if player.Name:lower() == value then
authorIds = {player.UserId}
break
end
end
end
if authorId then
authorIds = {authorId}
else
authorIds = AuthorDirectory.ExactMatches(value)
end
if authorIds and #authorIds > 0 then
extendResultsAuthorIdsSearch(results, authorIds)
end
if #results >= desiredResults then return results end
for _, book in ipairs(books) do
if Books:AuthorNamesContainFullWord(book, value) then
results:ConsiderAdd(book)
end
end
if #results >= desiredResults then return results end
for _, book in ipairs(books) do
if Books:AuthorNamesContain(book, value) then
results:ConsiderAdd(book)
end
end
if #results >= desiredResults then return results end
local partialAuthorIds = AuthorDirectory.PartialMatches(authorId or value)
if partialAuthorIds then
for i = #partialAuthorIds, 1, -1 do
if authorIds and table.find(authorIds, partialAuthorIds[i]) then
table.remove(partialAuthorIds, i)
end
end
if #partialAuthorIds > 0 then
extendResultsAuthorIdsSearch(results, partialAuthorIds)
end
end
return results
end
local numBooks = #books
local function getRandomResults()
if numBooks <= desiredResults * 2 then -- easier to shuffle a larger list than to try to randomly select that many unique elements
return List.Shuffle(List.Clone(books))
else
local results = {}
local selected = {}
for i = 1, desiredResults do
for attempts = 1, 3 do
local new = math.random(1, numBooks)
if not selected[new] then
selected[new] = true
results[#results + 1] = books[new]
break
end
end
end
return results
end
end
local box = searchFrame.TextBox
local search = titleSearch
local title = searchFrame.SortBy.Title
local author = searchFrame.SortBy.Author
local function showResults(results)
local num = math.min(#results, desiredResults)
for i = 1, num do
local entry = entries[i]
local book = results[i]
entry.Text = ("%s by %s%s"):format(book.Title, book.AuthorLine, book.Genre and (" (%s)"):format(book.Genre) or "")
entry.Parent = resultsFrame
end
resultsFrame.CanvasSize = UDim2.new(0, 0, 0, entry.Size.Y.Offset * num)
for i = num + 1, #entries do
entries[i].Parent = nil
end
end
local showingRandom = false
local function performSearch()
if shrunk then
expand()
end
if box.Text == "" then
if not showingRandom then
showingRandom = true
results = getRandomResults()
end
else
results = search(box.Text)
showingRandom = false
end
showResults(results)
end
local lastFocusLost = 0
box.FocusLost:Connect(function()
lastFocusLost = os.clock()
end)
local function highlight(obj)
obj.TextStrokeTransparency = 0
obj.TextTransparency = 0
end
local function unhighlight(obj)
obj.TextStrokeTransparency = 1
obj.TextTransparency = 0.25
end
local prevButton
local function setSearchMode(mode)
search = mode.search
if prevButton then
unhighlight(prevButton)
end
prevButton = mode.button
highlight(prevButton)
box.PlaceholderText = mode.placeholderText
end
local function activateSearchButton(mode)
setSearchMode(mode)
if os.clock() - lastFocusLost < 0.1 then
box:CaptureFocus()
end
performSearch()
end
local titleSearchMode = {
search = titleSearch,
button = title,
placeholderText = "Book title",
}
local authorSearchMode = {
search = authorSearch,
button = author,
placeholderText = "Author username or id",
}
title.Activated:Connect(function()
activateSearchButton(titleSearchMode)
end)
author.Activated:Connect(function()
activateSearchButton(authorSearchMode)
end)
activateSearchButton(titleSearchMode)
box:GetPropertyChangedSignal("Text"):Connect(performSearch)
module.CloseOnCatchClick = false
local open = false
local hidden = false
function module:Open()
open = true
if not hidden then
gui.Enabled = true
box:CaptureFocus()
end
end
function module:Close()
open = false
clearPathfind()
stopScanning()
gui.Enabled = false
if shrunk then
expand(true)
end
end
function module:Hide()
gui.Enabled = false
end
function module:Unhide()
if open then
gui.Enabled = true
end
end
localPlayer.CharacterAdded:Connect(function()
if gui.Enabled then
module:Close()
end
end)
return module
|
function applyMods()
--Car Icon Start
disabledIconDFF = engineLoadDFF("mods/disabledicon.dff", 1314)
engineReplaceModel(disabledIconDFF, 1314)
disabledIconTXD = engineLoadTXD("mods/icons.txd")
engineImportTXD(disabledIconTXD, 1314)
--Car Icon End
--Fix interior ID 24 Start
intCOL = engineLoadCOL("mods/fixes/interior24.col")
engineReplaceCOL(intCOL, 14776)
--Fix interior ID 24 End
--[[
--SEB Skin Start
skinDFF = engineLoadDFF("mods/skins/seb.dff", 287)
engineReplaceModel(skinDFF, 287)
skinTXD = engineLoadTXD("mods/skins/seb.txd")
engineImportTXD(skinTXD, 287)
--SEB Skin End
]]
--HSU Mod Start
hsuDFF = engineLoadDFF("mods/hsu.dff", 494)
engineReplaceModel(hsuDFF, 494)
hsuTXD = engineLoadTXD("mods/hsu.txd")
engineImportTXD(hsuTXD, 494)
hsuDFF2 = engineLoadDFF("mods/hsu.dff", 502)
engineReplaceModel(hsuDFF2, 502)
hsuTXD2 = engineLoadTXD("mods/hsu.txd")
engineImportTXD(hsuTXD2, 502)
--HSU Mod End
--Leviathan Mod Start
leviDFF = engineLoadDFF("mods/levi.dff", 417)
engineReplaceModel(leviDFF, 417)
leviTXD = engineLoadTXD("mods/levi.txd")
engineImportTXD(leviTXD, 417)
--Leviathan Mod End
--Raindance
rainDFF = engineLoadDFF("mods/raindanc.dff", 563)
engineReplaceModel(rainDFF, 563)
rainTXD = engineLoadTXD("mods/raindanc.txd")
engineImportTXD(rainTXD, 563)
engineReplaceModel(engineLoadDFF("mods/vehicles/patriot.dff", 470), 470)
engineImportTXD(engineLoadTXD("mods/vehicles/patriot.txd"), 470)
-- DFT-30 mod by Adams (He has given the permission - anumaz, 13/06/2014)
engineReplaceModel(engineLoadDFF("mods/vehicles/dft30.dff", 578), 578)
local dftTXD = engineLoadTXD("mods/vehicles/dft30.txd")
engineImportTXD(dftTXD, 578)
engineReplaceModel(engineLoadDFF("mods/vehicles/trailer.dff", 611 ), 611)
local trailerTXD = engineLoadTXD("mods/vehicles/trailer.txd")
engineImportTXD(trailerTXD, 611)
engineReplaceModel(engineLoadDFF("mods/vehicles/fbitruck.dff", 528), 528)
engineImportTXD(engineLoadTXD("mods/vehicles/fbitruck.txd"), 528)
engineReplaceModel(engineLoadDFF("mods/vehicles/firetruck.dff", 407), 407)
engineImportTXD(engineLoadTXD("mods/vehicles/firetruck.txd"), 407)
-- Enterable Mr. Whoopie
engineImportTXD(engineLoadTXD("mods/vehicles/mrwhoop.txd"), 423)
engineReplaceModel(engineLoadDFF("mods/vehicles/mrwhoop.dff"), 423)
-- Enterable Hotdog stand
engineImportTXD(engineLoadTXD("mods/vehicles/hotdog.txd"), 588)
engineReplaceModel(engineLoadDFF("mods/vehicles/hotdog.dff"), 588)
--Factory object
engineReplaceModel(engineLoadDFF("mods/factory.dff", 14584), 14584)
engineReplaceCOL(engineLoadCOL("mods/factory.col"), 14584)
--[[
engineReplaceModel(engineLoadDFF("mods/maps/lsmall_shop01.dff", 6048), 6048)
engineReplaceModel(engineLoadDFF("mods/maps/lsmall_window01.dff", 6048), 6048)
engineReplaceModel(engineLoadDFF("mods/maps/mallb_laW02.dff", 6048), 6048)
engineImportTXD(engineLoadTXD("mods/maps/lsmall_shops.txd"), 6048)
]]
-- Bus stops
busStop = engineLoadTXD("ls/bustopm.txd")
engineImportTXD(busStop, 1257)
-- Retextures
a = engineLoadTXD ( "ls/barrio1_lae.txd" )
engineImportTXD ( a, 5489 )
b = engineLoadTXD ( "ls/idlewood6_detail.txd" )
engineImportTXD ( b, 5489 )
--[[
local sniper1 = engineLoadDFF("mods/weapons/sniper.dff", 358)
engineReplaceModel(sniper1, 358)
local sniper2 = engineLoadTXD("mods/weapons/sniper.txd")
engineImportTXD(sniper2, 358)
]]
--Picture Frames Collisions (Exciter)
frameCol = engineLoadCOL("mods/cols/frame_4.col")
engineReplaceCOL(frameCol, 2287)
--[[
--Special skin for admin and supporters on-duty / MAXIME
local admin1 = engineLoadDFF("mods/skins/admin.dff", 90)
engineReplaceModel(admin1, 90)
local admin2 = engineLoadTXD("mods/skins/admin.txd")
engineImportTXD(admin2, 90)
]]
-- Verona Mall
engineImportTXD(engineLoadTXD("verona/lsmall_shops.txd", 2967), 2967)
engineReplaceModel(engineLoadDFF("verona/lsmall_shop01.dff", 2967), 2967)
engineReplaceCOL(engineLoadCOL("verona/lsmall_shop01.col"), 2967)
engineImportTXD(engineLoadTXD("verona/mall_law.txd", 2036), 2036)
engineReplaceModel(engineLoadDFF("verona/mallb_laW02.dff", 2036), 2036)
engineReplaceCOL(engineLoadCOL("verona/mallb_laW02.col"), 2036)
engineSetModelLODDistance(2036, 300)
engineSetModelLODDistance(2967, 300)
-------------
-- Objects --
-------------
local txd = engineLoadTXD('mods/objects/all_walls.txd',true)
engineImportTXD(txd, 1008)
engineImportTXD(txd, 1009)
engineImportTXD(txd, 1010)
engineImportTXD(txd, 3060)
engineReplaceModel(engineLoadDFF("mods/objects/wall017.dff", 1008), 1008) -- Custom Wall
engineReplaceCOL(engineLoadCOL("mods/objects/wall017.col"), 1008)
engineReplaceModel(engineLoadDFF("mods/objects/wall045.dff", 1009), 1009) -- Custom Doorway
engineReplaceCOL(engineLoadCOL("mods/objects/wall045.col"), 1009)
engineReplaceModel(engineLoadDFF("mods/objects/wall063.dff", 1010), 1010) -- Custom Window
engineReplaceCOL(engineLoadCOL("mods/objects/wall063.col"), 1010)
engineReplaceModel(engineLoadDFF("mods/objects/wall101.dff", 3060), 3060) -- Custom Large Wall
engineReplaceCOL(engineLoadCOL("mods/objects/wall101.col"), 3060)
-----------
-- Items --
-----------
--iFruit by Maxime
--Cola Bottle (Exciter)
local txd = engineLoadTXD("items/cola.txd")
engineImportTXD(txd,2880)
local dff = engineLoadDFF("items/cola.dff",2880)
engineReplaceModel(dff,2880)
local txd = engineLoadTXD("items/Ciggy1.txd")
engineImportTXD(txd,3027)
local dff = engineLoadDFF("items/Ciggy1.dff",3027)
engineReplaceModel(dff,3027)
local txd = engineLoadTXD("items/parapakx.txd")
engineImportTXD(txd,3026)
local dff = engineLoadDFF("items/para_pack.dff",3026)
engineReplaceModel(dff,3026)
local dff = engineLoadDFF("items/safe.dff",2332)
engineReplaceModel(dff,2332)
--Santa Hat (Chaos)
local santaSkin = engineLoadTXD("items/SantaHats.txd")
engineImportTXD(santaSkin, 954)
local santaSkin = engineLoadDFF("items/SantaHats.dff")
engineReplaceModel(santaSkin, 954)
-- Flashlight
engineImportTXD( engineLoadTXD( "items/flashlight.txd" ), 15060 ) -- Replacing interior building shadow
engineReplaceModel ( engineLoadDFF( "items/flashlight.dff", 0 ), 15060,true)
-- Enterable Ambulance + Texturable
engineImportTXD( engineLoadTXD( "mods/vehicles/ambulance.txd" ), 416 )
engineReplaceModel(engineLoadDFF("mods/vehicles/ambulance.dff", 416), 416)
----------------------------------
-- Chistmas Only Mods (Exciter) --
----------------------------------
local txd = engineLoadTXD("xmas/artict1.txd") --Trailer: artict1
engineImportTXD(txd,591)
local dff = engineLoadDFF("xmas/artict1.dff",591) --Trailer: artict1
engineReplaceModel(dff,591)
local txd = engineLoadTXD("xmas/rdtrain.txd") --Roadtrain
engineImportTXD(txd,515)
local dff = engineLoadDFF("xmas/rdtrain.dff",515) --Roadtrain
engineReplaceModel(dff,515)
--Santa
--[[local santaSkin = engineLoadTXD("xmas/santa.txd")
engineImportTXD(santaSkin, 245)
local santaSkin = engineLoadDFF("xmas/santa.dff")
engineReplaceModel(santaSkin, 245)]]
end
addEventHandler ( "onClientResourceStart", resourceRoot, function()
applyMods()
setTimer (applyMods, 1000, 1)
end )
local skins = {1, 2 ,7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62 ,63, 117, 118}
function getModdedSkins()
return skins or {}
end
|
ac.FogAlgorithm = __enum({ cpp = 'fog_algorithm' }, {
Original = 0,
New = 1
})
ac.ShadowsState = __enum({ cpp = 'shadows_state' }, {
Off = 0,
On = 1,
EverythingShadowed = 2
})
ac.TextureState = __enum({ cpp = 'async_texture_state' }, {
Empty = 0,
Loading = 1,
Failed = 2,
Ready = 3
})
ac.CameraMode = __enum({ cpp = 'CameraMode' }, {
Cockpit = 0, -- first person view
Car = 1, -- F6 camera
Drivable = 2, -- chase/bonnet/bumper/dash cameras
Track = 3, -- replay camera
Helicopter = 4, -- moving replay camera
OnBoardFree = 5, -- F5 camera
Free = 6, -- F7 camera
Deprecated = 7,
ImageGeneratorCamera = 8,
Start = 9, -- starting camera
})
ac.DrivableCamera = __enum({ cpp = 'DrivableCamera' }, {
Chase = 0,
Chase2 = 1,
Bonnet = 2,
Bumper = 3,
Dash = 4,
})
ac.LightsDebugMode = __enum({ cpp = 'lights_debug_mode' }, {
Off = 0,
Outline = 1,
BoundingBox = 2,
BoundingSphere = 4,
Text = 8,
})
ac.VAODebugMode = __enum({ cpp = 'vao_mode' }, {
Active = 1,
Inactive = 3,
VAOOnly = 4,
ShowNormals = 5
})
ac.Wheel = __enum({ cpp = 'ac_wheel' }, {
FrontLeft = 1,
FrontRight = 2,
RearLeft = 4,
RearRight = 8,
Front = 3,
Rear = 12,
Left = 5,
Right = 10,
All = 15
})
ac.MirrorPieceRole = __enum({ cpp = 'ac_mirrorpiece_role' }, {
None = 0,
Top = 1,
Left = 2,
Right = 4
})
ac.MirrorPieceFlip = __enum({ underlying = 'int' }, {
None = 0,
Horizontal = 1,
Vertical = 2,
Both = 3
})
ac.MirrorMonitorType = __enum({ underlying = 'int' }, {
TN = 0, -- oldschool displays with a lot of color distortion
VA = 2, -- medium tier, less color distortion
IPS = 1, -- almost no color distortion
})
ac.WeatherType = __enum({ cpp = 'weather_type', underlying = 'char' }, {
LightThunderstorm = 0,
Thunderstorm = 1,
HeavyThunderstorm = 2,
LightDrizzle = 3,
Drizzle = 4,
HeavyDrizzle = 5,
LightRain = 6,
Rain = 7,
HeavyRain = 8,
LightSnow = 9,
Snow = 10,
HeavySnow = 11,
LightSleet = 12,
Sleet = 13,
HeavySleet = 14,
Clear = 15,
FewClouds = 16,
ScatteredClouds = 17,
BrokenClouds = 18,
OvercastClouds = 19,
Fog = 20,
Mist = 21,
Smoke = 22,
Haze = 23,
Sand = 24,
Dust = 25,
Squalls = 26,
Tornado = 27,
Hurricane = 28,
Cold = 29,
Hot = 30,
Windy = 31,
Hail = 32
})
ac.TonemapFunction = __enum({ cpp = 'tonemap_function' }, {
Linear = 0, -- simple linear mapping.
LinearClamped = 1, -- linear mapping (LDR clamp)
Sensitometric = 2, -- simple simulation of response of film, CCD, etc., recommended
Reinhard = 3, -- Reinhard
ReinhardLum = 4, -- saturation retention type Reinhard tone map function
Log = 5, -- tone map function for the logarithmic space
LogLum = 6 -- saturation retention type logarithmic space tone map function
})
ac.FolderID = __enum({ cpp = 'known_dir' }, {
AppData = 0, -- …/AppData
Documents = 1, -- …/Documents
Root = 4, -- …/SteamApps/common/assettocorsa
Cfg = 5, -- …/Documents/Assetto Corsa/cfg
Setups = 6, -- @hidden
Logs = 7, -- …/Documents/Assetto Corsa/logs
Screenshots = 8, -- …/Documents/Assetto Corsa/screens
Replays = 9, -- …/Documents/Assetto Corsa/replay
ReplaysTemp = 10, -- …/Documents/Assetto Corsa/replay/temp
UserSetups = 11, -- …/Documents/Assetto Corsa/setups
PPFilters = 12, -- …/SteamApps/common/assettocorsa/system/cfg/ppfilters
ContentCars = 13, -- …/SteamApps/common/assettocorsa/content/cars
ContentDrivers = 14, -- …/SteamApps/common/assettocorsa/content/drivers
ContentTracks = 15, -- …/SteamApps/common/assettocorsa/content/tracks
ExtRoot = 16, -- …/SteamApps/common/assettocorsa/extension
ExtCfgSys = 17, -- …/SteamApps/common/assettocorsa/extension/config
ExtCfgUser = 18, -- …/Documents/Assetto Corsa/cfg/extension
ExtTextures = 21, -- …/SteamApps/common/assettocorsa/extension/textures
ACApps = 23, -- …/SteamApps/common/assettocorsa/apps
ACAppsPython = 24, -- …/SteamApps/common/assettocorsa/apps/python
ExtCfgState = 25, -- …/Documents/Assetto Corsa/cfg/extension/state (changing configs there does not trigger any live reloads)
ContentFonts = 26, -- …/SteamApps/common/assettocorsa/content/fonts
RaceResults = 27, -- …/Documents/Assetto Corsa/out
AppDataLocal = 28, -- …/AppData/Local
ExtFonts = 29, -- …/SteamApps/common/assettocorsa/extension/fonts
ACDocuments = 31 -- …/Documents/Assetto Cors
})
ac.FolderId = ac.FolderID
ac.HolidayType = __enum({ cpp = 'holiday_type' }, {
None = 0,
NewYear = 1,
Christmas = 2,
VictoryDay = 3,
IndependenceDay = 4,
Halloween = 5,
JapanFestival = 6,
ChineseNewYear = 7,
EidAlAdha = 8,
GuyFawkesNight = 9
})
ac.SkyRegion = __enum({ cpp = 'sky_side', passThrough = true }, {
None = 0,
Sun = 1,
Opposite = 2,
All = 3
})
ac.AudioChannel = __enum({ override = 'ac.getAudioVolume/key', underlying = 'string' }, {
Main = 'main',
Rain = 'rain',
})
---At the moment, most of those flag types are never shown, but more flags will be added later.
ac.FlagType = __enum({ cpp = 'flag_type' }, {
None = 0, -- no flag, works
Start = 1, -- works in race, practice or hotlap modes
Caution = 2, -- yellow flag, works
Slippery = 3, -- does not work yet
PitLaneClosed = 4, -- does not work yet
Stop = 5, -- black flag, works
SlowVehicle = 6, -- does not work yet
Ambulance = 7, -- does not work yet
ReturnToPits = 8, -- penalty flag, works
MechanicalFailure = 9, -- does not work yet
Unsportsmanlike = 10, -- does not work yet
StopCancel = 11, -- does not work yet
FasterCar = 12, -- blue flag, works
Finished = 13, -- checkered flag, works
OneLapLeft = 14, -- white flag, works
})
---More types might be added later, or at least a `CustomMode` type.
ac.SessionType = __enum({ cpp = 'SessionType' }, {
Undefined = 0,
Practice = 1,
Qualify = 2,
Race = 3,
Hotlap = 4,
TimeAttack = 5,
Drift = 6,
Drag = 7,
})
|
data:extend({
{
type = "recipe",
name = "radioisotope-thermoelectric-generator",
energy_required = 150,
enabled = "false",
ingredients =
{
{"uranium-fuel-cell", 100},
{"substation", 10},
{"rocket-control-unit", 100},
{"steel-plate", 100},
},
result = "radioisotope-thermoelectric-generator",
category = "satellite-crafting",
}
})
|
local t = {something="hello", somelist={ "A", "B", "C" }, anotherlist={1,2,"z"}}
--for k, v in pairs(t) do
-- print("key: " .. k .. " value: ")
-- pprint(v)
--end
--print("calling serve2 with table t")
serve2("list.po2", t)
|
Config = {}
Config.DrawDistance = 100.0
Config.MarkerColor = { r = 102, g = 0, b = 102 }
Config.NPCJobEarnings = {min = 200, max = 300}
Config.EnablePlayerManagement = true
local second = 1000
local minute = 60 * second
-- How much time before auto respawn at hospital
Config.RespawnDelayAfterRPDeath = 5 * minute
-- How much time before a menu opens to ask the player if he wants to respawn at hospital now
-- The player is not obliged to select YES, but he will be auto respawn
-- at the end of RespawnDelayAfterRPDeath just above.
Config.RespawnToHospitalMenuTimer = true
Config.MenuRespawnToHospitalDelay = 5 * minute
Config.EnableSocietyOwnedVehicles = false
Config.RemoveWeaponsAfterRPDeath = true
Config.RemoveCashAfterRPDeath = true
Config.RemoveItemsAfterRPDeath = true
-- Will display a timer that shows RespawnDelayAfterRPDeath time remaining
Config.ShowDeathTimer = true
-- Will allow to respawn at any time, don't use RespawnToHospitalMenuTimer at the same time !
Config.EarlyRespawn = false
-- The player can have a fine (on bank account)
Config.EarlyRespawnFine = false
Config.EarlyRespawnFineAmount = 100
Config.Locale = 'en'
Config.JobLocations = {
{x = 295.44149780273,y = -1439.6423339844,z = 28.803928375244 },
{x = 1165.1629638672,y = -1536.8948974609,z = 38.400791168213 },
{x = 1827.8881835938,y = 3693.8835449219,z = 33.224269866943 },
}
Config.Blip = {
Pos = { x = 1151.447, y = -1529.491, z = 34.375 },
Sprite = 61,
Display = 4,
Scale = 1.2,
Colour = 2,
}
Config.HelicopterSpawner = {
SpawnPoint = { x = 1151.447, y = -1529.491, z = 34.375 },
Heading = 0.0
}
Config.Zones = {
HospitalInteriorEntering1 = {
Pos = { x = 1151.447, y = -1529.491, z = 34.375 },
Size = { x = 1.5, y = 1.5, z = 1.0 },
Type = 1
},
HospitalInteriorInside1 = {
Pos = { x = 251.464, y = -1369.770, z = 28.648 },
Size = { x = 1.5, y = 1.5, z = 1.0 },
Type = -1
},
HospitalInteriorOutside1 = {
Pos = { x = 1153.364, y = -1525.731, z = 33.843 },
Size = { x = 1.5, y = 1.5, z = 1.0 },
Type = -1
},
HospitalInteriorExit1 = {
Pos = { x = 253.612, y = -1371.66, z = 28.647 },
Size = { x = 1.5, y = 1.5, z = 1.0 },
Type = 1
},
HospitalInteriorEntering2 = {
Pos = { x = 1137.181, y = -1597.504, z = 33.692 },
Size = { x = 1.5, y = 1.5, z = 1.0 },
Type = 1
},
HospitalInteriorInside2 = {
Pos = { x = 240.508, y = -1360.565, z = 28.647 },
Size = { x = 1.5, y = 1.5, z = 1.0 },
Type = -1
},
HospitalInteriorOutside2 = {
Pos = { x = 1137.922, y = -1601.434, z = 33.692 },
Size = { x = 1.5, y = 1.5, z = 1.0 },
Type = -1
},
HospitalInteriorExit2 = {
Pos = { x = 238.587, y = -1359.113, z = 28.647 },
Size = { x = 1.5, y = 1.5, z = 1.0 },
Type = 1
},
AmbulanceActions = {
Pos = { x = 244.048, y = -1366.330, z = 28.647 },
Size = { x = 1.5, y = 1.5, z = 1.0 },
Type = 1
},
VehicleSpawner = {
Pos = { x = 1128.290, y = -1601.451, z = 33.893 },
Size = { x = 1.5, y = 1.5, z = 1.0 },
Type = 1
},
VehicleSpawnPoint = {
Pos = { x = 1138.061, y = -1607.882, z = 34.692 },
Size = { x = 1.5, y = 1.5, z = 1.0 },
Type = -1
},
VehicleDeleter = {
Pos = { x = 1146.143, y = -1617.472, z = 34.694 },
Size = { x = 3.0, y = 3.0, z = 2.0 },
Type = 1
},
Pharmacy = {
Pos = {x = 230.38511657715,y = -1366.3583984375,z = 38.534370422363 },
Size = { x = 1.5, y = 1.5, z = 0.4 },
Type = 1
},
}
|
--[[ Copyright (c) 2010 Manuel "Roujin" Wolf
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. --]]
dofile "ui"
--! Variant of UI for running games
class "GameUI" (UI)
---@type GameUI
local GameUI = _G["GameUI"]
local TH = require "TH"
local WM = require "sdl".wm
local SDL = require "sdl"
local lfs = require "lfs"
local pathsep = package.config:sub(1, 1)
function GameUI:GameUI(app, local_hospital)
self:UI(app)
self.hospital = local_hospital
self.tutorial = { chapter = 0, phase = 0 }
if _MAP_EDITOR then
self:addWindow(UIMapEditor(self))
else
self.adviser = UIAdviser(self)
self.bottom_panel = UIBottomPanel(self)
self.menu_bar = UIMenuBar(self)
self.bottom_panel:addWindow(self.adviser)
self:addWindow(self.bottom_panel)
self:addWindow(self.menu_bar)
end
local scr_w = app.config.width
local scr_h = app.config.height
self.visible_diamond = self:makeVisibleDiamond(scr_w, scr_h)
if self.visible_diamond.w <= 0 or self.visible_diamond.h <= 0 then
-- For a standard 128x128 map, screen size would have to be in the
-- region of 3276x2457 in order to be too large.
if not _MAP_EDITOR then
error "Screen size too large for the map"
end
end
self.screen_offset_x, self.screen_offset_y = app.map:WorldToScreen(
app.map.th:getCameraTile(local_hospital:getPlayerIndex()))
self.zoom_factor = 1
self:scrollMap(-scr_w / 2, 16 - scr_h / 2)
self.limit_to_visible_diamond = not _MAP_EDITOR
self.transparent_walls = false
self.do_world_hit_test = true
self:setRandomAnnouncementTarget()
self.ticks_since_last_announcement = 0
self.momentum = app.config.scrolling_momentum
self.current_momentum = {x = 0.0, y = 0.0, z = 0.0}
self.speed_up_key_pressed = false
end
function GameUI:setupGlobalKeyHandlers()
UI.setupGlobalKeyHandlers(self)
self:addKeyHandler("escape", self, self.setEditRoom, false)
self:addKeyHandler("escape", self, self.showMenuBar)
self:addKeyHandler("z", self, self.keySpeedUp)
self:addKeyHandler("x", self, self.keyTransparent)
self:addKeyHandler({"shift", "a"}, self, self.toggleAdviser)
self:addKeyHandler({"ctrl", "d"}, self.app.world, self.app.world.dumpGameLog)
self:addKeyHandler({"ctrl", "t"}, self.app, self.app.dumpStrings)
self:addKeyHandler({"alt", "a"}, self, self.togglePlayAnnouncements)
self:addKeyHandler({"alt", "s"}, self, self.togglePlaySounds)
self:addKeyHandler({"alt", "m"}, self, self.togglePlayMusic)
if self.app.config.debug then
self:addKeyHandler("f11", self, self.showCheatsWindow)
end
end
function GameUI:makeVisibleDiamond(scr_w, scr_h)
local map_w = self.app.map.width
local map_h = self.app.map.height
assert(map_w == map_h, "UI limiter requires square map")
-- The visible diamond is the region which the top-left corner of the screen
-- is limited to, and ensures that the map always covers all of the screen.
-- Its verticies are at (x + w, y), (x - w, y), (x, y + h), (x, y - h).
return {
x = - scr_w / 2,
y = 16 * map_h - scr_h / 2,
w = 32 * map_h - scr_h - scr_w / 2,
h = 16 * map_h - scr_h / 2 - scr_w / 4,
}
end
function GameUI:setZoom(factor)
if factor <= 0 then
return
end
local old_factor = self.zoom_factor
if not factor or math.abs(factor - 1) < 0.001 then
factor = 1
end
local scr_w = self.app.config.width
local scr_h = self.app.config.height
local refx, refy = self.cursor_x or scr_w / 2, self.cursor_y or scr_h / 2
local cx, cy = self:ScreenToWorld(refx, refy)
self.zoom_factor = factor
self.visible_diamond = self:makeVisibleDiamond(scr_w / factor, scr_h / factor)
if self.visible_diamond.w < 0 or self.visible_diamond.h < 0 then
self:setZoom(old_factor)
return false
else
cx, cy = self.app.map:WorldToScreen(cx, cy)
self:scrollMap(cx - self.screen_offset_x - refx / factor,
cy - self.screen_offset_y - refy / factor)
return true
end
end
function GameUI:draw(canvas)
local app = self.app
local config = app.config
if _MAP_EDITOR or not self.in_visible_diamond then
canvas:fillBlack()
end
local zoom = self.zoom_factor
if canvas:scale(zoom) then
app.map:draw(canvas, self.screen_offset_x, self.screen_offset_y, config.width / zoom, config.height / zoom, 0, 0)
canvas:scale(1)
else
self:setZoom(1)
app.map:draw(canvas, self.screen_offset_x, self.screen_offset_y, config.width, config.height, 0, 0)
end
Window.draw(self, canvas, 0, 0) -- NB: not calling UI.draw on purpose
self:drawTooltip(canvas)
if self.simulated_cursor then
self.simulated_cursor.draw(canvas, self.cursor_x, self.cursor_y)
end
end
function GameUI:onChangeResolution()
-- Recalculate scrolling bounds
local scr_w = self.app.config.width
local scr_h = self.app.config.height
self.visible_diamond = self:makeVisibleDiamond(scr_w / self.zoom_factor, scr_h / self.zoom_factor)
self:scrollMap(0, 0)
UI.onChangeResolution(self)
end
--! Update UI state after the UI has been depersisted
--! When an UI object is depersisted, its state will reflect how the UI was at
-- the moment of persistence, which may be different to the keyboard / mouse
-- state at the moment of depersistence.
--!param ui (UI) The previously existing UI object, from which values should be
-- taken.
function GameUI:resync(ui)
if self.drag_mouse_move then
-- Check that a window is actually being dragged. If none is found, then
-- remove the drag handler.
local something_being_dragged = false
for _, window in ipairs(self.windows) do
if window.dragging then
something_being_dragged = true
break
end
end
if not something_being_dragged then
self.drag_mouse_move = nil
end
end
self.tick_scroll_amount = ui.tick_scroll_amount
self.down_count = ui.down_count
if ui.limit_to_visible_diamond ~= nil then
self.limit_to_visible_diamond = ui.limit_to_visible_diamond
end
self.key_remaps = ui.key_remaps
self.key_to_button_remaps = ui.key_to_button_remaps
end
local scroll_keys = {
up = {x = 0, y = -10},
right = {x = 10, y = 0},
down = {x = 0, y = 10},
left = {x = -10, y = 0},
}
function GameUI:updateKeyScroll()
local dx, dy = 0, 0
for key, scr in pairs(scroll_keys) do
if self.buttons_down[key] then
dx = dx + scr.x
dy = dy + scr.y
end
end
if dx ~= 0 or dy ~= 0 then
self.tick_scroll_amount = {x = dx, y = dy}
return true
else
self.tick_scroll_amount = false
return false
end
end
function GameUI:keySpeedUp()
self.speed_up_key_pressed = true
self.app.world:speedUp()
end
function GameUI:keyTransparent()
self:makeTransparentWalls()
end
function GameUI:onKeyDown(rawchar, modifiers, is_repeat)
if UI.onKeyDown(self, rawchar, modifiers, is_repeat) then
-- Key has been handled already
return true
end
local key = rawchar:lower()
if scroll_keys[key] then
self:updateKeyScroll()
return
end
end
function GameUI:onKeyUp(rawchar)
if UI.onKeyUp(self, rawchar) then
return true
end
local key = rawchar:lower()
if scroll_keys[key] then
self:updateKeyScroll()
return
end
-- Guess that the "Speed Up" key was released because the
-- code parameter can't provide UTF-8 key codes:
self.speed_up_key_pressed = false
if self.app.world:isCurrentSpeed("Speed Up") then
self.app.world:previousSpeed()
end
if self.transparent_walls then
self:removeTransparentWalls()
end
end
function GameUI:makeDebugFax()
local message = {
{text = "debug fax"}, -- no translation needed imo
choices = {{text = "close debug fax", choice = "close"}},
}
-- Don't use "strike" type here, as these open a different window and must have an owner
local types = {"emergency", "epidemy", "personality", "information", "disease", "report"}
self.bottom_panel:queueMessage(types[math.random(1, #types)], message)
end
function GameUI:ScreenToWorld(x, y)
local zoom = self.zoom_factor
return self.app.map:ScreenToWorld(self.screen_offset_x + x / zoom, self.screen_offset_y + y / zoom)
end
function GameUI:WorldToScreen(x, y)
local zoom = self.zoom_factor
x, y = self.app.map:WorldToScreen(x, y)
x = x - self.screen_offset_x
y = y - self.screen_offset_y
return x * zoom, y * zoom
end
function GameUI:getScreenOffset()
return self.screen_offset_x, self.screen_offset_y
end
--! Change if the World should be tested for entities under the cursor
--!param mode (boolean or room) true to enable hit test (normal), false
--! to disable, room to enable only for non-door objects in given room
function GameUI:setWorldHitTest(mode)
self.do_world_hit_test = mode
end
function GameUI:onCursorWorldPositionChange()
local zoom = self.zoom_factor
local x = self.screen_offset_x + self.cursor_x / zoom
local y = self.screen_offset_y + self.cursor_y / zoom
local entity = nil
if self.do_world_hit_test and not self:hitTest(self.cursor_x, self.cursor_y) then
entity = self.app.map.th:hitTestObjects(x, y)
if self.do_world_hit_test ~= true then
-- limit to non-door objects in room
local room = self.do_world_hit_test
entity = entity and class.is(entity, Object) and entity:getRoom() == room
and entity ~= room.door and entity
end
end
if entity ~= self.cursor_entity then
-- Stop displaying hoverable moods for the old entity
if self.cursor_entity then
self.cursor_entity:setMood(nil)
end
-- Make the entity easily accessible when debugging, and ignore "deselecting" an entity.
if entity then
self.debug_cursor_entity = entity
end
local epidemic = self.hospital.epidemic
local infected_cursor = TheApp.gfx:loadMainCursor("epidemic")
local epidemic_cursor = TheApp.gfx:loadMainCursor("epidemic_hover")
self.cursor_entity = entity
if self.cursor ~= self.edit_room_cursor and self.cursor ~= self.waiting_cursor then
local cursor = self.default_cursor
if self.app.world.user_actions_allowed then
--- If the patient is infected show the infected cursor
if epidemic and epidemic.coverup_in_progress and
entity and entity.infected and not epidemic.timer.closed then
cursor = infected_cursor
-- In vaccination mode display epidemic hover cursor for all entities
elseif epidemic and epidemic.vaccination_mode_active then
cursor = epidemic_cursor
-- Otherwise just show the normal cursor and hover if appropriate
else
cursor = entity and entity.hover_cursor or
(self.down_count ~= 0 and self.down_cursor or self.default_cursor)
end
end
self:setCursor(cursor)
end
if self.bottom_panel then
self.bottom_panel:setDynamicInfo(nil)
end
end
-- Queueing icons over patients
local wx, wy = self:ScreenToWorld(self.cursor_x, self.cursor_y)
wx = math.floor(wx)
wy = math.floor(wy)
local room
if wx > 0 and wy > 0 and wx < self.app.map.width and wy < self.app.map.height then
room = self.app.world:getRoom(wx, wy)
end
if room ~= self.cursor_room then
-- Unset queue mood for patients queueing the old room
if self.cursor_room then
local queue = self.cursor_room.door.queue
if queue then
for _, humanoid in ipairs(queue) do
humanoid:setMood("queue", "deactivate")
end
end
end
-- Set queue mood for patients queueing the new room
if room then
local queue = room.door.queue
if queue then
for _, humanoid in ipairs(queue) do
humanoid:setMood("queue", "activate")
end
end
end
self.cursor_room = room
end
-- Any hoverable mood should be displayed on the new entity
if class.is(entity, Humanoid) then
for key, value in pairs(entity.active_moods) do
if value.on_hover then
entity:setMoodInfo(value)
break
end
end
end
-- Dynamic info
if entity and self.bottom_panel then
self.bottom_panel:setDynamicInfo(entity:getDynamicInfo())
end
return Window.onCursorWorldPositionChange(self, self.cursor_x, self.cursor_y)
end
local UpdateCursorPosition = TH.cursor.setPosition
local highlight_x, highlight_y
--! Called when the mouse enters or leaves the game window.
function GameUI:onWindowActive(gain)
if gain == 0 then
self.tick_scroll_amount_mouse = false
end
end
-- TODO: try to remove duplication with UI:onMouseMove
function GameUI:onMouseMove(x, y, dx, dy)
local repaint = UpdateCursorPosition(self.app.video, x, y)
if self.app.moviePlayer.playing then
return false
end
self.cursor_x = x
self.cursor_y = y
if self:onCursorWorldPositionChange() or self.simulated_cursor then
repaint = true
end
if self.buttons_down.mouse_middle then
local zoom = self.zoom_factor
self.current_momentum.x = -dx/zoom
self.current_momentum.y = -dy/zoom
-- Stop zooming when the middle mouse button is pressed
self.current_momentum.z = 0
self:scrollMap(self.current_momentum.x, self.current_momentum.y)
repaint = true
end
if self.drag_mouse_move then
self.drag_mouse_move(x, y)
return true
end
local scroll_region_size
if self.app.config.fullscreen then
-- As the mouse is locked within the window, a 1px region feels a lot
-- larger than it actually is.
scroll_region_size = 1
else
-- In windowed mode, a reasonable size is needed, though not too large.
scroll_region_size = 8
end
if not self.app.config.prevent_edge_scrolling and (x < scroll_region_size
or y < scroll_region_size or x >= self.app.config.width - scroll_region_size
or y >= self.app.config.height - scroll_region_size) then
local dx = 0
local dy = 0
local scroll_power = 7
if x < scroll_region_size then
dx = -scroll_power
elseif x >= self.app.config.width - scroll_region_size then
dx = scroll_power
end
if y < scroll_region_size then
dy = -scroll_power
elseif y >= self.app.config.height - scroll_region_size then
dy = scroll_power
end
if not self.tick_scroll_amount_mouse then
self.tick_scroll_amount_mouse = {x = dx, y = dy}
else
self.tick_scroll_amount_mouse.x = dx
self.tick_scroll_amount_mouse.y = dy
end
else
self.tick_scroll_amount_mouse = false
end
if Window.onMouseMove(self, x, y, dx, dy) then
repaint = true
end
self:updateTooltip()
local map = self.app.map
local wx, wy = self:ScreenToWorld(x, y)
wx = math.floor(wx)
wy = math.floor(wy)
if highlight_x then
--map.th:setCell(highlight_x, highlight_y, 4, 0)
highlight_x = nil
end
if 1 <= wx and wx <= 128 and 1 <= wy and wy <= 128 then
if map.th:getCellFlags(wx, wy).passable then
--map.th:setCell(wx, wy, 4, 24 + 8 * 256)
highlight_x = wx
highlight_y = wy
end
end
return repaint
end
function GameUI:onMouseUp(code, x, y)
if self.app.moviePlayer.playing then
return UI.onMouseUp(self, code, x, y)
end
local button = self.button_codes[code]
if button == "right" and not _MAP_EDITOR and highlight_x then
local window = self:getWindow(UIPatient)
local patient = (window and window.patient.is_debug and window.patient) or self.hospital:getDebugPatient()
if patient then
patient:walkTo(highlight_x, highlight_y)
patient:queueAction{name = "idle"}
end
end
if self.edit_room then
if class.is(self.edit_room, Room) then
if button == "right" and self.cursor == self.waiting_cursor then
-- Still waiting for people to leave the room, abort editing it.
self:setEditRoom(false)
end
else -- No room chosen yet, but about to edit one.
if button == "left" then -- Take the clicked one.
local room = self.app.world:getRoom(self:ScreenToWorld(x, y))
if room and not room.crashed then
self:setCursor(self.waiting_cursor)
self.edit_room = room
room:tryToEdit()
end
else -- right click, we don't want to edit a room after all.
self:setEditRoom(false)
end
end
end
-- During vaccination mode you can only interact with
-- infected patients
local epidemic = self.hospital.epidemic
-- infected patients
local epidemic = self.hospital.epidemic
if epidemic and epidemic.vaccination_mode_active then
if button == "left" then
if self.cursor_entity then
-- Allow click behaviour for infected patients
if self.cursor_entity.infected then
self.cursor_entity:onClick(self,button)
end
end
elseif button == "right" then
--Right click turns vaccination mode off
local watch = TheApp.ui:getWindow(UIWatch)
watch:toggleVaccinationMode()
end
end
return UI.onMouseUp(self, code, x, y)
end
function GameUI:onMouseWheel(x, y)
local inside_window = false
if self.windows then
for _, window in ipairs(self.windows) do
if window:hitTest(self.cursor_x - window.x, self.cursor_y - window.y) then
inside_window = true
break
end
end
end
if not inside_window then
-- Apply momentum to the zoom
if math.abs(self.current_momentum.z) < 12 then
self.current_momentum.z = self.current_momentum.z + y
end
end
return UI.onMouseWheel(self, x, y)
end
function GameUI:setRandomAnnouncementTarget()
-- NB: Every tick is 30ms, so 2000 ticks is 1 minute
self.random_announcement_ticks_target = math.random(8000, 12000)
end
function GameUI:playAnnouncement(name, played_callback, played_callback_delay)
self.ticks_since_last_announcement = 0
if self.app.world:getLocalPlayerHospital():hasStaffedDesk() then
UI.playAnnouncement(self, name, played_callback, played_callback_delay)
end
end
function GameUI:onTick()
local repaint = UI.onTick(self)
if not self.buttons_down.mouse_middle then
if math.abs(self.current_momentum.x) < 0.2 and math.abs(self.current_momentum.y) < 0.2 then
-- Stop scrolling
self.current_momentum.x = 0.0
self.current_momentum.y = 0.0
else
self.current_momentum.x = self.current_momentum.x * self.momentum
self.current_momentum.y = self.current_momentum.y * self.momentum
self:scrollMap(self.current_momentum.x, self.current_momentum.y)
end
if math.abs(self.current_momentum.z) < 0.2 then
self.current_momentum.z = 0.0
else
self.current_momentum.z = self.current_momentum.z * self.momentum
self.app.world:adjustZoom(self.current_momentum.z)
end
end
if not self.app.world:isCurrentSpeed("Pause") then
local ticks_since_last_announcement = self.ticks_since_last_announcement
if ticks_since_last_announcement >= self.random_announcement_ticks_target then
self:playAnnouncement("rand*.wav")
self:setRandomAnnouncementTarget()
else
self.ticks_since_last_announcement = ticks_since_last_announcement + 1
end
end
if self.tick_scroll_amount or self.tick_scroll_amount_mouse then
-- The scroll amount per tick gradually increases as the duration of the
-- scroll increases due to this multiplier.
local mult = self.tick_scroll_mult
mult = mult + 0.02
if mult > 2 then
mult = 2
end
self.tick_scroll_mult = mult
-- Combine the mouse scroll and keyboard scroll
local dx, dy = 0, 0
if self.tick_scroll_amount_mouse then
dx, dy = self.tick_scroll_amount_mouse.x, self.tick_scroll_amount_mouse.y
-- If the middle mouse button is down, then the world is being dragged,
-- and so the scroll direction due to the cursor being at the map edge
-- should be opposite to normal to make it feel more natural.
if self.buttons_down.mouse_middle then
dx, dy = -dx, -dy
end
end
if self.tick_scroll_amount then
dx = dx + self.tick_scroll_amount.x
dy = dy + self.tick_scroll_amount.y
end
-- Faster scrolling with shift key
local factor = self.app.config.scroll_speed
if self.app.key_modifiers.shift then
mult = mult * factor
end
self:scrollMap(dx * mult, dy * mult)
repaint = true
else
self.tick_scroll_mult = 1
end
if self:onCursorWorldPositionChange() then
repaint = true
end
return repaint
end
local abs, sqrt_5, floor = math.abs, math.sqrt(1 / 5), math.floor
function GameUI:scrollMapTo(x, y)
local zoom = 2 * self.zoom_factor
local config = self.app.config
return self:scrollMap(x - self.screen_offset_x - config.width / zoom,
y - self.screen_offset_y - config.height / zoom)
end
function GameUI.limitPointToDiamond(dx, dy, visible_diamond, do_limit)
-- If point outside visible diamond, then move point to the nearest position
-- on the edge of the diamond (NB: relies on diamond.w == 2 * diamond.h).
local rx = dx - visible_diamond.x
local ry = dy - visible_diamond.y
if abs(rx) + abs(ry) * 2 > visible_diamond.w then
if do_limit then
-- Determine the quadrant which the point lies in and accordingly set:
-- (vx, vy) : a unit vector perpendicular to the diamond edge in the quadrant
-- (p1x, p1y), (p2x, p2y) : the two diamond verticies in the quadrant
-- d : distance from the point to the line defined by the diamond edge (not the line segment itself)
local vx, vy, d
local p1x, p1y, p2x, p2y = 0, 0, 0, 0
if rx >= 0 and ry >= 0 then
p1x, p2y = visible_diamond.w, visible_diamond.h
vx, vy = sqrt_5, 2 * sqrt_5
d = (rx * vx + ry * vy) - (p1x * vx)
elseif rx >= 0 and ry < 0 then
p2x, p1y = visible_diamond.w, -visible_diamond.h
vx, vy = sqrt_5, -2 * sqrt_5
d = (rx * vx + ry * vy) - (p2x * vx)
elseif rx < 0 and ry >= 0 then
p2x, p1y = -visible_diamond.w, visible_diamond.h
vx, vy = -sqrt_5, 2 * sqrt_5
d = (rx * vx + ry * vy) - (p2x * vx)
else--if rx < 0 and ry < 0 then
p1x, p2y = -visible_diamond.w, -visible_diamond.h
vx, vy = -sqrt_5, -2 * sqrt_5
d = (rx * vx + ry * vy) - (p1x * vx)
end
-- In the unit vector parallel to the diamond edge, resolve the two verticies and
-- the point, and either move the point to the edge or to one of the two verticies.
-- NB: vx, vy, p1x, p1y, p2x, p2y are set such that p1 < p2.
local p1 = vx * p1y - vy * p1x
local p2 = vx * p2y - vy * p2x
local pd = vx * ry - vy * rx
if pd < p1 then
dx, dy = p1x + visible_diamond.x, p1y + visible_diamond.y
elseif pd > p2 then
dx, dy = p2x + visible_diamond.x, p2y + visible_diamond.y
else--if p1 <= pd and pd <= p2 then
dx, dy = dx - d * vx, dy - d * vy
end
else
return dx, dy, false
end
end
return dx, dy, true
end
function GameUI:scrollMap(dx, dy)
dx = dx + self.screen_offset_x
dy = dy + self.screen_offset_y
dx, dy, self.in_visible_diamond = self.limitPointToDiamond(dx, dy,
self.visible_diamond, self.limit_to_visible_diamond)
self.screen_offset_x = floor(dx + 0.5)
self.screen_offset_y = floor(dy + 0.5)
end
function GameUI:limitCamera(mode)
self.limit_to_visible_diamond = mode
self:scrollMap(0, 0)
end
--! Applies the current setting for wall transparency to the map
function GameUI:applyTransparency()
self.app.map.th:setWallDrawFlags(self.transparent_walls and 4 or 0)
end
--! Sets wall transparency to the specified parameter
--!param mode (boolean) whether to enable or disable wall transparency
function GameUI:setWallsTransparent(mode)
self.transparent_walls = mode
self:applyTransparency()
end
--! Toggles transparency of walls, i.e. enables if currently disabled, and vice versa
function GameUI:makeTransparentWalls()
self:setWallsTransparent(true)
end
function GameUI:removeTransparentWalls()
self:setWallsTransparent(not self.transparent_walls)
end
function UI:toggleAdviser()
self.app.config.adviser_disabled = not self.app.config.adviser_disabled
self.app:saveConfig()
end
function UI:togglePlaySounds()
self.app.config.play_sounds = not self.app.config.play_sounds
self.app.audio:playSoundEffects(self.app.config.play_sounds)
self.app:saveConfig()
end
function UI:togglePlayAnnouncements()
self.app.config.play_announcements = not self.app.config.play_announcements
self.app:saveConfig()
end
function UI:togglePlayMusic(item)
if not self.app.audio.background_music then
self.app.config.play_music = true
self.app.audio:playRandomBackgroundTrack() -- play
else
self.app.config.play_music = false
self.app.audio:stopBackgroundTrack() -- stop
end
-- self.app.config.play_music = not self.app.config.play_music
self.app:saveConfig()
end
local tutorial_phases
local function make_tutorial_phases()
tutorial_phases = {
{
-- 1) build reception
{ text = _A.tutorial.build_reception, -- 1
begin_callback = function() TheApp.ui:getWindow(UIBottomPanel):startButtonBlinking(3) end,
end_callback = function() TheApp.ui:getWindow(UIBottomPanel):stopButtonBlinking() end, },
{ text = _A.tutorial.order_one_reception, -- 2
begin_callback = function() TheApp.ui:getWindow(UIFurnishCorridor):startButtonBlinking(3) end,
end_callback = function() TheApp.ui:getWindow(UIFurnishCorridor):stopButtonBlinking(3) end, },
{ text = _A.tutorial.accept_purchase, -- 3
begin_callback = function() TheApp.ui:getWindow(UIFurnishCorridor):startButtonBlinking(2) end,
end_callback = function() TheApp.ui:getWindow(UIFurnishCorridor):stopButtonBlinking(2) end, },
_A.tutorial.rotate_and_place_reception, -- 4
_A.tutorial.reception_invalid_position, -- 5
-- 6: object other than reception selected. currently no text for this phase.
},
{
-- 2) hire receptionist
{ text = _A.tutorial.hire_receptionist, -- 1
begin_callback = function() TheApp.ui:getWindow(UIBottomPanel):startButtonBlinking(5) end,
end_callback = function() TheApp.ui:getWindow(UIBottomPanel):stopButtonBlinking() end, },
{ text = _A.tutorial.select_receptionists, -- 2
begin_callback = function() TheApp.ui:getWindow(UIHireStaff):startButtonBlinking(4) end,
end_callback = function() TheApp.ui:getWindow(UIHireStaff):stopButtonBlinking() end, },
{ text = _A.tutorial.next_receptionist, -- 3
begin_callback = function() TheApp.ui:getWindow(UIHireStaff):startButtonBlinking(8) end,
end_callback = function() TheApp.ui:getWindow(UIHireStaff):stopButtonBlinking() end, },
{ text = _A.tutorial.prev_receptionist, -- 4
begin_callback = function() TheApp.ui:getWindow(UIHireStaff):startButtonBlinking(5) end,
end_callback = function() TheApp.ui:getWindow(UIHireStaff):stopButtonBlinking() end, },
{ text = _A.tutorial.choose_receptionist, -- 5
begin_callback = function() TheApp.ui:getWindow(UIHireStaff):startButtonBlinking(6) end,
end_callback = function() TheApp.ui:getWindow(UIHireStaff):stopButtonBlinking() end, },
_A.tutorial.place_receptionist, -- 6
_A.tutorial.receptionist_invalid_position, -- 7
},
{
-- 3) build GP's office
-- 3.1) room window
{ text = _A.tutorial.build_gps_office, -- 1
begin_callback = function() TheApp.ui:getWindow(UIBottomPanel):startButtonBlinking(2) end,
end_callback = function() TheApp.ui:getWindow(UIBottomPanel):stopButtonBlinking() end, },
{ text = _A.tutorial.select_diagnosis_rooms, -- 2
begin_callback = function() TheApp.ui:getWindow(UIBuildRoom):startButtonBlinking(1) end,
end_callback = function() TheApp.ui:getWindow(UIBuildRoom):stopButtonBlinking() end, },
{ text = _A.tutorial.click_gps_office, -- 3
begin_callback = function() TheApp.ui:getWindow(UIBuildRoom):startButtonBlinking(5) end,
end_callback = function() TheApp.ui:getWindow(UIBuildRoom):stopButtonBlinking() end, },
-- 3.2) blueprint
-- [11][58] was maybe planned to be used in this place, but is not needed.
_A.tutorial.click_and_drag_to_build, -- 4
_A.tutorial.room_in_invalid_position, -- 5
_A.tutorial.room_too_small, -- 6
_A.tutorial.room_too_small_and_invalid, -- 7
{ text = _A.tutorial.room_big_enough, -- 8
begin_callback = function() TheApp.ui:getWindow(UIEditRoom):startButtonBlinking(4) end,
end_callback = function() TheApp.ui:getWindow(UIEditRoom):stopButtonBlinking() end, },
-- 3.3) door and windows
_A.tutorial.place_door, -- 9
_A.tutorial.door_in_invalid_position, -- 10
{ text = _A.tutorial.place_windows, -- 11
begin_callback = function() TheApp.ui:getWindow(UIEditRoom):startButtonBlinking(4) end,
end_callback = function() TheApp.ui:getWindow(UIEditRoom):stopButtonBlinking() end, },
{ text = _A.tutorial.window_in_invalid_position, -- 12
begin_callback = function() TheApp.ui:getWindow(UIEditRoom):startButtonBlinking(4) end,
end_callback = function() TheApp.ui:getWindow(UIEditRoom):stopButtonBlinking() end, },
-- 3.4) objects
_A.tutorial.place_objects, -- 13
_A.tutorial.object_in_invalid_position, -- 14
{ text = _A.tutorial.confirm_room, -- 15
begin_callback = function() TheApp.ui:getWindow(UIEditRoom):startButtonBlinking(4) end,
end_callback = function() TheApp.ui:getWindow(UIEditRoom):stopButtonBlinking() end, },
{ text = _A.tutorial.information_window, -- 16
begin_callback = function() TheApp.ui:getWindow(UIInformation):startButtonBlinking(1) end,
end_callback = function() TheApp.ui:getWindow(UIInformation):stopButtonBlinking() end, },
},
{
-- 4) hire doctor
{ text = _A.tutorial.hire_doctor, -- 1
begin_callback = function() TheApp.ui:getWindow(UIBottomPanel):startButtonBlinking(5) end,
end_callback = function() TheApp.ui:getWindow(UIBottomPanel):stopButtonBlinking() end, },
{ text = _A.tutorial.select_doctors, -- 2
begin_callback = function() TheApp.ui:getWindow(UIHireStaff):startButtonBlinking(1) end,
end_callback = function() TheApp.ui:getWindow(UIHireStaff):stopButtonBlinking() end, },
{ text = _A.tutorial.choose_doctor, -- 3
begin_callback = function() TheApp.ui:getWindow(UIHireStaff):startButtonBlinking(6) end,
end_callback = function() TheApp.ui:getWindow(UIHireStaff):stopButtonBlinking() end, },
_A.tutorial.place_doctor, -- 4
_A.tutorial.doctor_in_invalid_position, -- 5
},
{
-- 5) end of tutorial
{ begin_callback = function()
-- The demo uses a single string for the post-tutorial info while
-- the real game uses three.
local texts = TheApp.using_demo_files and {
_S.introduction_texts["level15"],
_S.introduction_texts["demo"],
} or {
_S.introduction_texts["level15"],
_S.introduction_texts["level16"],
_S.introduction_texts["level17"],
_S.introduction_texts["level1"],
}
TheApp.ui:addWindow(UIInformation(TheApp.ui, {texts}))
TheApp.ui:addWindow(UIWatch(TheApp.ui, "initial_opening"))
end,
},
},
}
end
tutorial_phases = setmetatable({}, {__index = function(t, k)
make_tutorial_phases()
return tutorial_phases[k]
end})
-- Called to trigger step to another part of the tutorial.
-- chapter: Individual parts of the tutorial. Step will only happen if it's the current chapter.
-- phase_from: Phase we need to be in for this step to happen. Multiple phases can be given here in an array.
-- phase_to: Phase we want to step to or "next" to go to next chapter or "end" to end tutorial.
-- returns true if we changed phase, false if we didn't
function GameUI:tutorialStep(chapter, phase_from, phase_to, ...)
if self.tutorial.chapter ~= chapter then
return false
end
if type(phase_from) == "table" then
local contains_current = false
for _, phase in ipairs(phase_from) do
if phase == self.tutorial.phase then
contains_current = true
break
end
end
if not contains_current then return false end
else
if self.tutorial.phase ~= phase_from then return false end
end
local old_phase = tutorial_phases[self.tutorial.chapter][self.tutorial.phase]
if old_phase and old_phase.end_callback and type(old_phase.end_callback) == "function" then
old_phase.end_callback(...)
end
if phase_to == "end" then
self.tutorial.chapter = 0
self.tutorial.phase = 0
return true
elseif phase_to == "next" then
self.tutorial.chapter = self.tutorial.chapter + 1
self.tutorial.phase = 1
else
self.tutorial.phase = phase_to
end
if TheApp.config.debug then print("Tutorial: Now in " .. self.tutorial.chapter .. ", " .. self.tutorial.phase) end
local new_phase = tutorial_phases[self.tutorial.chapter][self.tutorial.phase]
local str, callback
if (type(new_phase) == "table" and type(new_phase.text) == "table") or not new_phase.text then
str = new_phase.text
callback = new_phase.begin_callback
else
str = new_phase
end
if str and str.text then
self.adviser:say(str, true, true)
else
self.adviser.stay_up = nil
end
if callback then
callback(...)
end
return true
end
function GameUI:startTutorial(chapter)
chapter = chapter or 1
self.tutorial.chapter = chapter
self.tutorial.phase = 0
self:tutorialStep(chapter, 0, 1)
end
function GameUI:setEditRoom(enabled)
-- TODO: Make the room the cursor is over flash
if enabled then
self:setCursor(self.edit_room_cursor)
self.edit_room = true
else
-- If the actual editing hasn't started yet but is on its way,
-- activate the room again.
if class.is(self.edit_room, Room) and self.cursor == self.waiting_cursor then
self.edit_room.is_active = true
else
-- If we are currently editing a room it may happen that we need to abort it.
-- Also remove any dialog where the user is buying items.
local item_window = self.app.ui:getWindow(UIFurnishCorridor)
if item_window and item_window.edit_dialog then
item_window:close()
end
local edit_window = self.app.ui:getWindow(UIEditRoom)
if edit_window then
edit_window:verifyOrAbortRoom()
end
end
self:setCursor(self.default_cursor)
self.edit_room = false
end
end
function GameUI:afterLoad(old, new)
if old < 16 then
self.zoom_factor = 1
end
if old < 23 then
self.do_world_hit_test = not self:getWindow(UIPlaceObjects)
end
if old < 28 then
self:setRandomAnnouncementTarget()
self.ticks_since_last_announcement = 0
end
if old < 34 then
self.adviser.queued_messages = {}
self.adviser.phase = 0
self.adviser.timer = nil
self.adviser.frame = 1
self.adviser.number_frames = 4
end
if old < 70 then
self:addKeyHandler({"shift", "a"}, self, self.toggleAdviser)
end
if old < 75 then
self.current_momentum = { x = 0, y = 0 }
self.momentum = self.app.config.scrolling_momentum
end
if old < 78 then
self.current_momentum = { x = 0, y = 0, z = 0}
end
if old < 81 then
self:removeKeyHandler("x", self, self.toggleWallsTransparent)
self:addKeyHandler("z", self, self.keySpeedUp)
self:addKeyHandler("x", self, self.keyTransparent)
end
return UI.afterLoad(self, old, new)
end
function GameUI:showBriefing()
local level = self.app.world.map.level_number
local text = {_S.information.custom_game}
if type(level) == "number" then
text = _S.introduction_texts[TheApp.using_demo_files and "demo" or "level" .. level]
elseif self.app.world.map.level_intro then
text = {self.app.world.map.level_intro}
end
self:addWindow(UIInformation(self, text))
end
--! Offers a confirmation window to quit the game and return to main menu
-- NB: overrides UI.quit, do NOT call it from here
function GameUI:quit()
self:addWindow(UIConfirmDialog(self, _S.confirmation.quit, --[[persistable:gameui_confirm_quit]] function()
self.app:loadMainMenu()
end))
end
function GameUI:showCheatsWindow()
self:addWindow(UICheats(self))
end
function GameUI:showMenuBar()
self.menu_bar:appear()
end
|
local Modules = script.Parent.Parent.Parent.Parent
local Roact = require(Modules.Roact)
local ComplexStringInput = require(script.Parent.ComplexStringInput)
local function IntegerInput(props)
return Roact.createElement(ComplexStringInput, {
Key = props.Key,
Value = props.Value,
Filter = function(raw)
return raw:match("%d*%.?%d*")
end,
Validate = function(raw)
if raw == "" then
raw = 0
end
return true, math.floor(tonumber(raw) + 0.5)
end,
Parse = function(raw)
return tonumber(raw)
end,
OnChanged = props.OnChanged,
})
end
return IntegerInput
|
function SetupWrapper(name)
if not EnabledManagedProjects() then
return
end
SetupExternalManagedTestProject(name .. ".CSharp")
end
group "Tests/Namespaces"
SetupTestNativeProject("NamespacesBase")
targetdir (path.join(gendir, "NamespacesDerived"))
|
-- [[ handler responders ]]
function getImage( playerToReceive, id )
triggerClientEvent( playerToReceive, "onClientGotImage", resourceRoot, exports.mrp_cache:getImage(id))
end
addEvent("getImage", true)
addEventHandler("getImage", resourceRoot , getImage)
|
--[[
fs_barrel
================
Copyright (C) 2018-2019 Quentin Bazin
LGPLv2.1+
See LICENSE.txt for more information
]]--
local modpath = minetest.get_modpath(minetest.get_current_modname())
fs_barrel = rawget(_G, "fs_barrel") or {}
fs_barrel.modpath = modpath
dofile(modpath .. "/barrel.lua")
dofile(modpath .. "/crafting.lua")
|
--***********************************************************
--** ROBERT JOHNSON **
--***********************************************************
require "ISUI/ISPanel"
---@class ISWhitelistTable : ISPanel
ISWhitelistTable = ISPanel:derive("ISWhitelistTable");
local FONT_HGT_SMALL = getTextManager():getFontHeight(UIFont.Small)
local FONT_HGT_MEDIUM = getTextManager():getFontHeight(UIFont.Medium)
local FONT_HGT_LARGE = getTextManager():getFontHeight(UIFont.Large)
local HEADER_HGT = FONT_HGT_MEDIUM + 2 * 2
function ISWhitelistTable:initialise()
ISPanel.initialise(self);
end
function ISWhitelistTable:render()
ISPanel.render(self);
-- self:drawText(self.tableName, self.width/2 - (getTextManager():MeasureStringX(UIFont.Medium, self.tableName) / 2), z, 1,1,1,1, UIFont.Medium);
self:drawRectBorder(self.datas.x, self.datas.y - HEADER_HGT, self.datas:getWidth(), HEADER_HGT + 1, 1, self.borderColor.r, self.borderColor.g, self.borderColor.b);
self:drawRect(self.datas.x, self.datas.y - HEADER_HGT, self.datas:getWidth(), HEADER_HGT + 1, self.listHeaderColor.a, self.listHeaderColor.r, self.listHeaderColor.g, self.listHeaderColor.b);
local x = 0;
for name, type in pairs(self.columns) do
if type["name"] ~= "id" then
self:drawRect(self.datas.x + x, 1 + self.datas.y - HEADER_HGT, 1, HEADER_HGT,1,self.borderColor.r, self.borderColor.g, self.borderColor.b);
self:drawText(type["name"], self.datas.x + x + 8, self.datas.y - HEADER_HGT + 2, 1,1,1,1,UIFont.Medium);
if self.columnSize[type["name"]] then
x = x + self.columnSize[type["name"]];
else
x = x + 100;
end
end
end
local y = self.datas.y + self.datas.height + 5
self:drawText(getText("IGUI_DbViewer_TotalResult") .. self.totalResult, 10, y, 1,1,1,1,UIFont.Small)
y = y + FONT_HGT_SMALL
if #self.datas.items > 0 or self.filtered then
self:drawText(getText("IGUI_DbViewer_Filters"), 10, y, 1,1,1,1,UIFont.Large);
y = y + FONT_HGT_LARGE
end
x = 10;
if #self.datas.items > 0 or self.filtered then
self:drawRectBorder(self.datas.x, y, self.datas:getWidth(), FONT_HGT_SMALL + 1, 1, self.borderColor.r, self.borderColor.g, self.borderColor.b);
self:drawRect(self.datas.x, y, self.datas:getWidth(), FONT_HGT_SMALL + 1, self.listHeaderColor.a, self.listHeaderColor.r, self.listHeaderColor.g, self.listHeaderColor.b);
end
local nbr = 1;
for _, v in ipairs(self.filters) do
if #self.datas.items > 0 or self.filtered then
v:setY(y + FONT_HGT_SMALL)
v:setVisible(true);
if self.columnSize[v.columnName] then
local size = self.columnSize[v.columnName] + 1
if nbr >= #self.columns then
size = self.width - x - 10;
end
self:drawText(v.columnName, x + 10, y, 1,1,1,1,UIFont.Small);
self:drawRectBorder(self.datas.x + x - 10, y, 1, self.datas.itemheight + 1, 1, self.borderColor.r, self.borderColor.g, self.borderColor.b);
v:setWidth(size)
v:setX(x);
x = x + self.columnSize[v.columnName];
nbr = nbr + 1;
else
x = x + 100;
end
else
v:setVisible(false);
end
end
if self.loading then
self:drawRect(0, 0, self:getWidth(), self:getHeight(), 0.8, 0.1, 0.1, 0.1);
self:drawTextCentre(getText("IGUI_DbViewer_Loading"), self:getWidth()/2, self:getHeight()/2, 1,1,1,1,UIFont.Large);
end
end
function ISWhitelistTable:new (x, y, width, height, tableName)
local o = ISPanel:new(x, y, width, height);
o.tableName = tableName;
setmetatable(o, self);
o.schema = {};
o.pages = {};
o.fullPages = {};
o.listHeaderColor = {r=0.4, g=0.4, b=0.4, a=0.3};
o.borderColor = {r=0.4, g=0.4, b=0.4, a=0};
o.backgroundColor = {r=0, g=0, b=0, a=1};
o.columnSize = {};
o.currentPage = 1;
o.buttonBorderColor = {r=0.7, g=0.7, b=0.7, a=0.5};
o.filters = {};
o.filtered = false;
ISWhitelistTable.instance = o;
o.totalResult = 0;
o.entriesPerPages = 500;
-- getTableResult(tableName);
return o;
end
function ISWhitelistTable:createChildren()
ISPanel.createChildren(self);
self.datas = ISScrollingListBox:new(10, HEADER_HGT, self.width - 20, self.height - 230);
self.datas:initialise();
self.datas:instantiate();
self.datas.itemheight = FONT_HGT_SMALL + 2 * 2
self.datas.selected = 0;
self.datas.joypadParent = self;
self.datas.font = UIFont.NewSmall;
self.datas.doDrawItem = self.drawDatas;
self.datas.drawBorder = true;
self.datas.parent = self;
self:addChild(self.datas);
self.pagePanel = ISPanel:new(0, self.datas:getBottom(), 100, FONT_HGT_MEDIUM + 2 * 2)
self.pagePanel:initialise()
self.pagePanel:instantiate()
self.pagePanel:noBackground()
self:addChild(self.pagePanel)
self.nbrPerPageLbl = ISLabel:new(0, 0, self.pagePanel.height, getText("IGUI_DbViewer_NbrPerPage"), 1, 1, 1, 1, UIFont.Small, true);
self.nbrPerPageLbl:initialise();
self.nbrPerPageLbl:instantiate();
self.pagePanel:addChild(self.nbrPerPageLbl);
local textWid = getTextManager():MeasureStringX(UIFont.Medium, "9999")
self.nbrPerPages = ISTextEntryBox:new("500", self.nbrPerPageLbl:getRight() + 6, 0, textWid + 2 * 2, FONT_HGT_MEDIUM + 2 * 2);
self.nbrPerPages.font = UIFont.Medium
self.nbrPerPages:initialise();
self.nbrPerPages:instantiate();
self.nbrPerPages:setOnlyNumbers(true);
self.nbrPerPages.onTextChange = ISWhitelistTable.onNbrPerPageChange;
self.nbrPerPages.target = self;
self.nbrPerPages.tableName = self.tableName;
self.pagePanel:addChild(self.nbrPerPages);
self.pagesLbl = ISLabel:new(self.nbrPerPages:getRight() + 6, 0, self.pagePanel.height, getText("IGUI_DbViewer_Page"), 1, 1, 1, 1, UIFont.Small, true);
self.pagesLbl:initialise();
self.pagesLbl:instantiate();
self.pagePanel:addChild(self.pagesLbl);
self.prePage = ISButton:new(self.pagesLbl:getRight() + 6, 0, 15, self.pagePanel.height, "<", self, ISWhitelistTable.onOptionPage);
self.prePage.internal = "PREVIOUS";
self.prePage:initialise();
self.prePage:instantiate();
self.prePage.borderColor = self.buttonBorderColor;
self.pagePanel:addChild(self.prePage);
self.pageLbl = ISLabel:new(self.prePage:getRight() + 6, 0, self.pagePanel.height, "1/1", 1, 1, 1, 1, UIFont.Small, true);
self.pageLbl:initialise();
self.pageLbl:instantiate();
self.pagePanel:addChild(self.pageLbl);
self.nextPage = ISButton:new(self.pageLbl:getRight() + 6, 0, 15, self.pagePanel.height, ">", self, ISWhitelistTable.onOptionPage);
self.nextPage.internal = "NEXT";
self.nextPage:initialise();
self.nextPage:instantiate();
self.nextPage.borderColor = self.buttonBorderColor;
self.pagePanel:addChild(self.nextPage);
self.pagePanel:setWidth(self.nextPage:getRight())
self.pagePanel:setX(self.width - self.pagePanel.width - 10)
for _, type in pairs(self.columns) do
local size = 100;
local entryHgt = FONT_HGT_SMALL + 2 * 2
if type["name"] ~= "id" then
if type["type"] == "TEXT" or type["type"] == "INTEGER" then
self.entry = ISTextEntryBox:new("", 10, self.datas.x + self.datas.height + 85, size, entryHgt);
self.entry.font = UIFont.Medium
self.entry:initialise();
self.entry:instantiate();
self.entry.columnName = type["name"];
self.entry.type = type["type"];
self.entry.tableName = self.tableName;
if type["type"] == "INTEGER" then
self.entry:setOnlyNumbers(true);
end
self.entry.onTextChange = ISWhitelistTable.onFilterChange;
self.entry.target = self;
self:addChild(self.entry);
table.insert(self.filters, self.entry);
end
if type["type"] == "BOOLEAN" then
self.combo = ISComboBox:new(10, self.datas.x + self.datas.height + 85, size, entryHgt, nil,nil);
self.combo:initialise();
self:addChild(self.combo);
self.combo:addOption("");
self.combo:addOption("true");
self.combo:addOption("false");
self.combo.type = type["type"];
self.combo.columnName = type["name"];
self.combo.onChange = ISWhitelistTable.onFilterChange;
self.combo.target = self;
self.combo.tableName = self.tableName;
self.combo.isComboBox = true;
table.insert(self.filters, self.combo);
end
end
end
end
function ISWhitelistTable.onNbrPerPageChange(entry)
local view = ISWhitelistViewer.instance.panel:getView(entry.tableName);
view.entriesPerPages = tonumber(entry:getInternalText());
if view.entriesPerPages == nil then view.entriesPerPages = 1; end
if #view.filters > 0 then
view.onFilterChange(view.filters[1]);
end
end
function ISWhitelistTable:clearFilters()
for _,v in ipairs(self.filters) do
if v.type =="BOOLEAN" then
v.selected = 0;
elseif v.type == "INTEGER" or v.type == "TEXT" then
v:setText("");
end
end
end
function ISWhitelistTable.onFilterChange(entry, combo)
local view = ISWhitelistViewer.instance.panel:getView(entry.tableName)
local filterTxt = "";
local columnName = entry.columnName;
if combo then
if combo.selected == 2 then
filterTxt = "true";
elseif combo.selected == 3 then
filterTxt = "false";
end
columnName = combo.columnName;
else
filterTxt = entry:getInternalText();
end
view.datas:clear();
view.columnSize = {};
view.filtered = string.trim(filterTxt) ~= "";
local allPagesFilter = {};
local data = {};
local newPage = ArrayList.new();
view.pages = {};
local size = 0;
view.totalResult = 0;
for _,v in ipairs(view.fullPages) do
for i=0, v:size()-1 do
local dbResult = v:get(i);
data.datas = {};
local add = true;
for j=0, dbResult:getColumns():size() - 1 do
local colName = dbResult:getColumns():get(j);
local value = dbResult:getValues():get(colName);
if filterTxt and filterTxt ~= "" and (colName == columnName and not luautils.stringStarts(string.lower(value), string.lower(filterTxt))) then
add = false;
end
data.datas[colName] = value;
if add then
local currentSize = view.columnSize[colName];
if not currentSize then currentSize = 0; end
if currentSize < getTextManager():MeasureStringX(UIFont.Large, dbResult:getValues():get(colName)) + 5 then
currentSize = getTextManager():MeasureStringX(UIFont.Large, dbResult:getValues():get(colName)) + 5;
end
if currentSize < getTextManager():MeasureStringX(UIFont.Large, colName) + 5 then
currentSize = getTextManager():MeasureStringX(UIFont.Large, colName) + 5;
end
if currentSize >= 200 then currentSize = 200; end
view.columnSize[colName] = currentSize;
else
local currentSize = view.columnSize[colName];
if not currentSize then
view.columnSize[colName] = 100;
end
end
end
if add then
size = size + 1;
view.totalResult = view.totalResult + 1;
newPage:add(dbResult);
if #allPagesFilter == 0 then
view.datas:addItem(data.datas["username"], data);
end
end
if size >= view.entriesPerPages then
table.insert(allPagesFilter, newPage);
newPage = ArrayList.new();
size = 0;
end
data = {};
end
end
if size > 0 then
table.insert(allPagesFilter, newPage);
end
view.pages = allPagesFilter;
view:doPagesButtons();
end
function ISWhitelistTable:clear()
self.totalResult = 0;
self.datas:clear();
self.columnSize = {};
self.pages = {};
self.fullPages = {};
self.loading = true;
end
function ISWhitelistTable:doPagesButtons()
local pagesNbr = #self.pages;
if pagesNbr == 0 then
pagesNbr = 1;
self.nextPage.enable = false;
self.prePage.enable = false;
end
if pagesNbr > 1 then
self.nextPage.enable = true;
self.prePage.enable = true;
end
self.currentPage = 1;
self.pageLbl.name = "1/" .. pagesNbr;
end
function ISWhitelistTable:onOptionPage(button, x, y)
if button.internal == "NEXT" then
self.currentPage = self.currentPage + 1;
if self.currentPage > #self.pages then
self.currentPage = #self.pages;
end
self.pageLbl.name = self.currentPage .. "/" .. #self.pages;
self.datas:clear();
self:computeResult(self.pages[self.currentPage], self);
end
if button.internal == "PREVIOUS" then
self.currentPage = self.currentPage - 1;
if self.currentPage < 1 then
self.currentPage = 1;
end
self.pageLbl.name = self.currentPage .. "/" .. #self.pages;
self.datas:clear();
self:computeResult(self.pages[self.currentPage], self);
end
end
function ISWhitelistTable:computeResult(datas)
local data = {};
self.columnSize = {};
for i=0, datas:size()-1 do
local dbResult = datas:get(i);
data.datas = {};
for j=0, dbResult:getColumns():size() - 1 do
local colName = dbResult:getColumns():get(j);
data.datas[colName] = dbResult:getValues():get(colName);
local currentSize = self.columnSize[colName];
if not currentSize then currentSize = 0; end
if currentSize < getTextManager():MeasureStringX(UIFont.Large, dbResult:getValues():get(colName)) + 5 then
currentSize = getTextManager():MeasureStringX(UIFont.Large, dbResult:getValues():get(colName)) + 5;
end
if currentSize < getTextManager():MeasureStringX(UIFont.Large, colName) + 5 then
currentSize = getTextManager():MeasureStringX(UIFont.Large, colName) + 5;
end
if currentSize >= 200 then currentSize = 200; end
self.columnSize[colName] = currentSize;
end
self.datas:addItem(data.datas["username"], data);
data = {};
end
end
ISWhitelistTable.getTableResult = function(datas, rowId, tableName)
local view = ISWhitelistViewer.instance.panel:getView(tableName)
view.loading = false;
if datas:size() > 0 then
if rowId == 0 then
view.totalResult = 0;
view.datas:clear();
view.columnSize = {};
view.pages = {};
end
view.totalResult = view.totalResult + datas:size();
table.insert(view.pages, datas);
table.insert(view.fullPages, datas);
view.pageLbl.name = "1/" .. #view.pages;
if rowId == 0 then
view:computeResult(datas);
end
view:doPagesButtons();
end
end
function ISWhitelistTable:drawDatas(y, item, alt)
local a = 0.9;
if self.selected == item.index then
self:drawRect(0, (y), self:getWidth(), self.itemheight, 0.3, 0.7, 0.35, 0.15);
end
if alt then
self:drawRect(0, (y), self:getWidth(), self.itemheight, 0.3, 0.6, 0.5, 0.5);
end
self:drawRectBorder(0, (y), self:getWidth(), self.itemheight, a, self.borderColor.r, self.borderColor.g, self.borderColor.b);
local x = 10;
if self.parent and self.parent.columns then
for name, type in pairs(self.parent.columns) do
if type["name"] ~= "id" and type["name"] ~= "moderator" then
self:drawText(item.item.datas[type["name"]], x, y + 2, 1, 1, 1, a, self.font);
self:drawRect(x - 10, y - 1, 1, self.itemheight,1,self.borderColor.r, self.borderColor.g, self.borderColor.b);
-- self:drawText(item.text, x, y + 2, 1, 1, 1, a, self.font);
if self.parent.parent.activeView and self.parent.parent.activeView.columnSize[type["name"]] then
x = x + self.parent.parent.activeView.columnSize[type["name"]];
else
x = x + 100;
end
end
end
end
return y + self.itemheight;
end
Events.OnGetTableResult.Add(ISWhitelistTable.getTableResult);
|
object_tangible_wearables_necklace_necklace_deepspace_rebel_wke_m = object_tangible_wearables_necklace_shared_necklace_deepspace_rebel_wke_m:new {
}
ObjectTemplates:addTemplate(object_tangible_wearables_necklace_necklace_deepspace_rebel_wke_m, "object/tangible/wearables/necklace/necklace_deepspace_rebel_wke_m.iff")
|
WireToolSetup.setCategory("Input, Output")
WireToolSetup.open("button", "Button", "gmod_wire_button", nil, "Buttons")
if CLIENT then
language.Add("tool.wire_button.name", "Button Tool (Wire)")
language.Add("tool.wire_button.desc", "Spawns a button for use with the wire system.")
language.Add("WireButtonTool_toggle", "Toggle")
language.Add("WireButtonTool_entityout", "Output Entity")
language.Add("WireButtonTool_value_on", "Value On:")
language.Add("WireButtonTool_value_off", "Value Off:")
TOOL.Information = {
{
name = "left",
text = "Create/Update " .. TOOL.Name
}
}
end
WireToolSetup.BaseLang()
WireToolSetup.SetupMax(20)
if SERVER then
ModelPlug_Register("button")
function TOOL:GetConVars()
return self:GetClientNumber("toggle") ~= 0, self:GetClientNumber("value_off"), self:GetClientNumber("value_on"), self:GetClientInfo("description"), self:GetClientNumber("entityout") ~= 0
end
-- Uses default WireToolObj:MakeEnt's WireLib.MakeWireEnt function
end
TOOL.ClientConVar = {
model = "models/props_c17/clock01.mdl",
model_category = "button",
toggle = "0",
value_off = "0",
value_on = "1",
description = "",
entityout = "0"
}
function TOOL.BuildCPanel(panel)
WireToolHelpers.MakePresetControl(panel, "wire_button")
ModelPlug_AddToCPanel_Multi(panel, {
button = "Normal",
button_small = "Small"
}, "wire_button", "#Button_Model", 6)
panel:CheckBox("#WireButtonTool_toggle", "wire_button_toggle")
panel:CheckBox("#WireButtonTool_entityout", "wire_button_entityout")
panel:NumSlider("#WireButtonTool_value_on", "wire_button_value_on", -10, 10, 1)
panel:NumSlider("#WireButtonTool_value_off", "wire_button_value_off", -10, 10, 1)
end
|
require("pk_pills")
AddCSLuaFile()
if SERVER then
resource.AddWorkshop("106427033")
include("ppp_include/drivemodes.lua")
end
game.AddParticles("particles/Vortigaunt_FX.pcf")
PrecacheParticleSystem("vortigaunt_beam")
PrecacheParticleSystem("vortigaunt_beam_b")
include("ppp_include/vox_lists.lua")
pk_pills.packStart("Half-Life 2","base","games/16/hl2.png")
include("ppp_include/pill_combine_soldiers.lua")
include("ppp_include/pill_combine_phys_small.lua")
include("ppp_include/pill_combine_phys_large.lua")
include("ppp_include/pill_combine_misc.lua")
include("ppp_include/pill_combine_new.lua")
include("ppp_include/pill_headcrabs.lua")
include("ppp_include/pill_zombies.lua")
include("ppp_include/pill_antlions.lua")
include("ppp_include/pill_wild.lua")
include("ppp_include/pill_resistance_heros.lua")
include("ppp_include/pill_resistance.lua")
include("ppp_include/pill_vorts.lua")
include("ppp_include/pill_birds.lua")
pk_pills.packStart("Fun","fun","icon16/rainbow.png")
include("ppp_include/pill_fun.lua")
include("ppp_include/pill_fun2.lua")
include("ppp_include/pill_fun3.lua")
include("ppp_include/pill_360_noscope.lua")
pk_pills.packStart("Jake","jake","icon16/box.png")
include("ppp_include/pill_jake.lua")
|
return {'pruis','pruisen','pruisisch','pruisische','prudent','prudentie','pruderie','pruik','pruikenbol','pruikenmaker','pruikenstijl','pruikentijd','pruikerig','pruilen','pruiler','pruilerig','pruillip','pruilmond','pruim','pruimbaar','pruimedant','pruimelaar','pruimen','pruimenbomen','pruimenboom','pruimenhout','pruimenjam','pruimenmoes','pruimenmond','pruimenpit','pruimenpluk','pruimensap','pruimentaart','pruimentijd','pruimer','pruimtabak','pruimtomaat','prul','pruldichter','prullaria','prullen','prullenbak','prullenboel','prullenkraam','prullenman','prullenmand','prullenvent','prullenwerk','prullerig','prullerij','prulletje','prullig','prulpoeet','prulschrijver','prulwerk','prune','prunel','prunus','prut','prutoog','pruts','prutsding','prutsen','prutser','prutserig','prutserij','prutswerk','pruttelaar','pruttelarij','pruttelen','pruttelig','prutterig','pruikenkop','prulachtig','prudentieel','pruil','prummel','pruijssers','prudon','pruijs','pruntel','pruijn','pruiksma','pruijsen','prudentiele','pruiken','pruikenbollen','pruikenmakers','pruikerige','pruilde','pruilden','pruilend','pruilerige','pruillipje','pruilt','pruimde','pruimden','pruimedanten','pruimelaars','pruimenmondje','pruimentaarten','pruimers','pruimpje','pruimpjes','pruimt','prullenbakken','prullenmanden','prullerige','prullerigste','prullerijen','prulletjes','prullige','prulligste','prulpoeten','prutogen','prutserige','prutsers','prutst','prutste','prutsten','prutswerkje','prutswerkjes','pruttel','pruttelaars','pruttelde','pruttelden','pruttelt','prutterige','pruderieen','pruimenpitten','pruimtomaten','pruldichters','prullenkramen','prullenventen','prullenwerken','prulschrijvers','prulwerken','prunellen','prunussen','prutsdingen','pruttelarijen','pruttelend','pruttelende','pruttelige','prudente','pruilmonden','pruimbare','pruikenkoppen','pruillippen','pruimenmonden','prulachtige','pruilmondje','prullenbakje','pruillipjes','prullenmandje','prutswerken'}
|
package.path = './data/lua/?.lua;' .. package.path
require("sgl")
require("screen/attract/defs")
local __aud_title_volume = 1.0
local __aud_title_loop = 0
local __fade_out_time_sec = 1.5
local __id_snd_title = SGL_SOUND_ID_INVALID
local __id_mov_title = SGL_MOV_ID_INVALID
local __id_sprite_title = SGL_SPRITE_ID_INVALID
local __STATE_PLAYING_NONE = 0
local __STATE_PLAYING_TITLE = 1
local __state_playing = __STATE_PLAYING_TITLE
local __confirmation_fade_out = false
local __confirmation_fade_out_timer = 0
local function __play(state)
-- stop current playing video first
if __state_playing == __STATE_PLAYING_TITLE then
sgl_sprite_activate(__id_sprite_title, false)
sgl_mov_stop(__id_mov_title)
sgl_snd_stop(__id_snd_title)
end
__state_playing = state
if __state_playing == __STATE_PLAYING_TITLE then
sgl_mov_play(__id_mov_title)
sgl_sprite_activate(__id_sprite_title, true)
sgl_snd_play(__id_snd_title)
end
end
local function __load(table_resources, table_args)
if not (table_args["aud_title_volume"] == nil) then
__aud_title_volume = table_args["aud_title_volume"]
end
if not (table_args["aud_title_loop"] == nil) then
__aud_title_loop = table_args["aud_title_loop"]
end
local res_aud_title = table_resources["aud_title"]
local res_mov_title = table_resources["mov_title"]
if res_aud_title == nil then
print("Missing aud_title resource entry")
return false
end
if res_mov_title == nil then
print("Missing mov_title resource entry")
return false
end
local asset_paths = sgl_asset_paths()
res_aud_title = asset_paths["aud"] .. "/" .. res_aud_title
res_mov_title = asset_paths["mov"] .. "/" .. res_mov_title
-- load audio file
__id_snd_title = sgl_snd_create(res_aud_title)
sgl_snd_loop(__id_snd_title, __aud_title_loop)
sgl_snd_volume(__id_snd_title, __aud_title_volume)
-- load title video
-- Use external sound file, not sound from video
__id_mov_title = sgl_mov_create(res_mov_title, false)
-- Loop endless, sound file determines loop count and end
sgl_mov_loop(__id_mov_title, -1)
sgl_mov_volume(__id_mov_title, 0.0)
__id_sprite_title = sgl_sprite_create(sgl_mov_texture(__id_mov_title))
sgl_sprite_pos(__id_sprite_title, 0, 0)
sgl_sprite_dim(__id_sprite_title, sgl_ren_screen_width(), sgl_ren_screen_height())
__play(__STATE_PLAYING_TITLE)
return true
end
local function __unload()
-- title audio
sgl_snd_stop(__id_snd_title)
sgl_snd_destroy(__id_snd_title)
-- title video
sgl_sprite_destroy(__id_sprite_title)
sgl_mov_stop(__id_mov_title)
sgl_mov_destroy(__id_mov_title)
end
local function __update(prev_delta_sec, input_state)
if __confirmation_fade_out then
__confirmation_fade_out_timer = __confirmation_fade_out_timer + prev_delta_sec
if __confirmation_fade_out_timer > __fade_out_time_sec then
-- fade out finished
__confirmation_fade_out = false
else
local fade_perc = (__fade_out_time_sec - __confirmation_fade_out_timer) / __fade_out_time_sec
-- fade out only possible when playing title
sgl_snd_volume(__id_snd_title, fade_perc)
sgl_sprite_alpha(__id_sprite_title, math.floor(fade_perc * 0xFF))
end
else
-- don't process inputs on transition
if input_state.digital[SCREEN_ATTRACT_DI_DEBUG_0] then
__play(__STATE_PLAYING_TITLE)
end
end
if __state_playing == __STATE_PLAYING_TITLE and not sgl_snd_playing(__id_snd_title) then
__play(__STATE_PLAYING_TITLE)
end
end
local function __on_enable()
__play(__STATE_PLAYING_TITLE)
end
local function __on_disable()
__play(__STATE_PLAYING_NONE)
end
local function __on_confirm()
__confirmation_fade_out = true
return true
end
local function __on_transition()
return not __confirmation_fade_out
end
return {
f_load = __load,
f_unload = __unload,
f_update = __update,
f_on_enable = __on_enable,
f_on_disable = __on_disable,
f_on_confirm = __on_confirm,
f_on_transition = __on_transition,
}
|
--[[
Name: MTA:Mario Kart
Filename: CameraHandlerC.lua
Author: Sam@ke
--]]
CameraHandlerC = {}
function CameraHandlerC:constructor(parent)
mainOutput("CameraHandlerC was loaded.")
self.mainClass = parent
self.player = getLocalPlayer()
self.roll = 0
self.fov = 92
self.distance = 6.5
self.angle = 180
self.vehicleCam = "off"
self.camDirection = "forward"
self.camHeight = 2.6
self.maxCamHeight = 10
self.camHeightModifier = 0
self.camModifyingSpeed = 0.35
self.cprx = 0
self.cpry = 0
self.m_LookBackward = bind(self.lookBackward, self)
bindKey(getKeyLookBack(), "down", self.m_LookBackward)
self.m_LookForward = bind(self.lookForward, self)
bindKey(getKeyLookBack(), "up", self.m_LookForward)
end
function CameraHandlerC:update()
if (self.player:isInVehicle() == true) then
setCameraClip(true, false)
self.vehicleCam = "on"
self.playerPos = self.player:getPosition()
self.playerRot = self.player:getRotation()
self.px, self.py, self.pz = self.playerPos.x, self.playerPos.y, self.playerPos.z
self.prx, self.pry, self.prz = self.playerRot.x, self.playerRot.y, self.playerRot.z
if (self.prx > self.cprx) then
self.cprx = self.cprx + 0.1
elseif (self.prx < self.cprx) then
self.cprx = self.cprx - 0.1
end
if (self.pry > self.cpry) then
self.cpry = self.cpry + 0.1
elseif (self.pry < self.cpry) then
self.cpry = self.cpry - 0.1
end
if (self.camDirection == "forward") then
self.x, self.y, self.z = getAttachedPosition(self.px, self.py, self.pz, self.cprx / 25, self.cpry / 25, self.prz, self.distance, self.angle, self.camHeight)
setCameraMatrix(self.x, self.y, self.z + self.camHeightModifier, self.px, self.py, self.pz + self.camHeight / 1.4, self.roll, self.fov)
elseif (self.camDirection == "backward") then
self.x, self.y, self.z = getAttachedPosition(self.px, self.py, self.pz, self.prx, self.pry, self.prz, self.distance / 1.2, 0, self.camHeight)
setCameraMatrix(self.x, self.y, self.z + self.camHeightModifier, self.px, self.py, self.pz + self.camHeight / 1.4, self.roll, self.fov)
end
if (isLineOfSightClear(self.x, self.y, self.z, self.px, self.py, self.pz + self.camHeight / 2, true, true, true, true, true, false, false, nil) == false) then
self.camHeightModifier = self.camHeightModifier + self.camModifyingSpeed
if (self.camHeightModifier >= self.maxCamHeight) then
self.camHeightModifier = self.maxCamHeight
end
else
self.camHeightModifier = self.camHeightModifier - self.camModifyingSpeed
if (self.camHeightModifier <= 0) then
self.camHeightModifier = 0
end
end
else
if (self.vehicleCam == "on") then
setCameraTarget(self.player)
self.vehicleCam = "off"
end
end
end
function CameraHandlerC:lookBackward()
self.camDirection = "backward"
end
function CameraHandlerC:lookForward()
self.camDirection = "forward"
end
function CameraHandlerC:destructor()
unbindKey(getKeyLookBack(), "down", self.m_LookBackward)
unbindKey(getKeyLookBack(), "up", self.m_LookForward)
mainOutput("CameraHandlerC was deleted.")
end
|
local string_value = "some value"
global_string_value = string_value .. " | it`s global"
local num = 4126.356
num2 = num ^ 2
for i = 0, 5 do
num2 = num2 - num
end
print(global_string_value, "\n", num2)
|
local _--[[kAddonName]], addon = ...
addon.tests = {}
local tests = {}
function addon.tests.register(name, func)
table.insert(tests, {name, func})
end
function addon.tests.run()
addon.utils.print('Running %d tests...', #tests)
local failures = 0
local realState = addon.store.getState()
local blankState = { globalCooldown = '0', globalAllowedTime = 0, entries = {} }
local mocks
local function mock(obj, name, value)
table.insert(mocks, 1, {obj, name, obj[name]})
obj[name] = value
end
for _, test in ipairs(tests) do
addon.store.dispatch({ name = 'setState', state = blankState })
mocks = {}
local name = test[1]
local func = test[2]
local function onError(err)
_G.geterrorhandler()(('%s (in test: %s)'):format(err, name))
end
local success = xpcall(func, onError, mock)
if not success then
failures = failures + 1
end
for _, record in ipairs(mocks) do
record[1][record[2]] = record[3]
end
end
addon.utils.print('Ran %d tests with %d failures.', #tests, failures)
addon.store.dispatch({ name = 'setState', state = realState })
end
function addon.tests.testEvent(mock, conditionGroup, eventArgs)
local callCount = 0
local function fakeRunEntry(entryIndex)
callCount = callCount + 1
assert(entryIndex == 1)
end
mock(addon.actions, 'runEntry', fakeRunEntry)
addon.store.dispatch({
name = 'createEntry',
conditionGroups = {conditionGroup},
})
addon.events.trigger(unpack(eventArgs))
assert(callCount == 1)
end
|
function guiComboBoxAdjustHeight(comboBox, itemCount)
if not scheck("u:element:gui-combobox,?n") then return false end
if not itemCount then itemCount = 1 end
local width = guiGetSize(comboBox, false)
return guiSetSize(comboBox, width, itemCount * 14 + 38, false)
end
|
version https://git-lfs.github.com/spec/v1
oid sha256:4f341b8f8c53dfd0da805b493eb8fcf1b6873be97dda9660b451794baddcaf66
size 579
|
local std = require('deviant')
local web = require('web')
local json = require('cjson')
local _M = { version = '0.1' }
local defaults = { socket = '/var/run/docker.sock', APIversion = '/v1.28' }
local API_URL = function (opts)
local opts = std.mergeTables(defaults, opts)
return "unix:" .. opts.socket .. ":" .. opts.APIversion
end
local API = { create = [[
{
"Hostname": "", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": true,
"AttachStderr": true, "Tty": false,
"OpenStdin": false, "StdinOnce": false,
"Cmd": {{cmd}},
"Image": "{{image}}",
"HostConfig": {
"Binds": {{binds}},
"PublishAllPorts": false,
"Privileged": {{privileged}},
"Dns": [ "8.8.8.8" ]
}
}
]]
}
local list = function()
local url = API_URL() .. '/containers/json'
local res, err = web.request(url, nil, { timeout = 90000 })
if res then
if res.status == 200 then
return res.body
else
err = res.body
end
end
return nil, err
end
local create = function(containerArgsTable)
local defaults = { privileged = 'false', binds = '', cmd = '', image = '' }
local opts = std.mergeTables(defaults, containerArgsTable)
opts.cmd = json.encode(opts.cmd)
opts.binds = json.encode(opts.binds)
local args = string.gsub(API.create,'{{(.-)}}', opts)
local url = API_URL() .. '/containers/create'
local res, err = web.request(url, { method = "POST", headers = { ['Content-Type'] = 'application/json' }, body = args }, { timeout = 90000 })
if res then
if res.status == 201 then
local response = json.decode(res.body)
return response.Id
else
err = res.body
end
end
return nil, err
end
local start = function(id)
local url = API_URL() .. '/containers/' .. id .. '/start'
local res, err = web.request(url, { method = "POST" }, { timeout = 90000 })
if res then
if res.status == 204 then
return true
else
err = res.body
end
end
return nil, err
end
local wait = function(id)
local url = API_URL() .. '/containers/' .. id .. '/wait'
local res, err = web.request(url, { method = "POST" }, { timeout = 90000 })
if res then
if res.status == 200 then
return true
else
err = res.body
end
end
return nil, err
end
local logs = function(id)
local url = API_URL() .. '/containers/' .. id .. '/logs?stdout=1'
local res, err = web.request(url, nil, { timeout = 90000 })
if res then
if res.status == 200 then
local body = string.gsub(res.body, '\1%z%z%z%z%z%z.','')
return body
else
err = res.body
end
end
return nil, err
end
local kill = function(id)
local url = API_URL() .. '/containers/' .. id .. '?force=1'
local res, err = web.request(url, { method = "DELETE" }, { timeout = 90000 })
if res then
if res.status == 204 then
return true
else
err = res.body
end
end
return nil, err
end
_M.list = list
_M.create = create
_M.start = start
_M.wait = wait
_M.logs = logs
_M.kill = kill
return _M
|
object_draft_schematic_food_beastfood_dry_fruit_substitute = object_draft_schematic_food_shared_beastfood_dry_fruit_substitute:new {
}
ObjectTemplates:addTemplate(object_draft_schematic_food_beastfood_dry_fruit_substitute, "object/draft_schematic/food/beastfood_dry_fruit_substitute.iff")
|
---
--- math.lua
---
--- Copyright (C) 2018-2019 Xrysnow. All rights reserved.
---
--local math = math
local pi = math.pi
local pix2 = math.pi * 2
local abs = math.abs
local acos = math.acos
local asin = math.asin
local atan = math.atan
local atan2 = math.atan2
local ceil = math.ceil
local cos = math.cos
local cosh = math.cosh
local deg = math.deg
local exp = math.exp
local floor = math.floor
local fmod = math.fmod
local frexp = math.frexp
local ldexp = math.ldexp
local log = math.log
local log10 = math.log10
local max = math.max
local min = math.min
local modf = math.modf
local pow = math.pow
local rad = math.rad
local random = math.random
local randomseed = math.randomseed
local sin = math.sin
local sinh = math.sinh
local sqrt = math.sqrt
local tan = math.tan
local tanh = math.tanh
if not math.cbrt then
---@param v number
---@return number
function math.cbrt(v)
return pow(v, 1 / 3)
end
end
if not math.clamp then
---@param v number
---@param lo number
---@param hi number
---@return number
function math.clamp(v, lo, hi)
return min(hi, max(v, lo))
end
end
if not math.hypot then
---@param v1 number
---@param v2 number
---@return number
function math.hypot(v1, v2)
return sqrt(v1 * v1 + v2 * v2)
end
end
if not math.lerp then
---@param v1 number
---@param v2 number
---@param a number
---@return number
function math.lerp(v1, v2, a)
return v1 + (v2 - v1) * a
end
end
if not math.remainder then
---C++ std::remainder
---C# Math.IEEERemainder
---@param v1 number
---@param v2 number
---@return number
function math.remainder(v1, v2)
return v1 - v2 * math.round(v1 / v2)
end
end
if not math.round then
---@param v number
---@return number
function math.round(v)
local f, c = floor(v), ceil(v)
if v - f < c - v then
return f
else
return c
end
end
end
--- solve:
--- a1 x + b1 y = c1
--- a2 x + b2 y = c2
---@return number,number,boolean
function math.solveLiner(a1, b1, c1, a2, b2, c2)
local den = a2 * b1 - a1 * b2
return (c2 * b1 - c1 * b2) / den, (c1 * a2 - c2 * a1) / den, den == 0
end
--------------------------------------------------
-- from Microsoft.Xna.Framework.MathHelper
--------------------------------------------------
---C# MathHelper.Barycentric
---@param v1 number
---@param v2 number
---@param v3 number
---@param a1 number
---@param a2 number
---@return number
function math.barycentric(v1, v2, v3, a1, a2)
return (v1 + (a1 * (v2 - v1))) + (a2 * (v3 - v1))
end
---C# MathHelper.SmoothStep
---@param v1 number
---@param v2 number
---@param a number
---@return number
function math.smoothstep(v1, v2, a)
a = math.clamp(a, 0, 1)
return math.lerp(v1, v2, a * a * (3 - 2 * a))
end
---C# MathHelper.WrapAngle
---@return number
---@param v number
function math.wrapangle(v)
local a = math.remainder(v, pix2)
if a <= -pi then
return a + pix2
elseif a > pi then
return a - pix2
else
return a
end
end
--------------------------------------------------
-- metrics
--------------------------------------------------
function math.EuclideanDistance(v1, v2)
local sum = 0
for i = 1, #v1 do
local d = v1[i] - v2[i]
sum = sum + d * d
end
return sqrt(sum)
end
function math.ManhattanDistance(v1, v2)
local sum = 0
for i = 1, #v1 do
sum = sum + abs(v1[i] - v2[i])
end
return sum
end
function math.ChebyshevDistance(v1, v2)
local ret = 0
for i = 1, #v1 do
local d = abs(v1[i] - v2[i])
if d > ret then
ret = d
end
end
return ret
end
function math.MinkowskiDistance(v1, v2, p)
local sum = 0
for i = 1, #v1 do
sum = sum + pow(abs(v1[i] - v2[i]), p)
end
return pow(sum, 1 / p)
end
--------------------------------------------------
-- special number
--------------------------------------------------
local inf = 1 / 0
local ninf = -1 / 0
--TODO: cdata float
if not math.isinf then
--- v == +/-inf
function math.isinf(v)
return v == inf or v == ninf
end
end
if not math.isfinite then
--- v is not positive infinity, negative infinity, or NaN
function math.isfinite(v)
return v ~= inf and v ~= ninf and v == v
end
end
if not math.isnan then
function math.isnan(v)
return v ~= v
end
end
|
local spell, super = Class(Spell, "ultimate_heal")
function spell:init()
super:init(self)
-- Display name
self.name = "UltimatHeal"
-- Name displayed when cast (optional)
self.cast_name = "ULTIMATEHEAL"
-- Battle description
self.effect = "Best\nhealing"
-- Menu description
self.description = "Heals 1 party member to the\nbest of Susie's ability."
-- TP cost
self.cost = 100
-- Target mode (ally, party, enemy, enemies, or none)
self.target = "ally"
-- Tags that apply to this spell
self.tags = {"heal"}
end
function spell:onCast(user, target)
target:heal(user.chara:getStat("magic") + 1)
end
return spell
|
local SPDict = require(game.ReplicatedStorage.Shared.SPDict)
local SongErrorParser = {}
local __tmpctr = 4
local function track_time_to_hash(p_track,p_time)
return string.format("%d_%d",p_track,p_time)
end
function SongErrorParser:scan_audiodata_for_errors(audio_data)
local tracked_notes = SPDict:new()
for i=1,#audio_data.HitObjects do
local itr_hitobj = audio_data.HitObjects[i]
local track = itr_hitobj.Track
if track == nil then
track = __tmpctr
__tmpctr = __tmpctr + 1
end
local itr_hitobj_hash = track_time_to_hash(itr_hitobj.Time,track)
if tracked_notes:contains(itr_hitobj_hash) then
error(string.format(
"SongErrorParser - Likely duplicate time/track note for (%s) at note[%d](Type[%d] Time[%d] Track[%d])",
audio_data.AudioFilename,
i,
itr_hitobj.Type,
itr_hitobj.Time,
track
))
end
tracked_notes:add(itr_hitobj_hash,true)
if itr_hitobj.Type == 2 then
local itr_hitobj_end_hash = track_time_to_hash(itr_hitobj.Time + itr_hitobj.Duration,track)
if tracked_notes:contains(itr_hitobj_end_hash) then
error(string.format(
"SongErrorParser - Likely duplicate time/track (HELD NOTE END) for (%s) at note[%d](Type[%d] Time[%d] Track[%d])",
audio_data.AudioFilename,
i,
itr_hitobj.Type,
itr_hitobj.Time,
track
))
end
tracked_notes:add(itr_hitobj_end_hash,true)
end
end
end
return SongErrorParser
|
AddCSLuaFile()
ENT.Type = "anim"
function ENT:Initialize()
self:SetModel("models/props_junk/PopCan01a.mdl")
if SERVER then
ParticleEffect("advisor_psychic_shield_idle",self:GetPos(),Angle(0,0,0),self)
self.sound = CreateSound(self,"ambient/machines/combine_shield_touch_loop1.wav")
self.sound:Play()
timer.Simple(2,function()
if !IsValid(self) then return end
self:DoDamage()
end)
timer.Simple(5,function()
if !IsValid(self) then return end
self:Remove()
end)
end
end
function ENT:DoDamage()
local entsInside = ents.FindInSphere(self:GetPos(),300)
local damage = DamageInfo()
damage:SetDamage(50)
damage:SetDamageType(DMG_DISSOLVE)
damage:SetAttacker(self:GetOwner())
damage:SetInflictor(self)
for k,v in pairs(entsInside) do
if v.GetPillUser and v:GetPillUser()==self:GetOwner() then continue end
v:TakeDamageInfo(damage)
end
self:EmitSound("npc/advisor/advisorheadvx04.wav")
end
function ENT:Think()
if SERVER then
local entsInside = ents.FindInSphere(self:GetPos(),300)
for k,v in pairs(entsInside) do
if v.GetPillUser and v:GetPillUser()==self:GetOwner() then continue end
local phys = v:GetPhysicsObject()
if IsValid(phys) then
phys:ApplyForceCenter(phys:GetMass()*Vector(0,0,120))
end
end
self:NextThink(CurTime()+.1)
return true
end
end
function ENT:OnRemove()
if SERVER then
self.sound:Stop()
self:EmitSound("npc/advisor/advisor_blast6.wav")
end
end
function ENT:Draw()
end
|
local SoundManager = {}
SoundManager.sounds = {}
function SoundManager:add(id, state)
SoundManager.sounds[id] = state
end
function SoundManager:remove(id)
SoundManager.sounds[id] = nil
end
function SoundManager:load()
SoundManager.sounds.intro = love.audio.newSource("res/sounds/intro.mp3", "static")
SoundManager.sounds.vibration = love.audio.newSource("res/sounds/vibration.mp3", "static")
end
function SoundManager:get(id)
return SoundManager.sounds[id]
end
return SoundManager
|
local R = require "rigel"
local RM = require "generators.modules"
local ffi = require("ffi")
local types = require("types")
local S = require("systolic")
--local cstdio = terralib.includec("stdio.h")
--local cstring = terralib.includec("string.h")
local harness = require "generators.harness"
local C = require "generators.examplescommon"
local f = require "fixed"
local soc = require "generators.soc"
local edgeTerra={}
if terralib~=nil then edgeTerra=require("edge_terra") end
W = 640
H = 480
T = 2
ITYPE = types.array2d( types.uint(8), 8 )
OTYPE = types.array2d( types.array2d(types.uint(8),4), 2 )
--local TTYPE = types.array2d( types.uint(32), 4 ):makeConst()
local TTYPE = types.uint(32)
local TAPVALUE =10
--soc.taps = R.newGlobal("taps","input",TTYPE,TAPVALUE)
local taps = soc.regStub{taps={TTYPE,TAPVALUE}}:instantiate("taps")
taps.extern = true
TAPS = false
if string.find(arg[0],"taps") then TAPS=true end
--------------
-- blur kernel
TConvWidth = 3
local gauss = C.gaussian(TConvWidth,3)
local convolvefn = C.convolveConstant( types.uint(8), TConvWidth, TConvWidth, gauss, 6 )
--------------
-- edge
local ty = types.uint(8)
local inp = f.parameter("nmsinp", types.array2d(ty,3,3))
local dx = inp:index(2,1):lift(0):toSigned()-inp:index(0,1):lift(0):toSigned()
dx = dx:abs()
local dy = inp:index(1,2):lift(0):toSigned()-inp:index(1,0):lift(0):toSigned()
dy = dy:abs()
local mag = (dx+dy):truncate(8):lower()
local edge = mag:toRigelModule("edgefn")
--------------
-- nms
local ty = types.uint(8)
local nms = RM.lift("nms", types.array2d(ty,3,3),ty,10,
function(inp)
local nms_N = S.gt(S.index(inp,1,1),S.index(inp,1,0))
local nms_S = S.ge(S.index(inp,1,1),S.index(inp,1,2))
local nms_E = S.gt(S.index(inp,1,1),S.index(inp,2,1))
local nms_W = S.ge(S.index(inp,1,1),S.index(inp,0,1))
local nmsout = S.__and(S.__and(nms_N,nms_S),S.__and(nms_E,nms_W))
return S.select(nmsout, S.constant(255,types.uint(8)), S.constant(0,types.uint(8)) )
end,
function() return edgeTerra.nms end)
--------------
local function makeThresh()
local inptype = types.tuple{types.uint(8),types.uint(32)}
local thfn = RM.lift("thfn", inptype, types.array2d(types.uint(8),4),0,
function(inp)
local inpData = S.index( inp, 0 )
local inpTap = S.index( inp, 1 )
local c_one = S.constant({255,255,255,0},types.array2d(types.uint(8),4))
local c_zero = S.constant({0,0,0,0},types.array2d(types.uint(8),4))
return S.select(S.gt(inpData,inpTap), c_one, c_zero )
end,
function() return edgeTerra.thresh end)
if TAPS==false then
local THRESH=10
local inp = R.input( types.rv(types.Par(types.uint(8))) )
local out = R.apply("rr", thfn, R.concat("rof",{inp,R.constant("Rt",THRESH,types.uint(32))}))
thfn = RM.lambda("EWR",inp,out)
end
return RM.makeHandshake(RM.map(thfn,T))
end
local thfn = makeThresh()
--------------
local BW = (TConvWidth-1)/2
local blurfn = C.stencilKernelPadcrop( types.uint(8), W,H,T,BW,BW,BW,BW,0,convolvefn,false)
local edgefn = C.stencilKernelPadcrop( types.uint(8), W,H,T,1,1,1,1,0,edge,false)
local nmsfn = C.stencilKernelPadcrop( types.uint(8), W,H,T,1,1,1,1,0,nms,false)
local FNTYPE
FNTYPE = ITYPE
local inp = R.input(R.Handshake(FNTYPE))
local out
local inptaps
out = inp
local out = R.apply("incrate", RM.changeRate(types.uint(8),1,8,2), out )
local out = R.apply("bf",blurfn,out)
local out = R.apply("ef",edgefn,out)
if TAPS then
out = R.apply("oack",RM.makeHandshake(C.packTapBroad(types.array2d(types.uint(8),T),TTYPE,taps.taps,T)),out)
out = R.apply("SOS",RM.makeHandshake(RM.SoAtoAoS(2,1,{types.uint(8),TTYPE})),out)
end
local out = R.apply("nf",thfn,out)
local hsfn = RM.lambda("hsfn",inp,out)
if TAPS then
harness{ outFile="edge_taps", fn=hsfn, inFile="ov7660_1chan.raw", tapType=TTYPE, tapValue=TAPVALUE, inSize={W,H}, outSize={W,H} }
else
harness{ outFile="edge", fn=hsfn, inFile="ov7660_1chan.raw", inSize={W,H}, outSize={W,H} }
end
|
---------------------------------------------------------------------------------------------------
-- -= Grid =-
---------------------------------------------------------------------------------------------------
local Grid = {}
Grid.__index = Grid
-- Creates and returns a new grid
function Grid:new()
local grid = {}
grid.cells = {}
grid.cells.mt = {__mode = ""}
return setmetatable(grid, Grid)
end
-- Weakens the grid's cells so the garbage collecter can delete their contents if they have no
-- other references.
function Grid:weaken()
self.cells.mt.__mode = "v"
for key,row in pairs(self.cells) do
setmetatable(row,self.cells.mt)
end
end
-- Unweakens the grid
function Grid:unweaken()
self.cells.mt.__mode = ""
for key,row in pairs(self.cells) do
setmetatable(row,self.cells.mt)
end
end
-- Gets the value of a single cell
function Grid:get(x,y)
return self.cells[x] and self.cells[x][y] or nil
end
-- Sets the value of a single cell
function Grid:set(x,y,value)
if not self.cells[x] then
self.cells[x] = setmetatable({}, self.cells.mt)
end
self.cells[x][y] = value
end
-- Sets all of the cells in an area to the same value
function Grid:setArea(startX, startY, endX, endY, value)
for x = startX,endX do
for y = startY,endY do
self:set(x,y,value)
end
end
end
-- Iterate over all values
function Grid:iterate()
local x, row = next(self.cells)
local y, val
return function()
repeat
y,val = next(row,y)
if y == nil then x,row = next(self.cells, x) end
until (val and x and y and type(x)=="number") or (not val and not x and not y)
return x,y,val
end
end
-- Iterate over a rectangle shape
function Grid:rectangle(startX, startY, endX, endY, includeNil)
local x, y = startX, startY
return function()
while y <= endY do
while x <=endX do
x = x+1
if self(x-1,y) ~= nil or includeNil then
return x-1, y, self(x-1,y)
end
end
x = startX
y = y+1
end
return nil
end
end
-- Iterate over a line. Set noDiag to true to keep from traversing diagonally.
function Grid:line(startX, startY, endX, endY, noDiag, includeNil)
local dx = math.abs(endX - startX)
local dy = math.abs(endY - startY)
local x = startX
local y = startY
local incrX = endX > startX and 1 or -1
local incrY = endY > startY and 1 or -1
local err = dx - dy
local err2 = err*2
local i = 1+dx+dy
local rx,ry,rv
local checkX = false
return function()
while i>0 do
rx,ry,rv = x,y,self(x,y)
err2 = err*2
while true do
checkX = not checkX
if checkX == true or not noDiag then
if err2 > -dy then
err = err - dy
x = x + incrX
i = i-1
if noDiag then break end
end
end
if checkX == false or not noDiag then
if err2 < dx then
err = err + dx
y = y + incrY
i = i-1
if noDiag then break end
end
end
if not noDiag then break end
end
if rx == endX and ry == endY then i = 0 end
if rv ~= nil or includeNil then return rx,ry,rv end
end
return nil
end
end
-- Iterates over a circle of cells
function Grid:circle(cx, cy, r, includeNil)
local x,y
x = x or cx-r
return function()
repeat
y = y == nil and cy or y <= cy and y-1 or y+1
while ((cx-x)*(cx-x)+(cy-y)*(cy-y)) >= r*r do
if x > cx+r then return nil end
x = x + (y < cy and 0 or 1)
y = cy + (y < cy and 1 or 0)
end
until self(x,y) ~= nil or includeNil
return x,y,self(x,y)
end
end
-- Cleans the grid of empty rows.
function Grid:clean()
for key,row in pairs(self.cells) do
if not next(row) then self.cells[key] = nil end
end
end
-- This makes calling the grid as a function act like Grid.get.
Grid.__call = Grid.get
-- Returns the grid class
return Grid
--------------------------------------------------------------------------------------
-- Copyright (c) 2011 Casey Baxter
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
-- Except as contained in this notice, the name(s) of the above copyright holders
-- shall not be used in advertising or otherwise to promote the sale, use or
-- other dealings in this Software without prior written authorization.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
|
-------------------------------------------------
-- Civilopedia screen
-------------------------------------------------
include( "InstanceManager" );
include( "IconSupport" );
-- table.sort method for sorting alphabetically.
function Alphabetically(a, b)
return Locale.Compare(a.entryName, b.entryName) == -1;
end
local portraitSize = 256;
local buttonSize = 64;
-- MOD - Advanced Civilopedia
local smallbuttonSize = 48;
-- various sizes of elements
local wideOuterFrameWidth = 436;
local wideInnerFrameWidth = 440;
local superWideOuterFrameWidth = 636;
local superWideInnerFrameWidth = 640;
local narrowOuterFrameWidth = 204;
local narrowInnerFrameWidth = 208;
local textPaddingFromInnerFrame = 34;
local offsetsBetweenFrames = 4;
local quoteButtonOffset = 60;
local numberOfButtonsPerRow = 3;
local numberOfButtonsPerRowWide = 6;
local buttonPadding = 8;
local buttonPaddingTimesTwo = 16;
-- textures that will be used a lot
local defaultErrorTextureSheet = "TechAtlasSmall.dds";
local addToList = 1;
local dontAddToList = 0;
-- defines for the various categories of topics
local CategoryHomePage = 1;
local CategoryGameConcepts = 2;
local CategoryTech = 3;
local CategoryUnits = 4;
local CategoryPromotions = 5;
local CategoryBuildings = 6;
local CategoryWonders = 7;
local CategoryPolicies = 8;
local CategoryPeople = 9;
local CategoryCivilizations = 10;
local CategoryCityStates = 11;
local CategoryTerrain = 12;
local CategoryResources = 13;
local CategoryImprovements = 14;
local CategoryBeliefs = 15;
local CategoryWorldCongress = 16;
local numCategories = 16;
local selectedCategory = CategoryHomePage;
local CivilopediaCategory = {};
local currentTopic = 0;
local endTopic = 0;
local listOfTopicsViewed = {};
local sortedList = {};
local otherSortedList = {};
local searchableTextKeyList = {};
local searchableList = {};
local categorizedList = {};
local absurdlyLargeNumTopicsInCategory = 10000;
local homePageOfCategoryID = 9999;
-- MOD - Advanced Civilopedia
local colorWhite = {x=1, y=1, z=1, w=1 };
local colorBlack = {x=0, y=0, z=0, w=1 };
local colorRed = {x=1, y=0, z=0, w=1 };
local colorSkyBlue = {x=0, y=0.25, z=0.95, w=1 };
-- MOD - Advanced Civilopedia
-- This list is for the order of leader flavors, if you change it, make sure that there being no nil value in the corresponding table!
local flavorList = { 17, 18, 19, 20, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 29, 32, 38, 14, 13, 16, 15, 11, 10, 21, 22, 23, 24, 27, 35, 26, 25, 31, 28, 30, 33, 34, 36, 37 };
-- These projects were more of an implementation detail and not explicit projects
-- that the user can build. So to avoid confusion, we shall ignore them from the pedia.
local projectsToIgnore = {
PROJECT_SS_COCKPIT = true,
PROJECT_SS_STASIS_CHAMBER = true,
PROJECT_SS_ENGINE = true,
PROJECT_SS_BOOSTER = true
};
-- the instance managers
local g_ListItemManager = InstanceManager:new( "ListItemInstance", "ListItemButton", Controls.ListOfArticles );
local g_ListHeadingManager = InstanceManager:new( "ListHeadingInstance", "ListHeadingButton", Controls.ListOfArticles );
local g_PrereqTechManager = InstanceManager:new( "PrereqTechInstance", "PrereqTechButton", Controls.PrereqTechInnerFrame );
local g_GreatWorksManager = InstanceManager:new( "GreatWorksInstance", "GreatWorksButton", Controls.GreatWorksInnerFrame );
local g_ObsoleteTechManager = InstanceManager:new( "ObsoleteTechInstance", "ObsoleteTechButton", Controls.ObsoleteTechInnerFrame );
local g_UpgradeManager = InstanceManager:new( "UpgradeInstance", "UpgradeButton", Controls.UpgradeInnerFrame );
local g_LeadsToTechManager = InstanceManager:new( "LeadsToTechInstance", "LeadsToTechButton", Controls.LeadsToTechInnerFrame );
local g_UnlockedUnitsManager = InstanceManager:new( "UnlockedUnitInstance", "UnlockedUnitButton", Controls.UnlockedUnitsInnerFrame );
local g_UnlockedBuildingsManager = InstanceManager:new( "UnlockedBuildingInstance", "UnlockedBuildingButton", Controls.UnlockedBuildingsInnerFrame );
local g_RevealedResourcesManager = InstanceManager:new( "RevealedResourceInstance", "RevealedResourceButton", Controls.RevealedResourcesInnerFrame );
local g_RequiredResourcesManager = InstanceManager:new( "RequiredResourceInstance", "RequiredResourceButton", Controls.RequiredResourcesInnerFrame );
local g_WorkerActionsManager = InstanceManager:new( "WorkerActionInstance", "WorkerActionButton", Controls.WorkerActionsInnerFrame );
local g_UnlockedProjectsManager = InstanceManager:new( "UnlockedProjectInstance", "UnlockedProjectButton", Controls.UnlockedProjectsInnerFrame );
local g_PromotionsManager = InstanceManager:new( "PromotionInstance", "PromotionButton", Controls.FreePromotionsInnerFrame );
local g_SpecialistsManager = InstanceManager:new( "SpecialistInstance", "SpecialistButton", Controls.SpecialistsInnerFrame );
local g_RequiredBuildingsManager = InstanceManager:new( "RequiredBuildingInstance", "RequiredBuildingButton", Controls.RequiredBuildingsInnerFrame );
local g_LocalResourcesManager = InstanceManager:new( "LocalResourceInstance", "LocalResourceButton", Controls.LocalResourcesInnerFrame );
local g_RequiredPromotionsManager = InstanceManager:new( "RequiredPromotionInstance", "RequiredPromotionButton", Controls.RequiredPromotionsInnerFrame );
local g_RequiredPoliciesManager = InstanceManager:new( "RequiredPolicyInstance", "RequiredPolicyButton", Controls.RequiredPoliciesInnerFrame );
local g_FreeFormTextManager = InstanceManager:new( "FreeFormTextInstance", "FFTextFrame", Controls.FFTextStack );
local g_BBTextManager = InstanceManager:new( "BBTextInstance", "BBTextFrame", Controls.BBTextStack );
local g_LeadersManager = InstanceManager:new( "LeaderInstance", "LeaderButton", Controls.LeadersInnerFrame );
local g_UniqueUnitsManager = InstanceManager:new( "UniqueUnitInstance", "UniqueUnitButton", Controls.UniqueUnitsInnerFrame );
local g_UniqueBuildingsManager = InstanceManager:new( "UniqueBuildingInstance", "UniqueBuildingButton", Controls.UniqueBuildingsInnerFrame );
local g_UniqueImprovementsManager = InstanceManager:new( "UniqueImprovementInstance", "UniqueImprovementButton", Controls.UniqueImprovementsInnerFrame );
local g_CivilizationsManager = InstanceManager:new( "CivilizationInstance", "CivilizationButton", Controls.CivilizationsInnerFrame );
local g_TraitsManager = InstanceManager:new( "TraitInstance", "TraitButton", Controls.TraitsInnerFrame );
local g_FeaturesManager = InstanceManager:new( "FeatureInstance", "FeatureButton", Controls.FeaturesInnerFrame );
local g_ResourcesFoundManager = InstanceManager:new( "ResourceFoundInstance", "ResourceFoundButton", Controls.ResourcesFoundInnerFrame );
local g_TerrainsManager = InstanceManager:new( "TerrainInstance", "TerrainButton", Controls.TerrainsInnerFrame );
local g_ReplacesManager = InstanceManager:new( "ReplaceInstance", "ReplaceButton", Controls.ReplacesInnerFrame );
local g_RevealTechsManager = InstanceManager:new( "RevealTechInstance", "RevealTechButton", Controls.RevealTechsInnerFrame );
local g_ImprovementsManager = InstanceManager:new( "ImprovementInstance", "ImprovementButton", Controls.ImprovementsInnerFrame );
-- MOD - Advanced Civilopedia
local g_UnitFlagAtlasManager = InstanceManager:new( "UnitFlagAtlasInstance", "UnitFlagAtlasButton", Controls.UnitFlagAtlasInnerFrame );
local g_PrereqProjectManager = InstanceManager:new( "PrereqProjectInstance", "PrereqProjectButton", Controls.PrereqProjectInnerFrame );
local g_CivLeaderInfoTextManager = InstanceManager:new( "CivLeaderInfoTextInstance", "CivLeaderInfoTextFrame", Controls.CivLeaderInfoTextStack );
local g_ObsoleteUnitManager = InstanceManager:new( "ObsoleteUnitInstance", "ObsoleteUnitButton", Controls.ObsoleteUnitInnerFrame );
local g_ObsoleteBuildingManager = InstanceManager:new( "ObsoleteBuildingInstance", "ObsoleteBuildingButton", Controls.ObsoleteBuildingInnerFrame );
local g_UnlockedPromotionsManager = InstanceManager:new( "UnlockedPromotionInstance", "UnlockedPromotionButton", Controls.UnlockedPromotionsInnerFrame );
local g_ReplacedByManager = InstanceManager:new( "ReplacedByInstance", "ReplacedByButton", Controls.ReplacedByInnerFrame );
local g_ResourcesProvidedManager = InstanceManager:new( "ResourcesProvidedInstance", "ResourcesProvidedButton", Controls.ResourcesProvidedInnerFrame );
local g_SupportingTechManager = InstanceManager:new( "SupportingTechInstance", "SupportingTechButton", Controls.SupportingTechInnerFrame );
local g_SupportingBuildingManager = InstanceManager:new( "SupportingBuildingInstance", "SupportingBuildingButton", Controls.SupportingBuildingInnerFrame );
local g_SupportingPolicyManager = InstanceManager:new( "SupportingPolicyInstance", "SupportingPolicyButton", Controls.SupportingPolicyInnerFrame );
-- adjust the various parts to fit the screen size
local _, screenSizeY = UIManager:GetScreenSizeVal(); -- Controls.BackDrop:GetSize();
local scrollBarWidth = Controls.ScrollBar:GetSize().x;
local scrollPanelSize = Controls.ScrollPanel:GetSize();
local scrollBarSize = { x = scrollBarWidth; y = screenSizeY - 172; };
Controls.ScrollBar:SetSize( scrollBarSize );
Controls.LeftScrollBar:SetSize( scrollBarSize );
Controls.ScrollBar:SetOffsetVal( 0, 18 );
Controls.LeftScrollBar:SetOffsetVal( 0, 18 );
Controls.DownButton:SetOffsetVal( 0, screenSizeY - 126 - 18 );
Controls.LeftDownButton:SetOffsetVal( 0, screenSizeY - 126 - 18 );
Controls.LeftUpButton:SetOffsetVal( 0, 0 );
scrollPanelSize.y = screenSizeY - 126;
Controls.ScrollPanel:SetSize( scrollPanelSize );
local leftScrollPanelSize = Controls.LeftScrollPanel:GetSize();
leftScrollPanelSize.y = screenSizeY - 126;
Controls.LeftScrollPanel:SetSize( leftScrollPanelSize );
Controls.ScrollPanel:CalculateInternalSize();
Controls.LeftScrollPanel:CalculateInternalSize();
function SetSelectedCategory( thisCategory )
print("SetSelectedCategory("..tostring(thisCategory)..")");
if selectedCategory ~= thisCategory then
selectedCategory = thisCategory;
-- set up tab
Controls.SelectedCategoryTab:SetOffsetVal(47 * (selectedCategory - 1), -10);
Controls.SelectedCategoryTab:SetTexture( CivilopediaCategory[selectedCategory].buttonTexture );
-- set up label for category
Controls.CategoryLabel:SetText( CivilopediaCategory[selectedCategory].labelString );
-- populate the list of entries
if CivilopediaCategory[selectedCategory].DisplayList then
CivilopediaCategory[selectedCategory].DisplayList();
else
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
end
Controls.ListOfArticles:CalculateSize();
Controls.ListOfArticles:ReprocessAnchoring();
end
-- get first entry from list (this will be a special page)
if CivilopediaCategory[selectedCategory].DisplayHomePage then
CivilopediaCategory[selectedCategory].DisplayHomePage();
end
Controls.ScrollPanel:CalculateInternalSize();
Controls.LeftScrollPanel:CalculateInternalSize();
end
-------------------------------------------------------------------------------
-- setup generic stuff for each category
-------------------------------------------------------------------------------
for i = 1, numCategories, 1 do
CivilopediaCategory[i] = {};
CivilopediaCategory[i].tag = i;
CivilopediaCategory[i].buttonClicked = function()
SetSelectedCategory(CivilopediaCategory[i].tag);
end
local buttonName = "CategoryButton"..tostring(i);
Controls[buttonName]:RegisterCallback( Mouse.eLClick, CivilopediaCategory[i].buttonClicked );
end
-------------------------------------------------------------------------------
-- setup the special case stuff for each category
-------------------------------------------------------------------------------
CivilopediaCategory[CategoryHomePage].buttonTexture = "Assets/UI/Art/Civilopedia/CivilopediaTopButtonsHome.dds";
CivilopediaCategory[CategoryGameConcepts].buttonTexture = "Assets/UI/Art/Civilopedia/CivilopediaTopButtonsGameplay.dds";
CivilopediaCategory[CategoryTech].buttonTexture = "Assets/UI/Art/Civilopedia/CivilopediaTopButtonsTechnology.dds";
CivilopediaCategory[CategoryUnits].buttonTexture = "Assets/UI/Art/Civilopedia/CivilopediaTopButtonsUnit.dds";
CivilopediaCategory[CategoryPromotions].buttonTexture = "Assets/UI/Art/Civilopedia/CivilopediaTopButtonsPromotions.dds";
CivilopediaCategory[CategoryBuildings].buttonTexture = "Assets/UI/Art/Civilopedia/CivilopediaTopButtonsBuildings.dds";
CivilopediaCategory[CategoryWonders].buttonTexture = "Assets/UI/Art/Civilopedia/CivilopediaTopButtonsWonders.dds";
CivilopediaCategory[CategoryPolicies].buttonTexture = "Assets/UI/Art/Civilopedia/CivilopediaTopButtonsSocialPolicy.dds";
CivilopediaCategory[CategoryPeople].buttonTexture = "Assets/UI/Art/Civilopedia/CivilopediaTopButtonsGreatPersons.dds";
CivilopediaCategory[CategoryCivilizations].buttonTexture = "Assets/UI/Art/Civilopedia/CivilopediaTopButtonsCivsCityStates.dds";
CivilopediaCategory[CategoryCityStates].buttonTexture = "Assets/UI/Art/Civilopedia/CivilopediaTopButtonsCities.dds";
CivilopediaCategory[CategoryTerrain].buttonTexture = "Assets/UI/Art/Civilopedia/CivilopediaTopButtonsTerrian.dds";
CivilopediaCategory[CategoryResources].buttonTexture = "Assets/UI/Art/Civilopedia/CivilopediaTopButtonsResourcesImprovements.dds";
CivilopediaCategory[CategoryImprovements].buttonTexture = "Assets/UI/Art/Civilopedia/CivilopediaTopButtonsImprovements.dds";
CivilopediaCategory[CategoryBeliefs].buttonTexture = "CivilopediaTopButtonsReligion.dds";
CivilopediaCategory[CategoryWorldCongress].buttonTexture = "CivilopediaTopButtonsWorldCongress.dds";
CivilopediaCategory[CategoryHomePage].labelString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CATEGORY_1_LABEL" );
CivilopediaCategory[CategoryGameConcepts].labelString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CATEGORY_2_LABEL" );
CivilopediaCategory[CategoryTech].labelString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CATEGORY_3_LABEL" );
CivilopediaCategory[CategoryUnits].labelString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CATEGORY_4_LABEL" );
CivilopediaCategory[CategoryPromotions].labelString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CATEGORY_5_LABEL" );
CivilopediaCategory[CategoryBuildings].labelString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CATEGORY_6_LABEL" );
CivilopediaCategory[CategoryWonders].labelString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CATEGORY_7_LABEL" );
CivilopediaCategory[CategoryPolicies].labelString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CATEGORY_8_LABEL" );
CivilopediaCategory[CategoryPeople].labelString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CATEGORY_9_LABEL" );
CivilopediaCategory[CategoryCivilizations].labelString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CATEGORY_10_LABEL" );
CivilopediaCategory[CategoryCityStates].labelString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CATEGORY_11_LABEL" );
CivilopediaCategory[CategoryTerrain].labelString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CATEGORY_12_LABEL" );
CivilopediaCategory[CategoryResources].labelString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CATEGORY_13_LABEL" );
CivilopediaCategory[CategoryImprovements].labelString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CATEGORY_14_LABEL" );
CivilopediaCategory[CategoryBeliefs].labelString = Locale.Lookup("TXT_KEY_PEDIA_CATEGORY_15_LABEL");
CivilopediaCategory[CategoryWorldCongress].labelString = Locale.Lookup("TXT_KEY_PEDIA_CATEGORY_16_LABEL");
CivilopediaCategory[CategoryHomePage].PopulateList = function()
sortedList[CategoryHomePage] = {};
sortedList[CategoryHomePage][1] = {}; -- there is only one section
local tableid = 1;
-- for each major category
for i=1, numCategories,1 do
-- add an entry to a list (localized name, tag, etc.)
local article = {};
local compoundName = "TXT_KEY_PEDIA_CATEGORY_" .. tostring(i) .. "_LABEL" ;
local name = Locale.ConvertTextKey( compoundName );
article.entryName = name;
article.entryID = i;
article.entryCategory = CategoryHomePage;
sortedList[CategoryHomePage][1][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[compoundName] = article;
categorizedList[(CategoryHomePage * absurdlyLargeNumTopicsInCategory) + i] = article;
end
end
CivilopediaCategory[CategoryGameConcepts].PopulateList = function()
sortedList[CategoryGameConcepts] = {};
local GameConceptsList = sortedList[CategoryGameConcepts];
local conceptSections = {
HEADER_CITIES = 1,
HEADER_COMBAT = 2,
HEADER_TERRAIN = 3,
HEADER_RESOURCES = 4,
HEADER_IMPROVEMENTS = 5,
HEADER_CITYGROWTH = 6,
HEADER_TECHNOLOGY = 7,
HEADER_CULTURE = 8,
HEADER_DIPLOMACY = 9,
HEADER_HAPPINESS = 10,
HEADER_FOW = 11,
HEADER_POLICIES = 12,
HEADER_GOLD = 13,
HEADER_ADVISORS = 14,
HEADER_PEOPLE = 15,
HEADER_CITYSTATE = 16,
HEADER_MOVEMENT = 17,
HEADER_AIRCOMBAT = 18,
HEADER_RUBARB = 19,
HEADER_UNITS = 20,
HEADER_VICTORY = 21,
HEADER_ESPIONAGE = 22,
HEADER_RELIGION = 23,
HEADER_TRADE = 24,
HEADER_WORLDCONGRESS = 25,
}
-- Create table.
for i,v in pairs(conceptSections) do
GameConceptsList[v] = {
headingOpen = false,
};
end
-- for each concept
for thisConcept in GameInfo.Concepts() do
local sectionID = conceptSections[thisConcept.CivilopediaHeaderType];
if(sectionID ~= nil) then
-- add an article to the list (localized name, unit tag, etc.)
local article = {};
local name = Locale.ConvertTextKey( thisConcept.Description )
article.entryName = name;
article.entryID = thisConcept.ID;
article.entryCategory = CategoryGameConcepts;
article.InsertBefore = thisConcept.InsertBefore;
article.InsertAfter = thisConcept.InsertAfter;
article.Type = thisConcept.Type;
table.insert(GameConceptsList[sectionID], article);
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[thisConcept.Description] = article;
categorizedList[(CategoryGameConcepts * absurdlyLargeNumTopicsInCategory) + thisConcept.ID] = article;
end
end
-- In order to maintain the original order as best as possible,
-- we assign "InsertBefore" values to all items that lack any insert.
for _, conceptList in ipairs(GameConceptsList) do
for i = #conceptList, 1, -1 do
local concept = conceptList[i];
if(concept.InsertBefore == nil and concept.InsertAfter == nil) then
for ii = i - 1, 1, -1 do
local previousConcept = conceptList[ii];
if(previousConcept.InsertBefore == nil and previousConcept.InsertAfter == nil) then
concept.InsertAfter = previousConcept.Type;
break;
end
end
end
end
end
-- sort the articles by their dependencies.
function DependencySort(articles)
-- index articles by Topic
local articlesByType= {};
local dependencies = {};
for i,v in ipairs(articles) do
articlesByType[v.Type] = v;
dependencies[v] = {};
end
for i,v in ipairs(articles) do
local insertBefore = v.InsertBefore;
if(insertBefore ~= nil) then
local article = articlesByType[insertBefore];
dependencies[article][v] = true;
end
local insertAfter = v.InsertAfter;
if(insertAfter ~= nil) then
local article = articlesByType[insertAfter];
dependencies[v][article] = true;
end
end
local sortedList = {};
local articleCount = #articles;
while(#sortedList < articleCount) do
-- Attempt to find a node with 0 dependencies
local article;
for i,a in ipairs(articles) do
if(dependencies[a] ~= nil and table.count(dependencies[a]) == 0) then
article = a;
break;
end
end
if(article == nil) then
print("Failed to sort articles topologically!! There are dependency cycles.");
return nil;
else
-- Insert Node
table.insert(sortedList, article);
-- Remove node
dependencies[article] = nil;
for a,d in pairs(dependencies) do
d[article] = nil;
end
end
end
return sortedList;
end
for i,v in ipairs(GameConceptsList) do
local oldList = v;
local newList = DependencySort(v);
if(newList == nil) then
newList = oldList;
else
newList.headingOpen = false;
end
GameConceptsList[i] = newList;
end
end
CivilopediaCategory[CategoryTech].PopulateList = function()
-- add the instances of the tech entries
sortedList[CategoryTech] = {};
-- for each era
for era in GameInfo.Eras() do
local eraID = era.ID;
sortedList[CategoryTech][eraID] = {};
local tableid = 1;
-- for each tech in this era
for tech in GameInfo.Technologies("Era = '" .. era.Type .. "'") do
-- add a tech entry to a list (localized name, unit tag, etc.)
local article = {};
local name = Locale.ConvertTextKey( tech.Description )
article.entryName = name;
article.entryID = tech.ID;
article.entryCategory = CategoryTech;
article.tooltipTextureOffset, article.tooltipTexture = IconLookup( tech.PortraitIndex, buttonSize, tech.IconAtlas );
if not article.tooltipTextureOffset then
article.tooltipTexture = defaultErrorTextureSheet;
article.tooltipTextureOffset = nullOffset;
end
sortedList[CategoryTech][eraID][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[tech.Description] = article;
categorizedList[(CategoryTech * absurdlyLargeNumTopicsInCategory) + tech.ID] = article;
end
-- sort this list alphabetically by localized name
table.sort(sortedList[CategoryTech][eraID], Alphabetically);
end
end
CivilopediaCategory[CategoryUnits].PopulateList = function()
-- add the instances of the unit entries
sortedList[CategoryUnits] = {};
function AddArticle(categoryID, entryID, unit)
local article = {};
local name = Locale.ConvertTextKey( unit.Description )
article.entryName = name;
article.entryID = unit.ID;
article.entryCategory = CategoryUnits;
article.tooltipTextureOffset, article.tooltipTexture = IconLookup( unit.PortraitIndex, buttonSize, unit.IconAtlas );
if not article.tooltipTextureOffset then
article.tooltipTexture = defaultErrorTextureSheet;
article.tooltipTextureOffset = nullOffset;
end
sortedList[CategoryUnits][categoryID][entryID] = article;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[unit.Description] = article;
categorizedList[(CategoryUnits * absurdlyLargeNumTopicsInCategory) + unit.ID] = article;
end
local sectionID = 0;
-- Add units which cost faith to a "Faith" category first.
if(Game == nil or not Game.IsOption(GameOptionTypes.GAMEOPTION_NO_RELIGION)) then
local faithUnits = {};
sortedList[CategoryUnits][0] = {};
local tableid = 1;
for unit in DB.Query("SELECT Units.ID, Units.Description, Units.PortraitIndex, Units.IconAtlas From Units where Units.FaithCost > 0 and Units.Cost == -1 and not RequiresFaithPurchaseEnabled and ShowInPedia == 1") do
AddArticle(0, tableid, unit);
tableid = tableid + 1;
end
sectionID = sectionID + 1;
end
-- for each era
local sql = [[
SELECT Units.ID, Units.Description, Units.PortraitIndex, Units.IconAtlas
FROM Units INNER JOIN Technologies on PreReqTech = Technologies.Type
WHERE (Units.FaithCost = 0 or RequiresFaithPurchaseEnabled or Units.Cost >= 0) and Units.ShowInPedia = 1 and Technologies.Era = ?;]];
local UnitsByEra = DB.CreateQuery(sql);
local bFirstEra = true;
for era in GameInfo.Eras() do
local eraID = era.ID + sectionID;
sortedList[CategoryUnits][eraID] = {};
local tableid = 1;
for unit in UnitsByEra(era.Type) do
AddArticle(eraID, tableid, unit);
tableid = tableid + 1;
end
-- put in all of the units that do not have tech requirements in the Ancient Era for lack of a better place
if(bFirstEra == true) then
for unit in DB.Query("SELECT Units.ID, Units.Description, Units.PortraitIndex, Units.IconAtlas From Units where PreReqTech is NULL and Special is NULL and (Units.FaithCost = 0 or RequiresFaithPurchaseEnabled or Units.Cost >= 0) and Units.ShowInPedia = 1") do
AddArticle(eraID, tableid, unit);
tableid = tableid + 1;
end
end
bFirstEra = false;
end
-- sort this list alphabetically by localized name
for k,v in pairs(sortedList[CategoryUnits]) do
table.sort(v, Alphabetically);
end
end
CivilopediaCategory[CategoryPromotions].PopulateList = function()
-- add the instances of the promotion entries
sortedList[CategoryPromotions] = {};
sortedList[CategoryPromotions][1] = {};
local tableid = 1;
-- for each promotion
for thisPromotion in GameInfo.UnitPromotions() do
if thisPromotion.PediaType == "PEDIA_MELEE" then
-- add an article to the list (localized name, unit tag, etc.)
local article = {};
local name = Locale.ConvertTextKey( thisPromotion.PediaEntry )
article.entryName = name;
article.entryID = thisPromotion.ID;
article.entryCategory = CategoryPromotions;
sortedList[CategoryPromotions][1][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[thisPromotion.Description] = article;
categorizedList[(CategoryPromotions * absurdlyLargeNumTopicsInCategory) + thisPromotion.ID] = article;
end
end
sortedList[CategoryPromotions][2] = {};
local tableid = 1;
for thisPromotion in GameInfo.UnitPromotions() do
if thisPromotion.PediaType == "PEDIA_RANGED" then
-- add an article to the list (localized name, unit tag, etc.)
local article = {};
local name = Locale.ConvertTextKey( thisPromotion.PediaEntry )
article.entryName = name;
article.entryID = thisPromotion.ID;
article.entryCategory = CategoryPromotions;
sortedList[CategoryPromotions][2][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[thisPromotion.Description] = article;
categorizedList[(CategoryPromotions * absurdlyLargeNumTopicsInCategory) + thisPromotion.ID] = article;
end
end
sortedList[CategoryPromotions][3] = {};
local tableid = 1;
for thisPromotion in GameInfo.UnitPromotions() do
if thisPromotion.PediaType == "PEDIA_NAVAL" then
-- add an article to the list (localized name, unit tag, etc.)
local article = {};
local name = Locale.ConvertTextKey( thisPromotion.PediaEntry )
article.entryName = name;
article.entryID = thisPromotion.ID;
article.entryCategory = CategoryPromotions;
sortedList[CategoryPromotions][3][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[thisPromotion.Description] = article;
categorizedList[(CategoryPromotions * absurdlyLargeNumTopicsInCategory) + thisPromotion.ID] = article;
end
end
sortedList[CategoryPromotions][4] = {};
local tableid = 1;
for thisPromotion in GameInfo.UnitPromotions() do
if thisPromotion.PediaType == "PEDIA_HEAL" then
-- add an article to the list (localized name, unit tag, etc.)
local article = {};
local name = Locale.ConvertTextKey( thisPromotion.PediaEntry )
article.entryName = name;
article.entryID = thisPromotion.ID;
article.entryCategory = CategoryPromotions;
sortedList[CategoryPromotions][4][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[thisPromotion.Description] = article;
categorizedList[(CategoryPromotions * absurdlyLargeNumTopicsInCategory) + thisPromotion.ID] = article;
end
end
sortedList[CategoryPromotions][5] = {};
local tableid = 1;
for thisPromotion in GameInfo.UnitPromotions() do
if thisPromotion.PediaType == "PEDIA_SCOUTING" then
-- add an article to the list (localized name, unit tag, etc.)
local article = {};
local name = Locale.ConvertTextKey( thisPromotion.PediaEntry )
article.entryName = name;
article.entryID = thisPromotion.ID;
article.entryCategory = CategoryPromotions;
sortedList[CategoryPromotions][5][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[thisPromotion.Description] = article;
categorizedList[(CategoryPromotions * absurdlyLargeNumTopicsInCategory) + thisPromotion.ID] = article;
end
end
sortedList[CategoryPromotions][6] = {};
local tableid = 1;
for thisPromotion in GameInfo.UnitPromotions() do
if thisPromotion.PediaType == "PEDIA_AIR" then
-- add an article to the list (localized name, unit tag, etc.)
local article = {};
local name = Locale.ConvertTextKey( thisPromotion.PediaEntry )
article.entryName = name;
article.entryID = thisPromotion.ID;
article.entryCategory = CategoryPromotions;
sortedList[CategoryPromotions][6][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[thisPromotion.Description] = article;
categorizedList[(CategoryPromotions * absurdlyLargeNumTopicsInCategory) + thisPromotion.ID] = article;
end
end
sortedList[CategoryPromotions][7] = {};
local tableid = 1;
for thisPromotion in GameInfo.UnitPromotions() do
if thisPromotion.PediaType == "PEDIA_SHARED" then
-- add an article to the list (localized name, unit tag, etc.)
local article = {};
local name = Locale.ConvertTextKey( thisPromotion.PediaEntry )
article.entryName = name;
article.entryID = thisPromotion.ID;
article.entryCategory = CategoryPromotions;
sortedList[CategoryPromotions][7][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[thisPromotion.Description] = article;
categorizedList[(CategoryPromotions * absurdlyLargeNumTopicsInCategory) + thisPromotion.ID] = article;
end
end
sortedList[CategoryPromotions][8] = {};
local tableid = 1;
for thisPromotion in GameInfo.UnitPromotions() do
if thisPromotion.PediaType == "PEDIA_ATTRIBUTES" then
-- add an article to the list (localized name, unit tag, etc.)
local article = {};
local name = Locale.ConvertTextKey( thisPromotion.PediaEntry )
article.entryName = name;
article.entryID = thisPromotion.ID;
article.entryCategory = CategoryPromotions;
sortedList[CategoryPromotions][8][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[thisPromotion.Description] = article;
categorizedList[(CategoryPromotions * absurdlyLargeNumTopicsInCategory) + thisPromotion.ID] = article;
end
end
-- sort this list alphabetically by localized name
for section = 1,8,1 do
table.sort(sortedList[CategoryPromotions][section], Alphabetically);
end
end
CivilopediaCategory[CategoryBuildings].PopulateList = function()
-- add the instances of the building entries
sortedList[CategoryBuildings] = {};
function AddArticle(categoryID, entryID, building)
local article = {};
local name = Locale.ConvertTextKey( building.Description )
article.entryName = name;
article.entryID = building.ID;
article.entryCategory = CategoryBuildings;
article.tooltipTextureOffset, article.tooltipTexture = IconLookup( building.PortraitIndex, buttonSize, building.IconAtlas );
if not article.tooltipTextureOffset then
article.tooltipTexture = defaultErrorTextureSheet;
article.tooltipTextureOffset = nullOffset;
end
sortedList[CategoryBuildings][categoryID][entryID] = article;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[building.Description] = article;
categorizedList[(CategoryBuildings * absurdlyLargeNumTopicsInCategory) + building.ID] = article;
end
local sectionID = 0;
if(Game == nil or not Game.IsOption(GameOptionTypes.GAMEOPTION_NO_RELIGION)) then
--Add Faith Buildings first
sortedList[CategoryBuildings][sectionID] = {};
local tableid = 1;
for building in DB.Query("SELECT Buildings.ID, Buildings.Description, Buildings.PortraitIndex, Buildings.IconAtlas from Buildings inner join BuildingClasses on Buildings.BuildingClass = BuildingClasses.Type where Buildings.FaithCost > 0 and Buildings.Cost > 0 and BuildingClasses.MaxGlobalInstances < 0 and (BuildingClasses.MaxPlayerInstances <> 1 or Buildings.SpecialistCount > 0) and BuildingClasses.MaxTeamInstances < 0 and Buildings.GreatWorkCount >= 0") do
AddArticle(0, tableid, building);
tableid = tableid + 1;
end
sectionID = sectionID + 1;
end
local sql = [[
SELECT Buildings.ID, Buildings.Description, Buildings.PortraitIndex, Buildings.IconAtlas
FROM Buildings
INNER JOIN BuildingClasses ON Buildings.BuildingClass = BuildingClasses.Type
INNER JOIN Technologies ON Buildings.PrereqTech = Technologies.Type
WHERE (FaithCost == 0 or Buildings.Cost >= 0) AND BuildingClasses.MaxGlobalInstances < 0 AND (BuildingClasses.MaxPlayerInstances <> 1 or Buildings.SpecialistCount > 0) AND BuildingClasses.MaxTeamInstances < 0 AND Buildings.GreatWorkCount >= 0 AND Technologies.Era = ?;]];
local BuildingsByEra = DB.CreateQuery(sql);
-- for each era
local bFirstEra = true;
for era in GameInfo.Eras() do
local eraID = era.ID + sectionID;
sortedList[CategoryBuildings][eraID] = {};
local tableid = 1;
for building in BuildingsByEra(era.Type) do
AddArticle(eraID, tableid, building);
tableid = tableid + 1;
end
-- put in all of the buildings that do not have tech requirements in the first Era for lack of a better place
if(bFirstEra) then
local sql = [[
SELECT Buildings.ID, Buildings.Description, Buildings.PortraitIndex, Buildings.IconAtlas
FROM Buildings
INNER JOIN BuildingClasses ON Buildings.BuildingClass = BuildingClasses.Type
WHERE Buildings.PrereqTech IS NULL AND (Buildings.FaithCost == 0 or Buildings.Cost >= 0) AND BuildingClasses.MaxGlobalInstances < 0 AND (BuildingClasses.MaxPlayerInstances <> 1 or Buildings.SpecialistCount > 0) AND BuildingClasses.MaxTeamInstances < 0 AND Buildings.GreatWorkCount >= 0;]];
for building in DB.Query(sql) do
AddArticle(eraID, tableid, building);
tableid = tableid + 1;
end
end
bFirstEra = false;
end
for k,v in pairs(sortedList[CategoryBuildings]) do
table.sort(v, Alphabetically);
end
end
CivilopediaCategory[CategoryWonders].PopulateList = function()
-- add the instances of the Wonder, National Wonder, Team Wonder, and Project entries
sortedList[CategoryWonders] = {};
-- first Wonders
sortedList[CategoryWonders][1] = {};
local tableid = 1;
for building in GameInfo.Buildings() do
-- exclude wonders etc.
local thisBuildingClass = GameInfo.BuildingClasses[building.BuildingClass];
if thisBuildingClass.MaxGlobalInstances > 0 then
local article = {};
local name = Locale.ConvertTextKey( building.Description )
article.entryName = name;
article.entryID = building.ID;
article.entryCategory = CategoryWonders;
article.tooltipTextureOffset, article.tooltipTexture = IconLookup( building.PortraitIndex, buttonSize, building.IconAtlas );
if not article.tooltipTextureOffset then
article.tooltipTexture = defaultErrorTextureSheet;
article.tooltipTextureOffset = nullOffset;
end
sortedList[CategoryWonders][1][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[building.Description] = article;
categorizedList[(CategoryWonders * absurdlyLargeNumTopicsInCategory) + building.ID] = article;
end
end
-- sort this list alphabetically by localized name
table.sort(sortedList[CategoryWonders][1], Alphabetically);
-- next National Wonders
sortedList[CategoryWonders][2] = {};
tableid = 1;
for building in GameInfo.Buildings() do
local thisBuildingClass = GameInfo.BuildingClasses[building.BuildingClass];
if thisBuildingClass.MaxPlayerInstances == 1 and building.SpecialistCount == 0 then
local article = {};
local name = Locale.ConvertTextKey( building.Description )
article.entryName = name;
article.entryID = building.ID;
article.entryCategory = CategoryWonders;
article.tooltipTextureOffset, article.tooltipTexture = IconLookup( building.PortraitIndex, buttonSize, building.IconAtlas );
if not article.tooltipTextureOffset then
article.tooltipTexture = defaultErrorTextureSheet;
article.tooltipTextureOffset = nullOffset;
end
sortedList[CategoryWonders][2][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[building.Description] = article;
categorizedList[(CategoryWonders * absurdlyLargeNumTopicsInCategory) + building.ID] = article;
end
end
-- sort this list alphabetically by localized name
table.sort(sortedList[CategoryWonders][2], Alphabetically);
-- finally Projects
sortedList[CategoryWonders][3] = {};
tableid = 1;
for building in GameInfo.Projects() do
local bIgnore = projectsToIgnore[building.Type];
if(bIgnore ~= true) then
local article = {};
local name = Locale.ConvertTextKey( building.Description )
article.entryName = name;
article.entryID = building.ID + 1000;
article.entryCategory = CategoryWonders;
article.tooltipTextureOffset, article.tooltipTexture = IconLookup( building.PortraitIndex, buttonSize, building.IconAtlas );
if not article.tooltipTextureOffset then
article.tooltipTexture = defaultErrorTextureSheet;
article.tooltipTextureOffset = nullOffset;
end
sortedList[CategoryWonders][3][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[building.Description] = article;
categorizedList[(CategoryWonders * absurdlyLargeNumTopicsInCategory) + building.ID + 1000] = article;
end
end
-- sort this list alphabetically by localized name
table.sort(sortedList[CategoryWonders][3], Alphabetically);
end
CivilopediaCategory[CategoryPolicies].PopulateList = function()
-- add the instances of the policy entries
sortedList[CategoryPolicies] = {};
-- for each policy branch
for branch in GameInfo.PolicyBranchTypes() do
local branchID = branch.ID;
sortedList[CategoryPolicies][branchID] = {};
local tableid = 1;
-- for each policy in this branch
for policy in GameInfo.Policies("PolicyBranchType = '" .. branch.Type .. "'") do
local article = {};
local name = Locale.ConvertTextKey( policy.Description )
article.entryName = name;
article.entryID = policy.ID;
article.entryCategory = CategoryPolicies;
article.tooltipTextureOffset, article.tooltipTexture = IconLookup( policy.PortraitIndex, buttonSize, policy.IconAtlas );
if not article.tooltipTextureOffset then
article.tooltipTexture = defaultErrorTextureSheet;
article.tooltipTextureOffset = nullOffset;
end
sortedList[CategoryPolicies][branchID][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[policy.Description] = article;
categorizedList[(CategoryPolicies * absurdlyLargeNumTopicsInCategory) + policy.ID] = article;
end
-- put in free policies that belong to this branch in here
if (branch.FreePolicy ~= nil) then
local freePolicy = GameInfo.Policies[branch.FreePolicy];
local article = {};
local name = Locale.ConvertTextKey( freePolicy.Description )
article.entryName = name;
article.entryID = freePolicy.ID;
article.entryCategory = CategoryPolicies;
article.tooltipTextureOffset, article.tooltipTexture = IconLookup( freePolicy.PortraitIndex, buttonSize, freePolicy.IconAtlas );
if not article.tooltipTextureOffset then
article.tooltipTexture = defaultErrorTextureSheet;
article.tooltipTextureOffset = nullOffset;
end
sortedList[CategoryPolicies][branchID][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[freePolicy.Description] = article;
categorizedList[(CategoryPolicies * absurdlyLargeNumTopicsInCategory) + freePolicy.ID] = article;
end
-- sort this list alphabetically by localized name
table.sort(sortedList[CategoryPolicies][branchID], Alphabetically);
end
end
CivilopediaCategory[CategoryPeople].PopulateList = function()
-- add the instances of the Specialists and Great People entries
sortedList[CategoryPeople] = {};
-- first Specialists
sortedList[CategoryPeople][1] = {};
local tableid = 1;
for person in GameInfo.Specialists() do
local article = {};
local name = Locale.ConvertTextKey( person.Description )
article.entryName = name;
article.entryID = person.ID;
article.entryCategory = CategoryPeople;
article.tooltipTextureOffset, article.tooltipTexture = IconLookup( person.PortraitIndex, buttonSize, person.IconAtlas );
if not article.tooltipTextureOffset then
article.tooltipTexture = defaultErrorTextureSheet;
article.tooltipTextureOffset = nullOffset;
end
sortedList[CategoryPeople][1][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[person.Description] = article;
categorizedList[(CategoryPeople * absurdlyLargeNumTopicsInCategory) + person.ID] = article; -- add a fudge factor
end
-- sort this list alphabetically by localized name
table.sort(sortedList[CategoryPeople][1], Alphabetically);
-- next Great People
sortedList[CategoryPeople][2] = {};
tableid = 1;
for unit in GameInfo.Units() do
if unit.PrereqTech == nil and unit.Special ~= nil then
local article = {};
local name = Locale.ConvertTextKey( unit.Description )
article.entryName = name;
article.entryID = unit.ID + 1000;
article.entryCategory = CategoryPeople;
article.tooltipTextureOffset, article.tooltipTexture = IconLookup( unit.PortraitIndex, buttonSize, unit.IconAtlas );
if not article.tooltipTextureOffset then
article.tooltipTexture = defaultErrorTextureSheet;
article.tooltipTextureOffset = nullOffset;
end
sortedList[CategoryPeople][2][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[unit.Description] = article;
categorizedList[(CategoryPeople * absurdlyLargeNumTopicsInCategory) + unit.ID + 1000] = article; -- todo: add fudge factor
end
end
-- sort this list alphabetically by localized name
table.sort(sortedList[CategoryPeople][2], Alphabetically);
end
CivilopediaCategory[CategoryCivilizations].PopulateList = function()
-- add the instances of the Civilization and Leader entries
sortedList[CategoryCivilizations] = {};
-- first Civilizations
sortedList[CategoryCivilizations][1] = {};
local tableid = 1;
for row in GameInfo.Civilizations() do
if row.Type ~= "CIVILIZATION_MINOR" and row.Type ~= "CIVILIZATION_BARBARIAN" then
local article = {};
local name = Locale.ConvertTextKey( row.ShortDescription )
article.entryName = name;
article.entryID = row.ID;
article.entryCategory = CategoryCivilizations;
article.tooltipTextureOffset, article.tooltipTexture = IconLookup( row.PortraitIndex, buttonSize, row.IconAtlas );
if not article.tooltipTextureOffset then
article.tooltipTexture = defaultErrorTextureSheet;
article.tooltipTextureOffset = nullOffset;
end
sortedList[CategoryCivilizations][1][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[row.ShortDescription] = article;
categorizedList[(CategoryCivilizations * absurdlyLargeNumTopicsInCategory) + row.ID] = article;
end
end
-- sort this list alphabetically by localized name
table.sort(sortedList[CategoryCivilizations][1], Alphabetically);
-- next Leaders
sortedList[CategoryCivilizations][2] = {};
local tableid = 1;
for row in GameInfo.Civilizations() do
if row.Type ~= "CIVILIZATION_MINOR" and row.Type ~= "CIVILIZATION_BARBARIAN" then
local leader = GameInfo.Leaders[GameInfo.Civilization_Leaders( "CivilizationType = '" .. row.Type .. "'" )().LeaderheadType];
local article = {};
local name = Locale.ConvertTextKey( leader.Description )
article.entryName = name;
article.entryID = row.ID + 1000;
article.entryCategory = CategoryCivilizations;
article.tooltipTextureOffset, article.tooltipTexture = IconLookup( leader.PortraitIndex, buttonSize, leader.IconAtlas );
if not article.tooltipTextureOffset then
article.tooltipTexture = defaultErrorTextureSheet;
article.tooltipTextureOffset = nullOffset;
end
sortedList[CategoryCivilizations][2][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[leader.Description] = article;
categorizedList[(CategoryCivilizations * absurdlyLargeNumTopicsInCategory) + row.ID + 1000] = article;
end
end
-- sort this list alphabetically by localized name
table.sort(sortedList[CategoryCivilizations][2], Alphabetically);
end
CivilopediaCategory[CategoryCityStates].PopulateList = function()
-- add the instances of the City States entries
sortedList[CategoryCityStates] = {};
-- for each trait
for trait in GameInfo.MinorCivTraits() do
local traitID = trait.ID;
sortedList[CategoryCityStates][traitID] = {};
local tableid = 1;
-- for each city state that has this trait
for cityState in GameInfo.MinorCivilizations("MinorCivTrait = '" .. trait.Type .. "'") do
-- add a tech entry to a list (localized name, tag, etc.)
local article = {};
local name = Locale.ConvertTextKey( cityState.Description )
article.entryName = name;
article.entryID = cityState.ID;
article.entryCategory = CategoryCityStates;
sortedList[CategoryCityStates][traitID][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[cityState.Description] = article;
categorizedList[(CategoryCityStates * absurdlyLargeNumTopicsInCategory) + cityState.ID] = article;
end
-- sort this list alphabetically by localized name
table.sort(sortedList[CategoryCityStates][traitID], Alphabetically);
end
end
CivilopediaCategory[CategoryTerrain].PopulateList = function()
-- add the instances of the Terrain and Features entries
sortedList[CategoryTerrain] = {};
-- first Specialists
sortedList[CategoryTerrain][1] = {};
local tableid = 1;
for row in GameInfo.Terrains() do
local article = {};
local name = Locale.ConvertTextKey( row.Description )
article.entryName = name;
article.entryID = row.ID;
article.entryCategory = CategoryTerrain;
article.tooltipTextureOffset, article.tooltipTexture = IconLookup( row.PortraitIndex, buttonSize, row.IconAtlas );
if not article.tooltipTextureOffset then
article.tooltipTexture = defaultErrorTextureSheet;
article.tooltipTextureOffset = nullOffset;
end
sortedList[CategoryTerrain][1][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[row.Description] = article;
categorizedList[(CategoryTerrain * absurdlyLargeNumTopicsInCategory) + row.ID] = article; -- add a fudge factor
end
-- sort this list alphabetically by localized name
table.sort(sortedList[CategoryTerrain][1], Alphabetically);
-- next Features
sortedList[CategoryTerrain][2] = {};
tableid = 1;
for row in GameInfo.Features() do
local article = {};
local name = Locale.ConvertTextKey( row.Description )
article.entryName = name;
article.entryID = row.ID + 1000;
article.entryCategory = CategoryTerrain;
article.tooltipTextureOffset, article.tooltipTexture = IconLookup( row.PortraitIndex, buttonSize, row.IconAtlas );
if not article.tooltipTextureOffset then
article.tooltipTexture = defaultErrorTextureSheet;
article.tooltipTextureOffset = nullOffset;
end
sortedList[CategoryTerrain][2][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[row.Description] = article;
categorizedList[(CategoryTerrain * absurdlyLargeNumTopicsInCategory) + row.ID + 1000] = article; -- add a fudge factor
end
-- now for the fake features (river and lake)
for row in GameInfo.FakeFeatures() do
local article = {};
local name = Locale.ConvertTextKey( row.Description )
article.entryName = name;
article.entryID = row.ID + 2000;
article.entryCategory = CategoryTerrain;
article.tooltipTextureOffset, article.tooltipTexture = IconLookup( row.PortraitIndex, buttonSize, row.IconAtlas );
if not article.tooltipTextureOffset then
article.tooltipTexture = defaultErrorTextureSheet;
article.tooltipTextureOffset = nullOffset;
end
sortedList[CategoryTerrain][2][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[row.Description] = article;
categorizedList[(CategoryTerrain * absurdlyLargeNumTopicsInCategory) + row.ID + 2000] = article; -- add a fudge factor
end
-- sort this list alphabetically by localized name
table.sort(sortedList[CategoryTerrain][2], Alphabetically);
end
CivilopediaCategory[CategoryResources].PopulateList = function()
-- add the instances of the resource entries
sortedList[CategoryResources] = {};
-- for each type of resource
for resourceType = 0, 2, 1 do
sortedList[CategoryResources][resourceType] = {};
local tableid = 1;
-- for each type of resource
for resource in GameInfo.Resources( "ResourceUsage = '" .. resourceType .. "'" ) do
-- add a tech entry to a list (localized name, tag, etc.)
local article = {};
local name = Locale.ConvertTextKey( resource.Description )
article.entryName = name;
article.entryID = resource.ID;
article.entryCategory = CategoryResources;
article.tooltipTextureOffset, article.tooltipTexture = IconLookup( resource.PortraitIndex, buttonSize, resource.IconAtlas );
if not article.tooltipTextureOffset then
article.tooltipTexture = defaultErrorTextureSheet;
article.tooltipTextureOffset = nullOffset;
end
sortedList[CategoryResources][resourceType][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[resource.Description] = article;
categorizedList[(CategoryResources * absurdlyLargeNumTopicsInCategory) + resource.ID] = article;
end
-- sort this list alphabetically by localized name
table.sort(sortedList[CategoryResources][resourceType], Alphabetically);
end
end
CivilopediaCategory[CategoryImprovements].PopulateList = function()
-- add the instances of the improvement entries
sortedList[CategoryImprovements] = {};
sortedList[CategoryImprovements][1] = {}; -- there is only one section (for now)
local tableid = 1;
-- for each improvement
for row in GameInfo.Improvements() do
if not row.GraphicalOnly then
-- add an article to the list (localized name, unit tag, etc.)
local article = {};
local name = Locale.ConvertTextKey( row.Description );
article.entryName = name;
article.entryID = row.ID;
article.entryCategory = CategoryImprovements;
article.tooltipTextureOffset, article.tooltipTexture = IconLookup( row.PortraitIndex, buttonSize, row.IconAtlas );
if not article.tooltipTextureOffset then
article.tooltipTexture = defaultErrorTextureSheet;
article.tooltipTextureOffset = nullOffset;
end
sortedList[CategoryImprovements][1][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[row.Description] = article;
categorizedList[(CategoryImprovements * absurdlyLargeNumTopicsInCategory) + row.ID] = article;
end
end
--add railroads and roads
for row in GameInfo.Routes() do
local article = {};
local name = Locale.ConvertTextKey( row.Description );
article.entryName = name;
article.entryID = row.ID + 1000;
article.entryCategory = CategoryImprovements;
article.tooltipTextureOffset, article.tooltipTexture = IconLookup( row.PortraitIndex, buttonSize, row.IconAtlas );
if not article.tooltipTextureOffset then
article.tooltipTexture = defaultErrorTextureSheet;
article.tooltipTextureOffset = nullOffset;
end
sortedList[CategoryImprovements][1][tableid] = article;
tableid = tableid + 1;
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[row.Description] = article;
categorizedList[(CategoryImprovements * absurdlyLargeNumTopicsInCategory) + 1000 + row.ID] = article;
end
-- sort this list alphabetically by localized name
table.sort(sortedList[CategoryImprovements][1], Alphabetically);
end
CivilopediaCategory[CategoryBeliefs].PopulateList = function()
sortedList[CategoryBeliefs] = {};
do
local section = {};
for religion in GameInfo.Religions("Type <> 'RELIGION_PANTHEON'") do
-- add a tech entry to a list (localized name, tag, etc.)
local article = {};
local name = Locale.ConvertTextKey(religion.Description)
article.entryName = name;
article.entryID = {"Religions", religion.ID};
article.entryCategory = CategoryBeliefs;
table.insert(section, article);
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[religion.Description] = article;
categorizedList[(CategoryBeliefs * absurdlyLargeNumTopicsInCategory) + religion.ID] = article;
end
-- sort this list alphabetically by localized name
table.sort(section, Alphabetically);
table.insert(sortedList[CategoryBeliefs], section);
end
-- for each type of resource
local sectionConditions = {
"Pantheon = 1",
"Founder = 1",
"Follower = 1",
"Enhancer = 1",
"Reformation = 1"
};
local numReligions = #GameInfo.Religions;
for i,condition in ipairs(sectionConditions) do
local section = {};
for belief in GameInfo.Beliefs(condition) do
-- add a tech entry to a list (localized name, tag, etc.)
local article = {};
local name = Locale.ConvertTextKey( belief.ShortDescription )
article.entryName = name;
article.entryID = {"Beliefs", belief.ID};
article.entryCategory = CategoryBeliefs;
table.insert(section, article);
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[belief.ShortDescription] = article;
categorizedList[(CategoryBeliefs * absurdlyLargeNumTopicsInCategory) + numReligions + belief.ID] = article;
end
-- sort this list alphabetically by localized name
table.sort(section, Alphabetically);
table.insert(sortedList[CategoryBeliefs], section);
end
end
CivilopediaCategory[CategoryWorldCongress].PopulateList = function()
sortedList[CategoryWorldCongress] = {};
do
local section = {};
for resolution in GameInfo.Resolutions() do
-- add a resolution entry to a list (localized name, tag, etc.)
local article = {};
local name = Locale.ConvertTextKey(resolution.Description)
article.entryName = name;
article.entryID = {"Resolutions", resolution.ID};
article.entryCategory = CategoryWorldCongress;
table.insert(section, article);
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[resolution.Description] = article;
categorizedList[(CategoryWorldCongress * absurdlyLargeNumTopicsInCategory) + resolution.ID] = article;
end
-- sort this list alphabetically by localized name
table.sort(section, Alphabetically);
table.insert(sortedList[CategoryWorldCongress], section);
end
do
local section = {};
for leagueProject in GameInfo.LeagueProjects() do
-- add a league project entry to a list (localized name, tag, etc.)
local article = {};
local name = Locale.ConvertTextKey(leagueProject.Description)
article.entryName = name;
article.entryID = {"LeagueProjects", leagueProject.ID};
article.entryCategory = CategoryWorldCongress;
table.insert(section, article);
-- index by various keys
searchableList[Locale.ToLower(name)] = article;
searchableTextKeyList[leagueProject.Description] = article;
categorizedList[(CategoryWorldCongress * absurdlyLargeNumTopicsInCategory) + leagueProject.ID] = article;
end
-- sort this list alphabetically by localized name
table.sort(section, Alphabetically);
table.insert(sortedList[CategoryWorldCongress], section);
end
end
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
function ResizeEtc()
Controls.ListOfArticles:CalculateSize();
Controls.WideStack:CalculateSize();
Controls.FFTextStack:CalculateSize();
Controls.NarrowStack:CalculateSize();
Controls.BBTextStack:CalculateSize();
Controls.SuperWideStack:CalculateSize();
Controls.BBTextStack:ReprocessAnchoring();
Controls.WideStack:ReprocessAnchoring();
Controls.FFTextStack:ReprocessAnchoring();
Controls.NarrowStack:ReprocessAnchoring();
Controls.ListOfArticles:ReprocessAnchoring();
Controls.SuperWideStack:ReprocessAnchoring();
Controls.ScrollPanel:CalculateInternalSize();
Controls.LeftScrollPanel:CalculateInternalSize();
end
--------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------
CivilopediaCategory[CategoryHomePage].DisplayHomePage = function()
ClearArticle();
Controls.ArticleID:SetText( Locale.ConvertTextKey("TXT_KEY_PEDIA_HOME_PAGE_LABEL") );
-- Update some circle logo
if IconHookup( 20, portraitSize, "TERRAIN_ATLAS", Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
g_BBTextManager:ResetInstances();
--Welcome and insert 1st manual paragraph
UpdateTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_HOME_PAGE_BLURB_TEXT" ), Controls.HomePageBlurbLabel, Controls.HomePageBlurbInnerFrame, Controls.HomePageBlurbFrame );
--How to use the Pedia
local thisBBTextInstance = g_BBTextManager:GetInstance();
if thisBBTextInstance then
thisBBTextInstance.BBTextHeader:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_HOME_PAGE_HELP_LABEL" ));
UpdateSuperWideTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_HOME_PAGE_HELP_TEXT" ), thisBBTextInstance.BBTextLabel, thisBBTextInstance.BBTextInnerFrame, thisBBTextInstance.BBTextFrame );
end
Controls.BBTextStack:SetHide( false );
ResizeEtc();
end;
CivilopediaCategory[CategoryGameConcepts].DisplayHomePage = function()
ClearArticle();
Controls.ArticleID:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_GAME_CONCEPT_PAGE_LABEL" ));
-- Update Some kind of circle logo
if IconHookup( 47, portraitSize, "TECH_ATLAS_1", Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
UpdateTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_QUOTE_BLOCK_GCONCEPTS" ), Controls.HomePageBlurbLabel, Controls.HomePageBlurbInnerFrame, Controls.HomePageBlurbFrame );
g_BBTextManager:ResetInstances();
--Basic Sectional Infos
local thisBBTextInstance = g_BBTextManager:GetInstance();
if thisBBTextInstance then
thisBBTextInstance.BBTextHeader:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_GAME_CONCEPT_PAGE_LABEL" ));
UpdateSuperWideTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_GAME_CONCEPT_HELP_TEXT" ), thisBBTextInstance.BBTextLabel, thisBBTextInstance.BBTextInnerFrame, thisBBTextInstance.BBTextFrame );
end
Controls.BBTextStack:SetHide( false );
--Did you know fact/tip of the day? Can be taken from rando advisor text. Or link to random page or modding
ResizeEtc();
end;
CivilopediaCategory[CategoryTech].DisplayHomePage = function()
ClearArticle();
Controls.ArticleID:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_TECH_PAGE_LABEL" ));
local portraitIndex = 48;
local portraitAtlas = "TECH_ATLAS_1";
for row in DB.Query("SELECT PortraitIndex, IconAtlas from Technologies ORDER By Random() LIMIT 1") do
portraitIndex = row.PortraitIndex;
portraitAtlas = row.IconAtlas;
end
if IconHookup( portraitIndex, portraitSize, portraitAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
UpdateTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_QUOTE_BLOCK_TECHS" ), Controls.HomePageBlurbLabel, Controls.HomePageBlurbInnerFrame, Controls.HomePageBlurbFrame );
g_BBTextManager:ResetInstances();
--Basic Sectional Infos
local thisBBTextInstance = g_BBTextManager:GetInstance();
if thisBBTextInstance then
thisBBTextInstance.BBTextHeader:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_TECH_PAGE_LABEL" ));
UpdateSuperWideTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_TECHNOLOGIES_HELP_TEXT" ), thisBBTextInstance.BBTextLabel, thisBBTextInstance.BBTextInnerFrame, thisBBTextInstance.BBTextFrame );
end
Controls.BBTextStack:SetHide( false );
ResizeEtc();
end;
CivilopediaCategory[CategoryUnits].DisplayHomePage = function()
ClearArticle();
Controls.ArticleID:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_UNITS_PAGE_LABEL" ));
local portraitIndex = 26;
local portraitAtlas = "UNIT_ATLAS_1";
for row in DB.Query("SELECT PortraitIndex, IconAtlas from Units ORDER By Random() LIMIT 1") do
portraitIndex = row.PortraitIndex;
portraitAtlas = row.IconAtlas;
end
if IconHookup( portraitIndex, portraitSize, portraitAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
UpdateTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_QUOTE_BLOCK_UNITS" ), Controls.HomePageBlurbLabel, Controls.HomePageBlurbInnerFrame, Controls.HomePageBlurbFrame );
g_BBTextManager:ResetInstances();
--Basic Sectional Infos
local thisBBTextInstance = g_BBTextManager:GetInstance();
if thisBBTextInstance then
thisBBTextInstance.BBTextHeader:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_UNITS_PAGE_LABEL" ));
UpdateSuperWideTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_UNITS_HELP_TEXT" ), thisBBTextInstance.BBTextLabel, thisBBTextInstance.BBTextInnerFrame, thisBBTextInstance.BBTextFrame );
end
Controls.BBTextStack:SetHide( false );
ResizeEtc();
end;
CivilopediaCategory[CategoryPromotions].DisplayHomePage = function()
ClearArticle();
Controls.ArticleID:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_PROMOTIONS_PAGE_LABEL" ));
local portraitIndex = 16;
local portraitAtlas = "PROMOTION_ATLAS";
for row in DB.Query("SELECT PortraitIndex, IconAtlas from UnitPromotions ORDER By Random() LIMIT 1") do
portraitIndex = row.PortraitIndex;
portraitAtlas = row.IconAtlas;
end
if IconHookup( portraitIndex, portraitSize, portraitAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
UpdateTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_QUOTE_BLOCK_PROMOTIONS" ), Controls.HomePageBlurbLabel, Controls.HomePageBlurbInnerFrame, Controls.HomePageBlurbFrame );
g_BBTextManager:ResetInstances();
--Basic Sectional Infos
local thisBBTextInstance = g_BBTextManager:GetInstance();
if thisBBTextInstance then
thisBBTextInstance.BBTextHeader:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_PROMOTIONS_PAGE_LABEL" ));
UpdateSuperWideTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_PROMOTIONS_HELP_TEXT" ), thisBBTextInstance.BBTextLabel, thisBBTextInstance.BBTextInnerFrame, thisBBTextInstance.BBTextFrame );
end
Controls.BBTextStack:SetHide( false );
ResizeEtc();
end;
CivilopediaCategory[CategoryBuildings].DisplayHomePage = function()
ClearArticle();
Controls.ArticleID:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_BUILDINGS_PAGE_LABEL" ));
local portraitIndex = 24;
local portraitAtlas = "BW_ATLAS_1";
for row in DB.Query("SELECT PortraitIndex, IconAtlas from Buildings where WonderSplashImage IS NULL ORDER By Random() LIMIT 1") do
portraitIndex = row.PortraitIndex;
portraitAtlas = row.IconAtlas;
end
if IconHookup( portraitIndex, portraitSize, portraitAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
UpdateTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_QUOTE_BLOCK_BUILDINGS" ), Controls.HomePageBlurbLabel, Controls.HomePageBlurbInnerFrame, Controls.HomePageBlurbFrame );
g_BBTextManager:ResetInstances();
--Basic Sectional Infos
local thisBBTextInstance = g_BBTextManager:GetInstance();
if thisBBTextInstance then
thisBBTextInstance.BBTextHeader:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_BUILDINGS_PAGE_LABEL" ));
UpdateSuperWideTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_BUILDINGS_HELP_TEXT" ), thisBBTextInstance.BBTextLabel, thisBBTextInstance.BBTextInnerFrame, thisBBTextInstance.BBTextFrame );
end
Controls.BBTextStack:SetHide( false );
ResizeEtc();
end;
CivilopediaCategory[CategoryWonders].DisplayHomePage = function()
ClearArticle();
Controls.ArticleID:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_WONDERS_PAGE_LABEL" ));
local portraitIndex = 2;
local portraitAtlas = "BW_ATLAS_2";
for row in DB.Query("SELECT PortraitIndex, IconAtlas from Buildings Where WonderSplashImage IS NOT NULL ORDER By Random() LIMIT 1") do
portraitIndex = row.PortraitIndex;
portraitAtlas = row.IconAtlas;
end
if IconHookup( portraitIndex, portraitSize, portraitAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
UpdateTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_QUOTE_BLOCK_WONDERS" ), Controls.HomePageBlurbLabel, Controls.HomePageBlurbInnerFrame, Controls.HomePageBlurbFrame );
g_BBTextManager:ResetInstances();
--Basic Sectional Infos
local thisBBTextInstance = g_BBTextManager:GetInstance();
if thisBBTextInstance then
thisBBTextInstance.BBTextHeader:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_WONDERS_PAGE_LABEL" ));
UpdateSuperWideTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_WONDERS_HELP_TEXT" ), thisBBTextInstance.BBTextLabel, thisBBTextInstance.BBTextInnerFrame, thisBBTextInstance.BBTextFrame );
end
Controls.BBTextStack:SetHide( false );
ResizeEtc();
end;
CivilopediaCategory[CategoryPolicies].DisplayHomePage = function()
ClearArticle();
Controls.ArticleID:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_POLICIES_PAGE_LABEL" ));
local portraitIndex = 25;
local portraitAtlas = "POLICY_ATLAS";
for row in DB.Query("SELECT PortraitIndex, IconAtlas from Policies Where IconAtlas IS NOT NULL ORDER By Random() LIMIT 1") do
portraitIndex = row.PortraitIndex;
portraitAtlas = row.IconAtlas;
end
if IconHookup( portraitIndex, portraitSize, portraitAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
UpdateTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_QUOTE_BLOCK_POLICIES" ), Controls.HomePageBlurbLabel, Controls.HomePageBlurbInnerFrame, Controls.HomePageBlurbFrame );
g_BBTextManager:ResetInstances();
--Basic Sectional Infos
local thisBBTextInstance = g_BBTextManager:GetInstance();
if thisBBTextInstance then
thisBBTextInstance.BBTextHeader:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_POLICIES_PAGE_LABEL" ));
UpdateSuperWideTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_SOCIAL_POL_HELP_TEXT" ), thisBBTextInstance.BBTextLabel, thisBBTextInstance.BBTextInnerFrame, thisBBTextInstance.BBTextFrame );
end
Controls.BBTextStack:SetHide( false );
ResizeEtc();
end;
CivilopediaCategory[CategoryPeople].DisplayHomePage = function()
ClearArticle();
Controls.ArticleID:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_PEOPLE_PAGE_LABEL" ));
if IconHookup( 47, portraitSize, "UNIT_ATLAS_2", Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
UpdateTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_QUOTE_BLOCK_PEOPLE" ), Controls.HomePageBlurbLabel, Controls.HomePageBlurbInnerFrame, Controls.HomePageBlurbFrame );
g_BBTextManager:ResetInstances();
--Basic Sectional Infos
local thisBBTextInstance = g_BBTextManager:GetInstance();
if thisBBTextInstance then
thisBBTextInstance.BBTextHeader:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_PEOPLE_PAGE_LABEL" ));
UpdateSuperWideTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_SPEC_HELP_TEXT" ), thisBBTextInstance.BBTextLabel, thisBBTextInstance.BBTextInnerFrame, thisBBTextInstance.BBTextFrame );
end
Controls.BBTextStack:SetHide( false );
ResizeEtc();
end;
CivilopediaCategory[CategoryCivilizations].DisplayHomePage = function()
ClearArticle();
Controls.ArticleID:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_CIVILIZATIONS_PAGE_LABEL" ));
local portraitIndex = 7;
local portraitAtlas = "LEADER_ATLAS";
for row in DB.Query("SELECT PortraitIndex, IconAtlas from Leaders where Type <> \"LEADER_BARBARIAN\" ORDER By Random() LIMIT 1") do
portraitIndex = row.PortraitIndex;
portraitAtlas = row.IconAtlas;
end
if IconHookup( portraitIndex, portraitSize, portraitAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
UpdateTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_QUOTE_BLOCK_CIVS" ), Controls.HomePageBlurbLabel, Controls.HomePageBlurbInnerFrame, Controls.HomePageBlurbFrame );
g_BBTextManager:ResetInstances();
--Basic Sectional Infos
local thisBBTextInstance = g_BBTextManager:GetInstance();
if thisBBTextInstance then
thisBBTextInstance.BBTextHeader:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_CIVILIZATIONS_PAGE_LABEL" ));
UpdateSuperWideTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_CIVS_HELP_TEXT" ), thisBBTextInstance.BBTextLabel, thisBBTextInstance.BBTextInnerFrame, thisBBTextInstance.BBTextFrame );
end
Controls.BBTextStack:SetHide( false );
ResizeEtc();
end;
CivilopediaCategory[CategoryCityStates].DisplayHomePage = function()
ClearArticle();
Controls.ArticleID:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_CITY_STATES_PAGE_LABEL" ));
if IconHookup( 44, portraitSize, "UNIT_ATLAS_2", Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
UpdateTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_QUOTE_BLOCK_CITYSTATES" ), Controls.HomePageBlurbLabel, Controls.HomePageBlurbInnerFrame, Controls.HomePageBlurbFrame );
g_BBTextManager:ResetInstances();
--Basic Sectional Infos
local thisBBTextInstance = g_BBTextManager:GetInstance();
if thisBBTextInstance then
thisBBTextInstance.BBTextHeader:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_CITY_STATES_PAGE_LABEL" ));
UpdateSuperWideTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_CSTATES_HELP_TEXT" ), thisBBTextInstance.BBTextLabel, thisBBTextInstance.BBTextInnerFrame, thisBBTextInstance.BBTextFrame );
end
Controls.BBTextStack:SetHide( false );
ResizeEtc();
end;
CivilopediaCategory[CategoryTerrain].DisplayHomePage = function()
ClearArticle();
Controls.ArticleID:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_TERRAIN_PAGE_LABEL" ));
local portraitIndex = 9;
local portraitAtlas = "TERRAIN_ATLAS";
for row in DB.Query("SELECT PortraitIndex, IconAtlas from Terrains ORDER By Random() LIMIT 1") do
portraitIndex = row.PortraitIndex;
portraitAtlas = row.IconAtlas;
end
if IconHookup( portraitIndex, portraitSize, portraitAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
UpdateTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_QUOTE_BLOCK_TERRAIN" ), Controls.HomePageBlurbLabel, Controls.HomePageBlurbInnerFrame, Controls.HomePageBlurbFrame );
g_BBTextManager:ResetInstances();
--Basic Sectional Infos
local thisBBTextInstance = g_BBTextManager:GetInstance();
if thisBBTextInstance then
thisBBTextInstance.BBTextHeader:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_TERRAIN_LABEL" ));
UpdateSuperWideTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_TERRAIN_HELP_TEXT" ), thisBBTextInstance.BBTextLabel, thisBBTextInstance.BBTextInnerFrame, thisBBTextInstance.BBTextFrame );
end
Controls.BBTextStack:SetHide( false );
local thisBBTextInstance = g_BBTextManager:GetInstance();
if thisBBTextInstance then
thisBBTextInstance.BBTextHeader:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_TERRAIN_FEATURES_LABEL" ));
UpdateSuperWideTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_TERRAIN_FEATURES_HELP_TEXT" ), thisBBTextInstance.BBTextLabel, thisBBTextInstance.BBTextInnerFrame, thisBBTextInstance.BBTextFrame );
end
ResizeEtc();
end;
CivilopediaCategory[CategoryResources].DisplayHomePage = function()
ClearArticle();
Controls.ArticleID:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_RESOURCES_PAGE_LABEL" ));
local portraitIndex = 6;
local portraitAtlas = "RESOURCE_ATLAS";
for row in DB.Query("SELECT PortraitIndex, IconAtlas from Resources ORDER By Random() LIMIT 1") do
portraitIndex = row.PortraitIndex;
portraitAtlas = row.IconAtlas;
end
if IconHookup( portraitIndex, portraitSize, portraitAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
UpdateTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_QUOTE_BLOCK_RESOURCES" ), Controls.HomePageBlurbLabel, Controls.HomePageBlurbInnerFrame, Controls.HomePageBlurbFrame );
g_BBTextManager:ResetInstances();
--Basic Sectional Infos
local thisBBTextInstance = g_BBTextManager:GetInstance();
if thisBBTextInstance then
thisBBTextInstance.BBTextHeader:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_RESOURCES_PAGE_LABEL" ));
UpdateSuperWideTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_RESOURCES_HELP_TEXT" ), thisBBTextInstance.BBTextLabel, thisBBTextInstance.BBTextInnerFrame, thisBBTextInstance.BBTextFrame );
end
Controls.BBTextStack:SetHide( false );
ResizeEtc();
end;
CivilopediaCategory[CategoryImprovements].DisplayHomePage = function()
ClearArticle();
Controls.ArticleID:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_IMPROVEMENTS_PAGE_LABEL" ));
--eventually make random?
local portraitIndex = 1;
local portraitAtlas = "BW_ATLAS_1";
for row in DB.Query("SELECT PortraitIndex, IconAtlas from Improvements ORDER By Random() LIMIT 1") do
portraitIndex = row.PortraitIndex;
portraitAtlas = row.IconAtlas;
end
if IconHookup( portraitIndex, portraitSize, portraitAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
UpdateTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_QUOTE_BLOCK_IMPROVEMENTS" ), Controls.HomePageBlurbLabel, Controls.HomePageBlurbInnerFrame, Controls.HomePageBlurbFrame );
g_BBTextManager:ResetInstances();
--Basic Sectional Infos
local thisBBTextInstance = g_BBTextManager:GetInstance();
if thisBBTextInstance then
thisBBTextInstance.BBTextHeader:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_IMPROVEMENTS_PAGE_LABEL" ));
UpdateSuperWideTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_IMPROVEMENT_HELP_TEXT" ), thisBBTextInstance.BBTextLabel, thisBBTextInstance.BBTextInnerFrame, thisBBTextInstance.BBTextFrame );
end
Controls.BBTextStack:SetHide( false );
ResizeEtc();
end;
CivilopediaCategory[CategoryBeliefs].DisplayHomePage = function()
ClearArticle();
Controls.ArticleID:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_BELIEFS_PAGE_LABEL" ));
Controls.Portrait:SetTexture("Religion256.dds");
Controls.Portrait:SetTextureOffsetVal(0,0);
Controls.Portrait:SetHide(false);
Controls.PortraitFrame:SetHide(false);
UpdateTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_BELIEFS_HOMEPAGE_BLURB" ), Controls.HomePageBlurbLabel, Controls.HomePageBlurbInnerFrame, Controls.HomePageBlurbFrame );
g_BBTextManager:ResetInstances();
--Basic Sectional Infos
local thisBBTextInstance = g_BBTextManager:GetInstance();
if thisBBTextInstance then
thisBBTextInstance.BBTextHeader:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_BELIEFS_HOMEPAGE_LABEL1" ));
UpdateSuperWideTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_BELIEFS_HOMEPAGE_TEXT1" ), thisBBTextInstance.BBTextLabel, thisBBTextInstance.BBTextInnerFrame, thisBBTextInstance.BBTextFrame );
end
Controls.BBTextStack:SetHide( false );
ResizeEtc();
end;
CivilopediaCategory[CategoryWorldCongress].DisplayHomePage = function()
ClearArticle();
Controls.ArticleID:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_WORLD_CONGRESS_PAGE_LABEL" ));
Controls.Portrait:SetTexture("WorldCongressPortrait256_EXP2.dds");
Controls.Portrait:SetTextureOffsetVal(0,0);
Controls.Portrait:SetHide(false);
Controls.PortraitFrame:SetHide(false);
UpdateTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_WORLD_CONGRESS_HOMEPAGE_BLURB" ), Controls.HomePageBlurbLabel, Controls.HomePageBlurbInnerFrame, Controls.HomePageBlurbFrame );
g_BBTextManager:ResetInstances();
--Basic Sectional Infos
local thisBBTextInstance = g_BBTextManager:GetInstance();
if thisBBTextInstance then
thisBBTextInstance.BBTextHeader:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_WORLD_CONGRESS_HOMEPAGE_LABEL1" ));
UpdateSuperWideTextBlock( Locale.ConvertTextKey( "TXT_KEY_PEDIA_WORLD_CONGRESS_HOMEPAGE_TEXT1" ), thisBBTextInstance.BBTextLabel, thisBBTextInstance.BBTextInnerFrame, thisBBTextInstance.BBTextFrame );
end
Controls.BBTextStack:SetHide( false );
ResizeEtc();
end;
--------------------------------------------------------------------------------------------------------
-- a few handy-dandy helper functions
--------------------------------------------------------------------------------------------------------
-- put text into a text block and resize the block
function UpdateTextBlock( localizedString, label, innerFrame, outerFrame )
local contentSize;
local frameSize = {};
label:SetText( localizedString );
contentSize = label:GetSize();
frameSize.x = wideInnerFrameWidth;
frameSize.y = contentSize.y + textPaddingFromInnerFrame;
innerFrame:SetSize( frameSize );
frameSize.x = wideOuterFrameWidth;
frameSize.y = contentSize.y + textPaddingFromInnerFrame - offsetsBetweenFrames;
outerFrame:SetSize( frameSize );
outerFrame:SetHide( false );
end
function UpdateNarrowTextBlock( localizedString, label, innerFrame, outerFrame )
local contentSize;
local frameSize = {};
label:SetText( localizedString );
contentSize = label:GetSize();
frameSize.x = narrowInnerFrameWidth;
frameSize.y = contentSize.y + textPaddingFromInnerFrame;
innerFrame:SetSize( frameSize );
frameSize.x = narrowOuterFrameWidth;
frameSize.y = contentSize.y + textPaddingFromInnerFrame - offsetsBetweenFrames;
outerFrame:SetSize( frameSize );
outerFrame:SetHide( false );
end
function UpdateSuperWideTextBlock( localizedString, label, innerFrame, outerFrame )
local contentSize;
local frameSize = {};
label:SetText( localizedString );
contentSize = label:GetSize();
frameSize.x = superWideInnerFrameWidth;
frameSize.y = contentSize.y + textPaddingFromInnerFrame;
innerFrame:SetSize( frameSize );
frameSize.x = superWideOuterFrameWidth;
frameSize.y = contentSize.y + textPaddingFromInnerFrame - offsetsBetweenFrames;
outerFrame:SetSize( frameSize );
outerFrame:SetHide( false );
end
function UpdateButtonFrame( numButtonsAdded, innerFrame, outerFrame )
if numButtonsAdded > 0 then
local frameSize = {};
local h = (math.floor((numButtonsAdded - 1) / numberOfButtonsPerRow) + 1) * buttonSize + buttonPaddingTimesTwo;
frameSize.x = narrowInnerFrameWidth;
frameSize.y = h;
innerFrame:SetSize( frameSize );
frameSize.x = narrowOuterFrameWidth;
frameSize.y = h - offsetsBetweenFrames;
outerFrame:SetSize( frameSize );
outerFrame:SetHide( false );
end
end
-- MOD - Advanced Civilopedia
function UpdateWideButtonFrame( numButtonsAdded, innerFrame, outerFrame )
if numButtonsAdded > 0 then
local frameSize = {};
local h = (math.floor((numButtonsAdded - 1) / numberOfButtonsPerRowWide) + 1) * buttonSize + buttonPaddingTimesTwo;
frameSize.x = wideInnerFrameWidth;
frameSize.y = h;
innerFrame:SetSize( frameSize );
frameSize.x = wideOuterFrameWidth;
frameSize.y = h - offsetsBetweenFrames;
outerFrame:SetSize( frameSize );
outerFrame:SetHide( false );
end
end
-- MOD - Advanced Civilopedia
function UpdateSmallButtonFrame( numButtonsAdded, innerFrame, outerFrame )
if numButtonsAdded > 0 then
local frameSize = {};
local h = (math.floor((numButtonsAdded - 1) / numberOfButtonsPerRow) + 1) * smallbuttonSize + buttonPaddingTimesTwo;
frameSize.x = narrowInnerFrameWidth;
frameSize.y = h;
innerFrame:SetSize( frameSize );
frameSize.x = narrowOuterFrameWidth;
frameSize.y = h - offsetsBetweenFrames;
outerFrame:SetSize( frameSize );
outerFrame:SetHide( false );
end
end
function UpdateSmallButton( buttonAdded, image, button, textureSheet, textureOffset, category, localizedText, buttonId )
if(textureSheet ~= nil) then
image:SetTexture( textureSheet );
end
if(textureOffset ~= nil) then
image:SetTextureOffset( textureOffset );
end
button:SetOffsetVal( (buttonAdded % numberOfButtonsPerRow) * buttonSize + buttonPadding, math.floor(buttonAdded / numberOfButtonsPerRow) * buttonSize + buttonPadding );
button:SetToolTipString( localizedText );
if(category ~= nil) then
button:SetVoids( buttonId, addToList );
button:RegisterCallback( Mouse.eLClick, CivilopediaCategory[category].SelectArticle );
end
end
-- MOD - Advanced Civilopedia
function UpdateSmallButtonWide( buttonAdded, image, button, textureSheet, textureOffset, category, localizedText, buttonId )
if(textureSheet ~= nil) then
image:SetTexture( textureSheet );
end
if(textureOffset ~= nil) then
image:SetTextureOffset( textureOffset );
end
button:SetOffsetVal( (buttonAdded % numberOfButtonsPerRowWide) * (buttonSize + buttonPadding) + buttonPadding, math.floor(buttonAdded / numberOfButtonsPerRowWide) * buttonSize + buttonPadding );
button:SetToolTipString( localizedText );
if(category ~= nil) then
button:SetVoids( buttonId, addToList );
button:RegisterCallback( Mouse.eLClick, CivilopediaCategory[category].SelectArticle );
end
end
-- MOD - Advanced Civilopedia
function UpdateSmallButtonAlpha( buttonAdded, image, shadow, button, textureSheet, textureOffset, category, localizedText, buttonId )
if(textureSheet ~= nil) then
image:SetTexture( textureSheet );
shadow:SetTexture( textureSheet );
end
if(textureOffset ~= nil) then
image:SetTextureOffset( textureOffset );
shadow:SetTextureOffset( textureOffset );
end
button:SetOffsetVal( (buttonAdded % numberOfButtonsPerRow) * buttonSize + buttonPadding, math.floor(buttonAdded / numberOfButtonsPerRow) * buttonSize + buttonPadding );
button:SetToolTipString( localizedText );
if(category ~= nil) then
button:SetVoids( buttonId, addToList );
button:RegisterCallback( Mouse.eLClick, CivilopediaCategory[category].SelectArticle );
end
end
-- MOD - Advanced Civilopedia
function SearchForEliteUnitOwner( unitID, pProject )
for playerID = 0, GameDefines.MAX_CIV_PLAYERS - 1 do
if Players ~= nil then
local pPlayer = Players[playerID];
if (pPlayer) and (pPlayer:IsAlive()) then
if pPlayer:IsMinorCiv() then
return nil;
end
if pPlayer:IsBarbarian() then
return nil;
end
-- if (pPlayer:CanTrain(unitID, true, true, true, false)) then
-- return pPlayer;
-- end
if ( Teams[pPlayer:GetTeam()]:GetProjectCount( pProject.ID ) > 0 ) then
-- if ( Teams[Players[pPlayer]:GetTeam()]:GetProjectCount( 0 ) > 0 ) then
return pPlayer;
end
end
end
end
return nil;
end
-- this will need to be enhanced to look at the current language
function TagExists( tag )
return Locale.HasTextKey(tag);
end
--------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------
CivilopediaCategory[CategoryHomePage].SelectArticle = function( pageID, shouldAddToList )
ClearArticle();
if pageID == 1 then
if selectedCategory ~= CategoryHomePage then
SetSelectedCategory(CategoryHomePage);
end
CivilopediaCategory[CategoryHomePage].DisplayHomePage();
elseif pageID == 2 then
if selectedCategory ~= CategoryGameConcepts then
SetSelectedCategory(CategoryGameConcepts);
end
CivilopediaCategory[CategoryGameConcepts].DisplayHomePage();
elseif pageID == 3 then
if selectedCategory ~= CategoryTech then
SetSelectedCategory(CategoryTech);
end
CivilopediaCategory[CategoryTech].DisplayHomePage();
elseif pageID == 4 then
if selectedCategory ~= CategoryUnits then
SetSelectedCategory(CategoryUnits);
end
CivilopediaCategory[CategoryUnits].DisplayHomePage();
elseif pageID == 5 then
if selectedCategory ~= CategoryPromotions then
SetSelectedCategory(CategoryPromotions);
end
CivilopediaCategory[CategoryPromotions].DisplayHomePage() ;
elseif pageID == 6 then
if selectedCategory ~= CategoryBuildings then
SetSelectedCategory(CategoryBuildings);
end
CivilopediaCategory[CategoryBuildings].DisplayHomePage();
elseif pageID == 7 then
if selectedCategory ~= CategoryWonders then
SetSelectedCategory(CategoryWonders);
end
CivilopediaCategory[CategoryWonders].DisplayHomePage();
elseif pageID == 8 then
if selectedCategory ~= CategoryPolicies then
SetSelectedCategory(CategoryPolicies);
end
CivilopediaCategory[CategoryPolicies].DisplayHomePage() ;
elseif pageID == 9 then
if selectedCategory ~= CategoryPeople then
SetSelectedCategory(CategoryPeople);
end
CivilopediaCategory[CategoryPeople].DisplayHomePage() ;
elseif pageID == 10 then
if selectedCategory ~= CategoryCivilizations then
SetSelectedCategory(CategoryCivilizations);
end
CivilopediaCategory[CategoryCivilizations].DisplayHomePage() ;
elseif pageID == 11 then
if selectedCategory ~= CategoryCityStates then
SetSelectedCategory(CategoryCityStates);
end
CivilopediaCategory[CategoryCityStates].DisplayHomePage() ;
elseif pageID == 12 then
if selectedCategory ~= CategoryTerrain then
SetSelectedCategory(CategoryTerrain);
end
CivilopediaCategory[CategoryTerrain].DisplayHomePage();
elseif pageID == 13 then
if selectedCategory ~= CategoryResources then
SetSelectedCategory(CategoryResources);
end
CivilopediaCategory[CategoryResources].DisplayHomePage() ;
elseif pageID == 14 then
if selectedCategory ~= CategoryImprovements then
SetSelectedCategory(CategoryImprovements);
end
CivilopediaCategory[CategoryImprovements].DisplayHomePage() ;
elseif pageID == CategoryBeliefs then
if selectedCategory ~= pageID then
SetSelectedCategory(pageID);
end
CivilopediaCategory[pageID].DisplayHomePage();
elseif pageID == CategoryWorldCongress then
if selectedCategory ~= pageID then
SetSelectedCategory(pageID);
end
CivilopediaCategory[pageID].DisplayHomePage();
else
print("couldn't find category home page");
end
ResizeEtc();
end
CivilopediaCategory[CategoryGameConcepts].SelectArticle = function( conceptID, shouldAddToList )
print("CivilopediaCategory[CategoryGameConcepts].SelectArticle");
if selectedCategory ~= CategoryGameConcepts then
SetSelectedCategory(CategoryGameConcepts);
end
ClearArticle();
if shouldAddToList == addToList then
currentTopic = currentTopic + 1;
listOfTopicsViewed[currentTopic] = categorizedList[(CategoryGameConcepts * absurdlyLargeNumTopicsInCategory) + conceptID];
for i = currentTopic + 1, endTopic, 1 do
listOfTopicsViewed[i] = nil;
end
endTopic = currentTopic;
end
if conceptID ~= -1 then
local thisConcept = GameInfo.Concepts[conceptID];
if thisConcept then
-- update the name
local name = Locale.ConvertTextKey( thisConcept.Description );
Controls.ArticleID:SetText( name );
-- portrait
-- update the summary
if thisConcept.Summary then
UpdateTextBlock( Locale.ConvertTextKey( thisConcept.Summary ), Controls.SummaryLabel, Controls.SummaryInnerFrame, Controls.SummaryFrame );
end
-- update the extended article
if thisConcept.Extended then
UpdateTextBlock( Locale.ConvertTextKey( thisConcept.Extended ), Controls.ExtendedLabel, Controls.ExtendedInnerFrame, Controls.ExtendedFrame );
end
-- update the Designer's Notes
if thisConcept.DesignNotes then
UpdateTextBlock( Locale.ConvertTextKey( thisConcept.DesignNotes ), Controls.DNotesLabel, Controls.DNotesInnerFrame, Controls.DNotesFrame );
end
-- related images
-- related concepts
end
end
ResizeEtc();
end
CivilopediaCategory[CategoryTech].SelectArticle = function( techID, shouldAddToList )
print("CivilopediaCategory[CategoryTech].SelectArticle");
if selectedCategory ~= CategoryTech then
SetSelectedCategory(CategoryTech);
end
ClearArticle();
if shouldAddToList == addToList then
currentTopic = currentTopic + 1;
listOfTopicsViewed[currentTopic] = categorizedList[(CategoryTech * absurdlyLargeNumTopicsInCategory) + techID];
for i = currentTopic + 1, endTopic, 1 do
listOfTopicsViewed[i] = nil;
end
endTopic = currentTopic;
end
if techID ~= -1 then
local thisTech = GameInfo.Technologies[techID];
local name = Locale.ConvertTextKey( thisTech.Description );
Controls.ArticleID:SetText( name );
-- if we have one, update the tech picture
if IconHookup( thisTech.PortraitIndex, portraitSize, thisTech.IconAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
-- update the cost
Controls.CostFrame:SetHide( false );
local cost = thisTech.Cost;
if(Game ~= nil) then
local pPlayer = Players[Game.GetActivePlayer()];
local pTeam = Teams[pPlayer:GetTeam()];
local pTeamTechs = pTeam:GetTeamTechs();
cost = pTeamTechs:GetResearchCost(techID);
end
if (cost > 0) then
Controls.CostLabel:SetText( tostring(cost).." [ICON_RESEARCH]" );
else
Controls.CostLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_FREE" ) );
end
local contentSize;
local frameSize = {};
local buttonAdded = 0;
local techType = thisTech.Type;
local condition = "TechType = '" .. techType .. "'";
local prereqCondition = "PrereqTech = '" .. techType .. "'";
local otherPrereqCondition = "TechPrereq = '" .. techType .. "'";
local revealCondition = "TechReveal = '" .. techType .. "'";
-- update the prereq techs
g_PrereqTechManager:ResetInstances();
buttonAdded = 0;
for row in GameInfo.Technology_PrereqTechs( condition ) do
local prereq = GameInfo.Technologies[row.PrereqTech];
local thisPrereqInstance = g_PrereqTechManager:GetInstance();
if thisPrereqInstance then
local textureOffset, textureSheet = IconLookup( prereq.PortraitIndex, buttonSize, prereq.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisPrereqInstance.PrereqTechImage, thisPrereqInstance.PrereqTechButton, textureSheet, textureOffset, CategoryTech, Locale.ConvertTextKey( prereq.Description ), prereq.ID );
buttonAdded = buttonAdded + 1;
end
end
UpdateButtonFrame( buttonAdded, Controls.PrereqTechInnerFrame, Controls.PrereqTechFrame );
-- update the leads to techs
g_LeadsToTechManager:ResetInstances();
buttonAdded = 0;
for row in GameInfo.Technology_PrereqTechs( prereqCondition ) do
local leadsTo = GameInfo.Technologies[row.TechType];
local thisLeadsToInstance = g_LeadsToTechManager:GetInstance();
if thisLeadsToInstance then
local textureOffset, textureSheet = IconLookup( leadsTo.PortraitIndex, buttonSize, leadsTo.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisLeadsToInstance.LeadsToTechImage, thisLeadsToInstance.LeadsToTechButton, textureSheet, textureOffset, CategoryTech, Locale.ConvertTextKey( leadsTo.Description ), leadsTo.ID );
buttonAdded = buttonAdded + 1;
end
end
UpdateButtonFrame( buttonAdded, Controls.LeadsToTechInnerFrame, Controls.LeadsToTechFrame );
-- update the units unlocked
g_UnlockedUnitsManager:ResetInstances();
buttonAdded = 0;
for thisUnitInfo in GameInfo.Units( prereqCondition ) do
if thisUnitInfo.ShowInPedia then
local thisUnitInstance = g_UnlockedUnitsManager:GetInstance();
if thisUnitInstance then
local textureOffset, textureSheet = IconLookup( thisUnitInfo.PortraitIndex, buttonSize, thisUnitInfo.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisUnitInstance.UnlockedUnitImage, thisUnitInstance.UnlockedUnitButton, textureSheet, textureOffset, CategoryUnits, Locale.ConvertTextKey( thisUnitInfo.Description ), thisUnitInfo.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.UnlockedUnitsInnerFrame, Controls.UnlockedUnitsFrame );
-- update the buildings unlocked
g_UnlockedBuildingsManager:ResetInstances();
buttonAdded = 0;
for thisBuildingInfo in GameInfo.Buildings( prereqCondition ) do
local thisBuildingInstance = g_UnlockedBuildingsManager:GetInstance();
if thisBuildingInstance then
if not IconHookup( thisBuildingInfo.PortraitIndex, buttonSize, thisBuildingInfo.IconAtlas, thisBuildingInstance.UnlockedBuildingImage ) then
thisBuildingInstance.UnlockedBuildingImage:SetTexture( defaultErrorTextureSheet );
thisBuildingInstance.UnlockedBuildingImage:SetTextureOffset( nullOffset );
end
--move this button
thisBuildingInstance.UnlockedBuildingButton:SetOffsetVal( (buttonAdded % numberOfButtonsPerRow) * buttonSize + buttonPadding, math.floor(buttonAdded / numberOfButtonsPerRow) * buttonSize + buttonPadding );
thisBuildingInstance.UnlockedBuildingButton:SetToolTipString( Locale.ConvertTextKey( thisBuildingInfo.Description ) );
thisBuildingInstance.UnlockedBuildingButton:SetVoids( thisBuildingInfo.ID, addToList );
local thisBuildingClass = GameInfo.BuildingClasses[thisBuildingInfo.BuildingClass];
if thisBuildingClass.MaxGlobalInstances > 0 or (thisBuildingClass.MaxPlayerInstances == 1 and thisBuildingInfo.SpecialistCount == 0) or thisBuildingClass.MaxTeamInstances > 0 then
thisBuildingInstance.UnlockedBuildingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryWonders].SelectArticle );
else
thisBuildingInstance.UnlockedBuildingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryBuildings].SelectArticle );
end
buttonAdded = buttonAdded + 1;
end
end
UpdateButtonFrame( buttonAdded, Controls.UnlockedBuildingsInnerFrame, Controls.UnlockedBuildingsFrame );
-- update the projects unlocked
g_UnlockedProjectsManager:ResetInstances();
buttonAdded = 0;
for thisProjectInfo in GameInfo.Projects( otherPrereqCondition ) do
local bIgnore = projectsToIgnore[thisProjectInfo.Type];
if(bIgnore ~= true) then
local thisProjectInstance = g_UnlockedProjectsManager:GetInstance();
if thisProjectInstance then
local textureOffset, textureSheet = IconLookup( thisProjectInfo.PortraitIndex, buttonSize, thisProjectInfo.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisProjectInstance.UnlockedProjectImage, thisProjectInstance.UnlockedProjectButton, textureSheet, textureOffset, CategoryWonders, Locale.ConvertTextKey( thisProjectInfo.Description ), thisProjectInfo.ID + 1000);
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.UnlockedProjectsInnerFrame, Controls.UnlockedProjectsFrame );
-- update the resources revealed
g_RevealedResourcesManager:ResetInstances();
buttonAdded = 0;
for revealedResource in GameInfo.Resources( revealCondition ) do
local thisRevealedResourceInstance = g_RevealedResourcesManager:GetInstance();
if thisRevealedResourceInstance then
local textureOffset, textureSheet = IconLookup( revealedResource.PortraitIndex, buttonSize, revealedResource.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisRevealedResourceInstance.RevealedResourceImage, thisRevealedResourceInstance.RevealedResourceButton, textureSheet, textureOffset, CategoryResources, Locale.ConvertTextKey( revealedResource.Description ), revealedResource.ID );
buttonAdded = buttonAdded + 1;
end
end
UpdateButtonFrame( buttonAdded, Controls.RevealedResourcesInnerFrame, Controls.RevealedResourcesFrame );
-- update the build actions unlocked
g_WorkerActionsManager:ResetInstances();
buttonAdded = 0;
for thisBuildInfo in GameInfo.Builds{PrereqTech = techType, ShowInPedia = 1} do
local thisWorkerActionInstance = g_WorkerActionsManager:GetInstance();
if thisWorkerActionInstance then
local textureOffset, textureSheet = IconLookup( thisBuildInfo.IconIndex, buttonSize, thisBuildInfo.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
if thisBuildInfo.RouteType then
UpdateSmallButton( buttonAdded, thisWorkerActionInstance.WorkerActionImage, thisWorkerActionInstance.WorkerActionButton, textureSheet, textureOffset, CategoryImprovements, Locale.ConvertTextKey( thisBuildInfo.Description ), GameInfo.Routes[thisBuildInfo.RouteType].ID + 1000 );
elseif thisBuildInfo.ImprovementType then
UpdateSmallButton( buttonAdded, thisWorkerActionInstance.WorkerActionImage, thisWorkerActionInstance.WorkerActionButton, textureSheet, textureOffset, CategoryImprovements, Locale.ConvertTextKey( thisBuildInfo.Description ), GameInfo.Improvements[thisBuildInfo.ImprovementType].ID );-- add fudge factor
else -- we are a choppy thing
UpdateSmallButton( buttonAdded, thisWorkerActionInstance.WorkerActionImage, thisWorkerActionInstance.WorkerActionButton, textureSheet, textureOffset, CategoryGameConcepts, Locale.ConvertTextKey( thisBuildInfo.Description ), GameInfo.Concepts["CONCEPT_WORKERS_CLEARINGLAND"].ID );-- add fudge factor
end
buttonAdded = buttonAdded + 1;
end
end
UpdateButtonFrame( buttonAdded, Controls.WorkerActionsInnerFrame, Controls.WorkerActionsFrame );
local obsoleteCondition = "ObsoleteTech = '" .. techType .. "'";
-- MOD - Advanced Civilopedia
-- update the units obsolete
g_ObsoleteUnitManager:ResetInstances();
buttonAdded = 0;
for thisUnitInfo in GameInfo.Units( obsoleteCondition ) do
if thisUnitInfo.ShowInPedia then
local thisUnitInstance = g_ObsoleteUnitManager:GetInstance();
if thisUnitInstance then
local textureOffset, textureSheet = IconLookup( thisUnitInfo.PortraitIndex, buttonSize, thisUnitInfo.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisUnitInstance.ObsoleteUnitImage, thisUnitInstance.ObsoleteUnitButton, textureSheet, textureOffset, CategoryUnits, Locale.ConvertTextKey( thisUnitInfo.Description ), thisUnitInfo.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.ObsoleteUnitInnerFrame, Controls.ObsoleteUnitFrame );
-- update the buildings obsolete
g_ObsoleteBuildingManager:ResetInstances();
buttonAdded = 0;
for thisBuildingInfo in GameInfo.Buildings( obsoleteCondition ) do
local thisBuildingInstance = g_ObsoleteBuildingManager:GetInstance();
if thisBuildingInstance then
local textureOffset, textureSheet = IconLookup( thisBuildingInfo.PortraitIndex, buttonSize, thisBuildingInfo.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisBuildingInstance.ObsoleteBuildingImage, thisBuildingInstance.ObsoleteBuildingButton, textureSheet, textureOffset, CategoryBuildings, Locale.ConvertTextKey( thisBuildingInfo.Description ), thisBuildingInfo.ID );
buttonAdded = buttonAdded + 1;
end
end
UpdateButtonFrame( buttonAdded, Controls.ObsoleteBuildingInnerFrame, Controls.ObsoleteBuildingFrame );
-- update the related articles
Controls.RelatedArticlesFrame:SetHide( true ); -- todo: figure out how this should be implemented
-- update the game info
if (thisTech.Help) then
UpdateTextBlock( Locale.ConvertTextKey( thisTech.Help ), Controls.GameInfoLabel, Controls.GameInfoInnerFrame, Controls.GameInfoFrame );
end
-- update the quote
if thisTech.Quote then
UpdateTextBlock( Locale.ConvertTextKey( thisTech.Quote ), Controls.SilentQuoteLabel, Controls.SilentQuoteInnerFrame, Controls.SilentQuoteFrame );
end
--Controls.QuoteLabel:SetText( Locale.ConvertTextKey( thisTech.Quote ) );
--contentSize = Controls.QuoteLabel:GetSize();
--frameSize.x = wideInnerFrameWidth;
--frameSize.y = contentSize.y + textPaddingFromInnerFrame + quoteButtonOffset;
--Controls.QuoteInnerFrame:SetSize( frameSize );
--frameSize.x = wideOuterFrameWidth;
--frameSize.y = contentSize.y + textPaddingFromInnerFrame - offsetsBetweenFrames + quoteButtonOffset;
--Controls.QuoteFrame:SetSize( frameSize );
--Controls.QuoteFrame:SetHide( false );
-- update the special abilites
local abilitiesString = "";
local numAbilities = 0;
for row in GameInfo.Route_TechMovementChanges( condition ) do
if numAbilities > 0 then
abilitiesString = abilitiesString .. "[NEWLINE]";
end
abilitiesString = abilitiesString .. Locale.ConvertTextKey("TXT_KEY_CIVILOPEDIA_SPECIALABILITIES_MOVEMENT", GameInfo.Routes[row.RouteType].Description);
numAbilities = numAbilities + 1;
end
for row in GameInfo.Improvement_TechYieldChanges( condition ) do
if numAbilities > 0 then
abilitiesString = abilitiesString .. "[NEWLINE]";
end
abilitiesString = abilitiesString .. Locale.ConvertTextKey("TXT_KEY_CIVILOPEDIA_SPECIALABILITIES_YIELDCHANGES", GameInfo.Improvements[row.ImprovementType].Description, GameInfo.Yields[row.YieldType].Description, row.Yield);
numAbilities = numAbilities + 1;
end
for row in GameInfo.Improvement_TechNoFreshWaterYieldChanges( condition ) do
if numAbilities > 0 then
abilitiesString = abilitiesString .. "[NEWLINE]";
end
abilitiesString = abilitiesString .. Locale.ConvertTextKey("TXT_KEY_CIVILOPEDIA_SPECIALABILITIES_NOFRESHWATERYIELDCHANGES", GameInfo.Improvements[row.ImprovementType].Description, GameInfo.Yields[row.YieldType].Description, row.Yield );
numAbilities = numAbilities + 1;
end
for row in GameInfo.Improvement_TechFreshWaterYieldChanges( condition ) do
if numAbilities > 0 then
abilitiesString = abilitiesString .. "[NEWLINE]";
end
abilitiesString = abilitiesString .. Locale.ConvertTextKey("TXT_KEY_CIVILOPEDIA_SPECIALABILITIES_FRESHWATERYIELDCHANGES", GameInfo.Improvements[row.ImprovementType].Description, GameInfo.Yields[row.YieldType].Description, row.Yield );
numAbilities = numAbilities + 1;
end
if thisTech.EmbarkedMoveChange > 0 then
if numAbilities > 0 then
abilitiesString = abilitiesString .. "[NEWLINE]";
end
abilitiesString = abilitiesString .. Locale.ConvertTextKey( "TXT_KEY_ABLTY_FAST_EMBARK_STRING" );
numAbilities = numAbilities + 1;
end
if thisTech.AllowsEmbarking then
if numAbilities > 0 then
abilitiesString = abilitiesString .. "[NEWLINE]";
end
abilitiesString = abilitiesString .. Locale.ConvertTextKey( "TXT_KEY_ALLOWS_EMBARKING" );
numAbilities = numAbilities + 1;
end
if thisTech.AllowsDefensiveEmbarking then
if numAbilities > 0 then
abilitiesString = abilitiesString .. "[NEWLINE]";
end
abilitiesString = abilitiesString .. Locale.ConvertTextKey( "TXT_KEY_ABLTY_DEFENSIVE_EMBARK_STRING" );
numAbilities = numAbilities + 1;
end
if thisTech.EmbarkedAllWaterPassage then
if numAbilities > 0 then
abilitiesString = abilitiesString .. "[NEWLINE]";
end
abilitiesString = abilitiesString .. Locale.ConvertTextKey( "TXT_KEY_ABLTY_OCEAN_EMBARK_STRING" );
numAbilities = numAbilities + 1;
end
if thisTech.AllowEmbassyTradingAllowed then
if numAbilities > 0 then
abilitiesString = abilitiesString .. "[NEWLINE]";
end
abilitiesString = abilitiesString .. Locale.ConvertTextKey( "TXT_KEY_ABLTY_ALLOW_EMBASSY_STRING" );
numAbilities = numAbilities + 1;
end
if thisTech.OpenBordersTradingAllowed then
if numAbilities > 0 then
abilitiesString = abilitiesString .. "[NEWLINE]";
end
abilitiesString = abilitiesString .. Locale.ConvertTextKey( "TXT_KEY_ABLTY_OPEN_BORDER_STRING" );
numAbilities = numAbilities + 1;
end
if thisTech.DefensivePactTradingAllowed then
if numAbilities > 0 then
abilitiesString = abilitiesString .. "[NEWLINE]";
end
abilitiesString = abilitiesString .. Locale.ConvertTextKey( "TXT_KEY_ABLTY_D_PACT_STRING" );
numAbilities = numAbilities + 1;
end
if thisTech.ResearchAgreementTradingAllowed then
if numAbilities > 0 then
abilitiesString = abilitiesString .. "[NEWLINE]";
end
abilitiesString = abilitiesString .. Locale.ConvertTextKey( "TXT_KEY_ABLTY_R_PACT_STRING" );
numAbilities = numAbilities + 1;
end
if thisTech.TradeAgreementTradingAllowed then
if numAbilities > 0 then
abilitiesString = abilitiesString .. "[NEWLINE]";
end
abilitiesString = abilitiesString .. Locale.ConvertTextKey( "TXT_KEY_ABLTY_T_PACT_STRING" );
numAbilities = numAbilities + 1;
end
if thisTech.BridgeBuilding then
if numAbilities > 0 then
abilitiesString = abilitiesString .. "[NEWLINE]";
end
abilitiesString = abilitiesString .. Locale.ConvertTextKey( "TXT_KEY_ABLTY_BRIDGE_STRING" );
numAbilities = numAbilities + 1;
end
if numAbilities > 0 then
UpdateTextBlock( Locale.ConvertTextKey( abilitiesString ), Controls.AbilitiesLabel, Controls.AbilitiesInnerFrame, Controls.AbilitiesFrame );
else
Controls.AbilitiesFrame:SetHide( true );
end
-- update the historical info
if (thisTech.Civilopedia) then
UpdateTextBlock( Locale.ConvertTextKey( thisTech.Civilopedia ), Controls.HistoryLabel, Controls.HistoryInnerFrame, Controls.HistoryFrame );
end
-- update the related images
Controls.RelatedImagesFrame:SetHide( true );
end
ResizeEtc();
end
CivilopediaCategory[CategoryUnits].SelectArticle = function( unitID, shouldAddToList )
print("CivilopediaCategory[CategoryUnits].SelectArticle");
if selectedCategory ~= CategoryUnits then
SetSelectedCategory(CategoryUnits);
end
ClearArticle();
if shouldAddToList == addToList then
currentTopic = currentTopic + 1;
listOfTopicsViewed[currentTopic] = categorizedList[(CategoryUnits * absurdlyLargeNumTopicsInCategory) + unitID];
for i = currentTopic + 1, endTopic, 1 do
listOfTopicsViewed[i] = nil;
end
endTopic = currentTopic;
end
if unitID ~= -1 then
local thisUnit = GameInfo.Units[unitID];
-- update the name
local name = Locale.ConvertTextKey( thisUnit.Description );
Controls.ArticleID:SetText( name );
-- update the portrait
if IconHookup( thisUnit.PortraitIndex, portraitSize, thisUnit.IconAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
-- MOD - update the flag atlas
g_UnitFlagAtlasManager:ResetInstances();
buttonAdded = 0;
local thisUnitFlagAtlasInstance = g_UnitFlagAtlasManager:GetInstance();
if thisUnitFlagAtlasInstance then
local textureOffset, textureSheet = IconLookup( thisUnit.UnitFlagIconOffset, 32, thisUnit.UnitFlagAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
local bColorChanged = false;
for row in GameInfo.Civilization_UnitClassOverrides{UnitType = thisUnit.Type} do
local thisCivilization = GameInfo.Civilizations[row.CivilizationType];
local thisColorSet = GameInfo.PlayerColors[thisCivilization.DefaultPlayerColor];
if (thisColorSet) then
local primaryColor = GameInfo.Colors[thisColorSet.PrimaryColor];
local secondaryColor = GameInfo.Colors[thisColorSet.SecondaryColor];
local iconColor = {x = primaryColor.Red, y = primaryColor.Green, z = primaryColor.Blue, w = primaryColor.Alpha};
local backColor = {x = secondaryColor.Red, y = secondaryColor.Green, z = secondaryColor.Blue, w = secondaryColor.Alpha};
bColorChanged = true;
thisUnitFlagAtlasInstance.UnitFlagAtlasImage:SetColor( iconColor );
thisUnitFlagAtlasInstance.UnitFlagAtlasImageBackground:SetColor( backColor );
end
end
if (not bColorChanged) then
if (thisUnit.ProjectPrereq) then
bColorChanged = true;
local prereqProject = GameInfo.Projects[thisUnit.ProjectPrereq];
local iMaxInstances = prereqProject.MaxGlobalInstances;
if (iMaxInstances == 1) then
local pPlayer = SearchForEliteUnitOwner( unitID, prereqProject );
if (pPlayer ~= nil) then
local iconColor, backColor = pPlayer:GetPlayerColors();
thisUnitFlagAtlasInstance.UnitFlagAtlasImage:SetColor( iconColor );
thisUnitFlagAtlasInstance.UnitFlagAtlasImageBackground:SetColor( backColor );
else -- set it to a certain color
thisUnitFlagAtlasInstance.UnitFlagAtlasImage:SetColor( colorRed );
thisUnitFlagAtlasInstance.UnitFlagAtlasImageBackground:SetColor( colorWhite );
end
else
local bFinished = false;
if ( Game ~= nil ) then
local pPlayer = Players[Game.GetActivePlayer()];
if ((Teams[pPlayer:GetTeam()]:GetProjectCount( prereqProject.ID ) > 0)) then
bFinished = true;
end
end
if bFinished then
if pPlayer == nil then
return
end
local iconColor, backColor = pPlayer:GetPlayerColors();
thisUnitFlagAtlasInstance.UnitFlagAtlasImage:SetColor( iconColor );
thisUnitFlagAtlasInstance.UnitFlagAtlasImageBackground:SetColor( backColor );
else
thisUnitFlagAtlasInstance.UnitFlagAtlasImage:SetColor( colorSkyBlue );
thisUnitFlagAtlasInstance.UnitFlagAtlasImageBackground:SetColor( colorWhite );
end
end
end
end
if (thisUnit.Trade) then
thisUnitFlagAtlasInstance.UnitFlagAtlasImageShadow:SetOffsetVal( -1, -3 );
else
thisUnitFlagAtlasInstance.UnitFlagAtlasImageShadow:SetOffsetVal( -1, 1 );
end
if (not bColorChanged) then
thisUnitFlagAtlasInstance.UnitFlagAtlasImage:SetColor( colorWhite );
thisUnitFlagAtlasInstance.UnitFlagAtlasImageBackground:SetColor( colorBlack );
end
UpdateSmallButtonAlpha( buttonAdded, thisUnitFlagAtlasInstance.UnitFlagAtlasImage, thisUnitFlagAtlasInstance.UnitFlagAtlasImageShadow, thisUnitFlagAtlasInstance.UnitFlagAtlasButton, textureSheet, textureOffset, CategoryUnits, Locale.ConvertTextKey( thisUnit.Description ), thisUnit.ID );
buttonAdded = buttonAdded + 1;
end
UpdateSmallButtonFrame( buttonAdded, Controls.UnitFlagAtlasInnerFrame, Controls.UnitFlagAtlasFrame );
-- MOD - update the max instances
local thisUnitClass = GameInfo.UnitClasses[thisUnit.Class];
local bMaxInstance = false;
local instanceString = "";
if thisUnitClass then
local bMaxPlayerInstance = false;
if (thisUnitClass.MaxPlayerInstances ~= -1) then
instanceString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_MAX_PLAYER_INSTANCES", thisUnitClass.MaxPlayerInstances );
bMaxPlayerInstance = true;
bMaxInstance = true;
end
if (thisUnitClass.MaxGlobalInstances ~= -1) then
instanceString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_MAX_GLOBAL_INSTANCES", thisUnitClass.MaxGlobalInstances );
bMaxInstance = true;
end
end
if bMaxInstance then
UpdateNarrowTextBlock( instanceString, Controls.MaxInstancesLabel, Controls.MaxInstancesInnerFrame, Controls.MaxInstancesFrame )
end
-- update the cost
Controls.CostFrame:SetHide( false );
local costString = "";
local cost = thisUnit.Cost;
local faithCost = thisUnit.FaithCost;
if(Game and not Game.IsOption(GameOptionTypes.GAMEOPTION_NO_RELIGION)) then
faithCost = Game.GetFaithCost(unitID);
end
if(Game ~= nil) then
cost = Players[Game.GetActivePlayer()]:GetUnitProductionNeeded( unitID );
end
if(cost == 1 and faithCost > 0) then
costString = tostring(faithCost) .. " [ICON_PEACE]";
elseif(cost > 0 and faithCost > 0) then
costString = Locale.Lookup("TXT_KEY_PEDIA_A_OR_B", tostring(cost) .. " [ICON_PRODUCTION]", tostring(faithCost) .. " [ICON_PEACE");
else
if(cost > 0) then
costString = tostring(cost) .. " [ICON_PRODUCTION]";
elseif(faithCost > 0) then
costString = tostring(faithCost) .. " [ICON_PEACE]";
else
costString = Locale.Lookup("TXT_KEY_FREE");
if(thisUnit.Type == "UNIT_SETTLER") then
Controls.CostFrame:SetHide(true);
end
end
end
Controls.CostLabel:SetText(costString);
-- update the Combat value
local combat = thisUnit.Combat;
if combat > 0 then
Controls.CombatLabel:SetText( tostring(combat).." [ICON_STRENGTH]" );
Controls.CombatFrame:SetHide( false );
end
-- update the Ranged Combat value
local rangedCombat = thisUnit.RangedCombat;
if rangedCombat > 0 then
Controls.RangedCombatLabel:SetText( tostring(rangedCombat).." [ICON_RANGE_STRENGTH]" );
Controls.RangedCombatFrame:SetHide( false );
end
-- update the Ranged Combat value
local rangedCombatRange = thisUnit.Range;
if rangedCombatRange > 0 then
Controls.RangedCombatRangeLabel:SetText( tostring(rangedCombatRange) );
Controls.RangedCombatRangeFrame:SetHide( false );
end
-- MOD - update the Combat Type value
if thisUnit.CombatClass then
local texts = "[ICON_BULLET]" .. Locale.ConvertTextKey( GameInfo.UnitCombatInfos[thisUnit.CombatClass].Description );
UpdateNarrowTextBlock( texts, Controls.CombatTypeLabel, Controls.CombatTypeInnerFrame, Controls.CombatTypeFrame );
end
-- update the Movement value
local movementRange = thisUnit.Moves;
if movementRange > 0 then
if thisUnit.Domain ~= "DOMAIN_AIR" then
Controls.MovementLabel:SetText( tostring(movementRange).." [ICON_MOVES]" );
Controls.MovementFrame:SetHide( false );
end
end
local contentSize;
local frameSize = {};
local buttonAdded = 0;
-- update the free promotions
g_PromotionsManager:ResetInstances();
buttonAdded = 0;
local condition = "UnitType = '" .. thisUnit.Type .. "'";
for row in GameInfo.Unit_FreePromotions( condition ) do
local promotion = GameInfo.UnitPromotions[row.PromotionType];
if promotion then
local thisPromotionInstance = g_PromotionsManager:GetInstance();
if thisPromotionInstance then
local textureOffset, textureSheet = IconLookup( promotion.PortraitIndex, buttonSize, promotion.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisPromotionInstance.PromotionImage, thisPromotionInstance.PromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( promotion.Description ), promotion.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.FreePromotionsInnerFrame, Controls.FreePromotionsFrame );
-- MOD - update the required resources
Controls.RequiredResourcesLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_REQ_RESRC_LABEL" ) );
g_RequiredResourcesManager:ResetInstances();
buttonAdded = 0;
local condition = "UnitType = '" .. thisUnit.Type .. "'";
for row in GameInfo.Unit_ResourceQuantityRequirements( condition ) do
local requiredResource = GameInfo.Resources[row.ResourceType];
if requiredResource then
local thisRequiredResourceInstance = g_RequiredResourcesManager:GetInstance();
if thisRequiredResourceInstance then
local textureOffset, textureSheet = IconLookup( requiredResource.PortraitIndex, buttonSize, requiredResource.IconAtlas );
local description = row.Cost .. " " .. Locale.ConvertTextKey( requiredResource.Description );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisRequiredResourceInstance.RequiredResourceImage, thisRequiredResourceInstance.RequiredResourceButton, textureSheet, textureOffset, CategoryResources, description, requiredResource.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.RequiredResourcesInnerFrame, Controls.RequiredResourcesFrame );
-- update the prereq techs
g_PrereqTechManager:ResetInstances();
buttonAdded = 0;
if thisUnit.PrereqTech then
local prereq = GameInfo.Technologies[thisUnit.PrereqTech];
if prereq then
local thisPrereqInstance = g_PrereqTechManager:GetInstance();
if thisPrereqInstance then
local textureOffset, textureSheet = IconLookup( prereq.PortraitIndex, buttonSize, prereq.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisPrereqInstance.PrereqTechImage, thisPrereqInstance.PrereqTechButton, textureSheet, textureOffset, CategoryTech, Locale.ConvertTextKey( prereq.Description ), prereq.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.PrereqTechInnerFrame, Controls.PrereqTechFrame );
-- update the obsolete techs
g_ObsoleteTechManager:ResetInstances();
buttonAdded = 0;
if thisUnit.ObsoleteTech then
local obs = GameInfo.Technologies[thisUnit.ObsoleteTech];
if obs then
local thisTechInstance = g_ObsoleteTechManager:GetInstance();
if thisTechInstance then
local textureOffset, textureSheet = IconLookup( obs.PortraitIndex, buttonSize, obs.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisTechInstance.ObsoleteTechImage, thisTechInstance.ObsoleteTechButton, textureSheet, textureOffset, CategoryTech, Locale.ConvertTextKey( obs.Description ), obs.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.ObsoleteTechInnerFrame, Controls.ObsoleteTechFrame );
-- update the Upgrade units
g_UpgradeManager:ResetInstances();
buttonAdded = 0;
if(Game ~= nil) then
local iUnitUpgrade = Game.GetUnitUpgradesTo(unitID);
if iUnitUpgrade ~= nil and iUnitUpgrade ~= -1 then
local obs = GameInfo.Units[iUnitUpgrade];
if obs then
local thisUpgradeInstance = g_UpgradeManager:GetInstance();
if thisUpgradeInstance then
local textureOffset, textureSheet = IconLookup( obs.PortraitIndex, buttonSize, obs.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisUpgradeInstance.UpgradeImage, thisUpgradeInstance.UpgradeButton, textureSheet, textureOffset, CategoryUnits, Locale.ConvertTextKey( obs.Description ), obs.ID );
buttonAdded = buttonAdded + 1;
end
end
end
else
for row in GameInfo.Unit_ClassUpgrades{UnitType = thisUnit.Type} do
local unitClass = GameInfo.UnitClasses[row.UnitClassType];
local upgradeUnit = GameInfo.Units[unitClass.DefaultUnit];
if (upgradeUnit) then
local thisUpgradeInstance = g_UpgradeManager:GetInstance();
if thisUpgradeInstance then
local textureOffset, textureSheet = IconLookup( upgradeUnit.PortraitIndex, buttonSize, upgradeUnit.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisUpgradeInstance.UpgradeImage, thisUpgradeInstance.UpgradeButton, textureSheet, textureOffset, CategoryUnits, Locale.ConvertTextKey( upgradeUnit.Description ), upgradeUnit.ID );
buttonAdded = buttonAdded + 1;
end
end
end
end
UpdateButtonFrame( buttonAdded, Controls.UpgradeInnerFrame, Controls.UpgradeFrame );
-- Are we a unique unit? If so, who do I replace?
local replacesUnitClass = {};
local specificCivs = {};
local classOverrideCondition = string.format("UnitType='%s' and CivilizationType <> 'CIVILIZATION_BARBARIAN' and CivilizationType <> 'CIVILIZATION_MINOR'", thisUnit.Type);
for row in GameInfo.Civilization_UnitClassOverrides(classOverrideCondition) do
specificCivs[row.CivilizationType] = 1;
replacesUnitClass[row.UnitClassType] = 1;
end
g_ReplacesManager:ResetInstances();
buttonAdded = 0;
for unitClassType, _ in pairs(replacesUnitClass) do
for replacedUnit in DB.Query("SELECT u.ID, u.Description, u.PortraitIndex, u.IconAtlas from Units as u inner join UnitClasses as uc on u.Type = uc.DefaultUnit where uc.Type = ?", unitClassType) do
local thisUnitInstance = g_ReplacesManager:GetInstance();
if thisUnitInstance then
local textureOffset, textureSheet = IconLookup( replacedUnit.PortraitIndex, buttonSize, replacedUnit.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisUnitInstance.ReplaceImage, thisUnitInstance.ReplaceButton, textureSheet, textureOffset, CategoryUnits, Locale.ConvertTextKey( replacedUnit.Description ), replacedUnit.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.ReplacesInnerFrame, Controls.ReplacesFrame );
g_CivilizationsManager:ResetInstances();
buttonAdded = 0;
for civilizationType, _ in pairs(specificCivs) do
local civ = GameInfo.Civilizations[civilizationType];
if(civ ~= nil) then
local thisCivInstance = g_CivilizationsManager:GetInstance();
if thisCivInstance then
local textureOffset, textureSheet = IconLookup( civ.PortraitIndex, buttonSize, civ.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisCivInstance.CivilizationImage, thisCivInstance.CivilizationButton, textureSheet, textureOffset, CategoryCivilizations, Locale.ConvertTextKey( civ.ShortDescription ), civ.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.CivilizationsInnerFrame, Controls.CivilizationsFrame );
-- MOD - If not, which units replaced us?
g_ReplacedByManager:ResetInstances();
buttonAdded = 0;
local bReplacedBy = false;
local replacedCondition = string.format("UnitClassType='%s' and CivilizationType <> 'CIVILIZATION_BARBARIAN' and CivilizationType <> 'CIVILIZATION_MINOR'", thisUnit.Class)
for row in GameInfo.Civilization_UnitClassOverrides( replacedCondition ) do
if ( row.UnitType ~= nil ) then
local thatUnit = GameInfo.Units[row.UnitType];
if ( thatUnit ~= thisUnit ) then
local thisReplacedByInstance = g_ReplacedByManager:GetInstance();
if thisReplacedByInstance then
local textureOffset, textureSheet = IconLookup( thatUnit.PortraitIndex, buttonSize, thatUnit.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisReplacedByInstance.ReplacedByImage, thisReplacedByInstance.ReplacedByButton, textureSheet, textureOffset, CategoryUnits, Locale.ConvertTextKey( thatUnit.Description ), thatUnit.ID );
buttonAdded = buttonAdded + 1;
end
end
end
end
if (buttonAdded ~= 0) then
UpdateButtonFrame( buttonAdded, Controls.ReplacedByInnerFrame, Controls.ReplacedByFrame );
end
-- MOD - update the prereq projects
g_PrereqProjectManager:ResetInstances();
buttonAdded = 0;
if thisUnit.ProjectPrereq then
local prereq = GameInfo.Projects[thisUnit.ProjectPrereq];
if prereq then
local thisPrereqInstance = g_PrereqProjectManager:GetInstance();
if thisPrereqInstance then
local textureOffset, textureSheet = IconLookup( prereq.PortraitIndex, buttonSize, prereq.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisPrereqInstance.PrereqProjectImage, thisPrereqInstance.PrereqProjectButton, textureSheet, textureOffset, CategoryWonders, Locale.ConvertTextKey( prereq.Description ), prereq.ID + 1000 );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.PrereqProjectInnerFrame, Controls.PrereqProjectFrame );
-- update the game info
if thisUnit.Help then
UpdateTextBlock( Locale.ConvertTextKey( thisUnit.Help ), Controls.GameInfoLabel, Controls.GameInfoInnerFrame, Controls.GameInfoFrame );
end
-- update the strategy info
if thisUnit.Strategy then
UpdateTextBlock( Locale.ConvertTextKey( thisUnit.Strategy ), Controls.StrategyLabel, Controls.StrategyInnerFrame, Controls.StrategyFrame );
end
-- update the historical info
if thisUnit.Civilopedia then
UpdateTextBlock( Locale.ConvertTextKey( thisUnit.Civilopedia ), Controls.HistoryLabel, Controls.HistoryInnerFrame, Controls.HistoryFrame );
end
-- update the related images
Controls.RelatedImagesFrame:SetHide( true );
end
ResizeEtc();
end
local defaultPromotionPortraitOffset = Vector2( 256, 256 );
CivilopediaCategory[CategoryPromotions].SelectArticle = function( promotionID, shouldAddToList )
print("CivilopediaCategory[CategoryPromotions].SelectArticle");
if selectedCategory ~= CategoryPromotions then
SetSelectedCategory(CategoryPromotions);
end
ClearArticle();
if shouldAddToList == addToList then
currentTopic = currentTopic + 1;
listOfTopicsViewed[currentTopic] = categorizedList[(CategoryPromotions * absurdlyLargeNumTopicsInCategory) + promotionID];
for i = currentTopic + 1, endTopic, 1 do
listOfTopicsViewed[i] = nil;
end
endTopic = currentTopic;
end
if promotionID ~= -1 then
local thisPromotion = GameInfo.UnitPromotions[promotionID];
-- update the name
local name = Locale.ConvertTextKey( thisPromotion.Description );
Controls.ArticleID:SetText( name );
-- portrait
if IconHookup( thisPromotion.PortraitIndex, portraitSize, thisPromotion.IconAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
local contentSize;
local frameSize = {};
local buttonAdded = 0;
-- required promotions
g_RequiredPromotionsManager:ResetInstances();
if thisPromotion.PromotionPrereq then
local thisReq = GameInfo.UnitPromotions[thisPromotion.PromotionPrereq];
if thisReq then
local thisRequiredPromotionInstance = g_RequiredPromotionsManager:GetInstance();
if thisRequiredPromotionInstance then
local textureOffset, textureSheet = IconLookup( thisReq.PortraitIndex, buttonSize, thisReq.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisRequiredPromotionInstance.RequiredPromotionImage, thisRequiredPromotionInstance.RequiredPromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( thisReq.Description ), thisReq.ID );
buttonAdded = buttonAdded + 1;
end
end
else
if thisPromotion.PromotionPrereqOr1 then
local thisReq = GameInfo.UnitPromotions[thisPromotion.PromotionPrereqOr1];
if thisReq then
local thisRequiredPromotionInstance = g_RequiredPromotionsManager:GetInstance();
if thisRequiredPromotionInstance then
local textureOffset, textureSheet = IconLookup( thisReq.PortraitIndex, buttonSize, thisReq.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisRequiredPromotionInstance.RequiredPromotionImage, thisRequiredPromotionInstance.RequiredPromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( thisReq.Description ), thisReq.ID );
buttonAdded = buttonAdded + 1;
end
end
end
if thisPromotion.PromotionPrereqOr2 then
local thisReq = GameInfo.UnitPromotions[thisPromotion.PromotionPrereqOr2];
if thisReq then
local thisRequiredPromotionInstance = g_RequiredPromotionsManager:GetInstance();
if thisRequiredPromotionInstance then
local textureOffset, textureSheet = IconLookup( thisReq.PortraitIndex, buttonSize, thisReq.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisRequiredPromotionInstance.RequiredPromotionImage, thisRequiredPromotionInstance.RequiredPromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( thisReq.Description ), thisReq.ID );
buttonAdded = buttonAdded + 1;
end
end
end
if thisPromotion.PromotionPrereqOr3 then
local thisReq = GameInfo.UnitPromotions[thisPromotion.PromotionPrereqOr3];
if thisReq then
local thisRequiredPromotionInstance = g_RequiredPromotionsManager:GetInstance();
if thisRequiredPromotionInstance then
local textureOffset, textureSheet = IconLookup( thisReq.PortraitIndex, buttonSize, thisReq.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisRequiredPromotionInstance.RequiredPromotionImage, thisRequiredPromotionInstance.RequiredPromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( thisReq.Description ), thisReq.ID );
buttonAdded = buttonAdded + 1;
end
end
end
if thisPromotion.PromotionPrereqOr4 then
local thisReq = GameInfo.UnitPromotions[thisPromotion.PromotionPrereqOr4];
if thisReq then
local thisRequiredPromotionInstance = g_RequiredPromotionsManager:GetInstance();
if thisRequiredPromotionInstance then
local textureOffset, textureSheet = IconLookup( thisReq.PortraitIndex, buttonSize, thisReq.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisRequiredPromotionInstance.RequiredPromotionImage, thisRequiredPromotionInstance.RequiredPromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( thisReq.Description ), thisReq.ID );
buttonAdded = buttonAdded + 1;
end
end
end
if thisPromotion.PromotionPrereqOr5 then
local thisReq = GameInfo.UnitPromotions[thisPromotion.PromotionPrereqOr5];
if thisReq then
local thisRequiredPromotionInstance = g_RequiredPromotionsManager:GetInstance();
if thisRequiredPromotionInstance then
local textureOffset, textureSheet = IconLookup( thisReq.PortraitIndex, buttonSize, thisReq.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisRequiredPromotionInstance.RequiredPromotionImage, thisRequiredPromotionInstance.RequiredPromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( thisReq.Description ), thisReq.ID );
buttonAdded = buttonAdded + 1;
end
end
end
if thisPromotion.PromotionPrereqOr6 then
local thisReq = GameInfo.UnitPromotions[thisPromotion.PromotionPrereqOr6];
if thisReq then
local thisRequiredPromotionInstance = g_RequiredPromotionsManager:GetInstance();
if thisRequiredPromotionInstance then
local textureOffset, textureSheet = IconLookup( thisReq.PortraitIndex, buttonSize, thisReq.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisRequiredPromotionInstance.RequiredPromotionImage, thisRequiredPromotionInstance.RequiredPromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( thisReq.Description ), thisReq.ID );
buttonAdded = buttonAdded + 1;
end
end
end
if thisPromotion.PromotionPrereqOr7 then
local thisReq = GameInfo.UnitPromotions[thisPromotion.PromotionPrereqOr7];
if thisReq then
local thisRequiredPromotionInstance = g_RequiredPromotionsManager:GetInstance();
if thisRequiredPromotionInstance then
local textureOffset, textureSheet = IconLookup( thisReq.PortraitIndex, buttonSize, thisReq.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisRequiredPromotionInstance.RequiredPromotionImage, thisRequiredPromotionInstance.RequiredPromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( thisReq.Description ), thisReq.ID );
buttonAdded = buttonAdded + 1;
end
end
end
if thisPromotion.PromotionPrereqOr8 then
local thisReq = GameInfo.UnitPromotions[thisPromotion.PromotionPrereqOr8];
if thisReq then
local thisRequiredPromotionInstance = g_RequiredPromotionsManager:GetInstance();
if thisRequiredPromotionInstance then
local textureOffset, textureSheet = IconLookup( thisReq.PortraitIndex, buttonSize, thisReq.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisRequiredPromotionInstance.RequiredPromotionImage, thisRequiredPromotionInstance.RequiredPromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( thisReq.Description ), thisReq.ID );
buttonAdded = buttonAdded + 1;
end
end
end
if thisPromotion.PromotionPrereqOr9 then
local thisReq = GameInfo.UnitPromotions[thisPromotion.PromotionPrereqOr9];
if thisReq then
local thisRequiredPromotionInstance = g_RequiredPromotionsManager:GetInstance();
if thisRequiredPromotionInstance then
local textureOffset, textureSheet = IconLookup( thisReq.PortraitIndex, buttonSize, thisReq.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisRequiredPromotionInstance.RequiredPromotionImage, thisRequiredPromotionInstance.RequiredPromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( thisReq.Description ), thisReq.ID );
buttonAdded = buttonAdded + 1;
end
end
end
end
UpdateButtonFrame( buttonAdded, Controls.RequiredPromotionsInnerFrame, Controls.RequiredPromotionsFrame );
-- MOD - Advanced Civilopedia
-- unlocked promotions
g_UnlockedPromotionsManager:ResetInstances();
buttonAdded = 0;
for row in GameInfo.UnitPromotions{PromotionPrereq = thisPromotion.Type} do
local unlocked = GameInfo.UnitPromotions[row.Type];
if unlocked then
local thisUnlockedInstance = g_UnlockedPromotionsManager:GetInstance();
if thisUnlockedInstance then
local textureOffset, textureSheet = IconLookup( unlocked.PortraitIndex, buttonSize, unlocked.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisUnlockedInstance.UnlockedPromotionImage, thisUnlockedInstance.UnlockedPromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( unlocked.Description ), unlocked.ID );
buttonAdded = buttonAdded + 1;
end
end
end
for row in GameInfo.UnitPromotions{PromotionPrereqOr1 = thisPromotion.Type} do
local unlocked = GameInfo.UnitPromotions[row.Type];
if unlocked then
local thisUnlockedInstance = g_UnlockedPromotionsManager:GetInstance();
if thisUnlockedInstance then
local textureOffset, textureSheet = IconLookup( unlocked.PortraitIndex, buttonSize, unlocked.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisUnlockedInstance.UnlockedPromotionImage, thisUnlockedInstance.UnlockedPromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( unlocked.Description ), unlocked.ID );
buttonAdded = buttonAdded + 1;
end
end
end
for row in GameInfo.UnitPromotions{PromotionPrereqOr2 = thisPromotion.Type} do
local unlocked = GameInfo.UnitPromotions[row.Type];
if unlocked then
local thisUnlockedInstance = g_UnlockedPromotionsManager:GetInstance();
if thisUnlockedInstance then
local textureOffset, textureSheet = IconLookup( unlocked.PortraitIndex, buttonSize, unlocked.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisUnlockedInstance.UnlockedPromotionImage, thisUnlockedInstance.UnlockedPromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( unlocked.Description ), unlocked.ID );
buttonAdded = buttonAdded + 1;
end
end
end
for row in GameInfo.UnitPromotions{PromotionPrereqOr3 = thisPromotion.Type} do
local unlocked = GameInfo.UnitPromotions[row.Type];
if unlocked then
local thisUnlockedInstance = g_UnlockedPromotionsManager:GetInstance();
if thisUnlockedInstance then
local textureOffset, textureSheet = IconLookup( unlocked.PortraitIndex, buttonSize, unlocked.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisUnlockedInstance.UnlockedPromotionImage, thisUnlockedInstance.UnlockedPromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( unlocked.Description ), unlocked.ID );
buttonAdded = buttonAdded + 1;
end
end
end
for row in GameInfo.UnitPromotions{PromotionPrereqOr4 = thisPromotion.Type} do
local unlocked = GameInfo.UnitPromotions[row.Type];
if unlocked then
local thisUnlockedInstance = g_UnlockedPromotionsManager:GetInstance();
if thisUnlockedInstance then
local textureOffset, textureSheet = IconLookup( unlocked.PortraitIndex, buttonSize, unlocked.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisUnlockedInstance.UnlockedPromotionImage, thisUnlockedInstance.UnlockedPromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( unlocked.Description ), unlocked.ID );
buttonAdded = buttonAdded + 1;
end
end
end
for row in GameInfo.UnitPromotions{PromotionPrereqOr5 = thisPromotion.Type} do
local unlocked = GameInfo.UnitPromotions[row.Type];
if unlocked then
local thisUnlockedInstance = g_UnlockedPromotionsManager:GetInstance();
if thisUnlockedInstance then
local textureOffset, textureSheet = IconLookup( unlocked.PortraitIndex, buttonSize, unlocked.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisUnlockedInstance.UnlockedPromotionImage, thisUnlockedInstance.UnlockedPromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( unlocked.Description ), unlocked.ID );
buttonAdded = buttonAdded + 1;
end
end
end
for row in GameInfo.UnitPromotions{PromotionPrereqOr6 = thisPromotion.Type} do
local unlocked = GameInfo.UnitPromotions[row.Type];
if unlocked then
local thisUnlockedInstance = g_UnlockedPromotionsManager:GetInstance();
if thisUnlockedInstance then
local textureOffset, textureSheet = IconLookup( unlocked.PortraitIndex, buttonSize, unlocked.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisUnlockedInstance.UnlockedPromotionImage, thisUnlockedInstance.UnlockedPromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( unlocked.Description ), unlocked.ID );
buttonAdded = buttonAdded + 1;
end
end
end
for row in GameInfo.UnitPromotions{PromotionPrereqOr7 = thisPromotion.Type} do
local unlocked = GameInfo.UnitPromotions[row.Type];
if unlocked then
local thisUnlockedInstance = g_UnlockedPromotionsManager:GetInstance();
if thisUnlockedInstance then
local textureOffset, textureSheet = IconLookup( unlocked.PortraitIndex, buttonSize, unlocked.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisUnlockedInstance.UnlockedPromotionImage, thisUnlockedInstance.UnlockedPromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( unlocked.Description ), unlocked.ID );
buttonAdded = buttonAdded + 1;
end
end
end
for row in GameInfo.UnitPromotions{PromotionPrereqOr8 = thisPromotion.Type} do
local unlocked = GameInfo.UnitPromotions[row.Type];
if unlocked then
local thisUnlockedInstance = g_UnlockedPromotionsManager:GetInstance();
if thisUnlockedInstance then
local textureOffset, textureSheet = IconLookup( unlocked.PortraitIndex, buttonSize, unlocked.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisUnlockedInstance.UnlockedPromotionImage, thisUnlockedInstance.UnlockedPromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( unlocked.Description ), unlocked.ID );
buttonAdded = buttonAdded + 1;
end
end
end
for row in GameInfo.UnitPromotions{PromotionPrereqOr9 = thisPromotion.Type} do
local unlocked = GameInfo.UnitPromotions[row.Type];
if unlocked then
local thisUnlockedInstance = g_UnlockedPromotionsManager:GetInstance();
if thisUnlockedInstance then
local textureOffset, textureSheet = IconLookup( unlocked.PortraitIndex, buttonSize, unlocked.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisUnlockedInstance.UnlockedPromotionImage, thisUnlockedInstance.UnlockedPromotionButton, textureSheet, textureOffset, CategoryPromotions, Locale.ConvertTextKey( unlocked.Description ), unlocked.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.UnlockedPromotionsInnerFrame, Controls.UnlockedPromotionsFrame );
-- promoted units
g_UniqueUnitsManager:ResetInstances();
buttonAdded = 0;
for row in GameInfo.Unit_FreePromotions{PromotionType = thisPromotion.Type} do
local thisUnitInfo = GameInfo.Units[row.UnitType];
if thisUnitInfo then
local thisUnitInstance = g_UniqueUnitsManager:GetInstance();
if thisUnitInstance then
local textureOffset, textureSheet = IconLookup( thisUnitInfo.PortraitIndex, buttonSize, thisUnitInfo.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
local unitCategory = CategoryUnits;
local unitEntryID = thisUnitInfo.ID;
UpdateSmallButton( buttonAdded, thisUnitInstance.UniqueUnitImage, thisUnitInstance.UniqueUnitButton, textureSheet, textureOffset, unitCategory, Locale.ConvertTextKey( thisUnitInfo.Description ), unitEntryID);
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.UniqueUnitsInnerFrame, Controls.UniqueUnitsFrame );
-- update the Combat Type value
local texts = "";
local bNewBlock = true;
for row in GameInfo.UnitPromotions_UnitCombats{PromotionType = thisPromotion.Type} do
local thisCombatClass = GameInfo.UnitCombatInfos[row.UnitCombatType];
if thisCombatClass then
if bNewBlock then
bNewBlock = false;
else
texts = texts .. "[NEWLINE]";
end
texts = texts .. "[ICON_BULLET]" .. Locale.ConvertTextKey( thisCombatClass.Description );
end
end
if texts ~= "" then
UpdateNarrowTextBlock( texts, Controls.CombatTypeLabel, Controls.CombatTypeInnerFrame, Controls.CombatTypeFrame );
end
-- update the game info
if thisPromotion.Help then
UpdateTextBlock( Locale.ConvertTextKey( thisPromotion.Help ), Controls.GameInfoLabel, Controls.GameInfoInnerFrame, Controls.GameInfoFrame );
end
end
ResizeEtc();
end
function SelectBuildingOrWonderArticle( buildingID )
if buildingID ~= -1 then
local thisBuilding = GameInfo.Buildings[buildingID];
-- update the name
local name = Locale.ConvertTextKey( thisBuilding.Description );
Controls.ArticleID:SetText( name );
-- update the portrait
if IconHookup( thisBuilding.PortraitIndex, portraitSize, thisBuilding.IconAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
-- update the cost
Controls.CostFrame:SetHide( false );
local costString = "";
local cost = thisBuilding.Cost;
if(Game ~= nil) then
cost = Players[Game.GetActivePlayer()]:GetBuildingProductionNeeded( buildingID );
end
local faithCost = thisBuilding.FaithCost;
if(Game and Game.IsOption(GameOptionTypes.GAMEOPTION_NO_RELIGION)) then
faithCost = 0;
end
local costPerPlayer = 0;
for tLeagueProject in GameInfo.LeagueProjects() do
if (tLeagueProject ~= nil) then
for iTier = 1, 3, 1 do
if (tLeagueProject["RewardTier" .. iTier] ~= nil) then
local tReward = GameInfo.LeagueProjectRewards[tLeagueProject["RewardTier" .. iTier]];
if (tReward ~= nil and tReward.Building ~= nil) then
if (GameInfo.Buildings[tReward.Building] ~= nil and GameInfo.Buildings[tReward.Building].ID == buildingID) then
costPerPlayer = tLeagueProject.CostPerPlayer;
if (Game ~= nil and Game.GetNumActiveLeagues() > 0) then
local pLeague = Game.GetActiveLeague();
if (pLeague ~= nil) then
costPerPlayer = pLeague:GetProjectCostPerPlayer(tLeagueProject.ID) / 100;
end
end
end
end
end
end
end
end
if(costPerPlayer > 0) then
costString = Locale.ConvertTextKey("TXT_KEY_LEAGUE_PROJECT_COST_PER_PLAYER", costPerPlayer);
elseif(cost == 1 and faithCost > 0) then
costString = tostring(faithCost) .. " [ICON_PEACE]";
elseif(cost > 0 and faithCost > 0) then
costString = Locale.Lookup("TXT_KEY_PEDIA_A_OR_B", tostring(cost) .. " [ICON_PRODUCTION]", tostring(faithCost) .. " [ICON_PEACE");
else
if(cost > 0) then
costString = tostring(cost).. " [ICON_PRODUCTION]";
elseif(faithCost > 0) then
costString = tostring(faithCost) .. " [ICON_PEACE]";
else
costString = Locale.Lookup("TXT_KEY_FREE");
end
end
Controls.CostLabel:SetText(costString);
-- update the maintenance
local perTurnCost = thisBuilding.GoldMaintenance;
if perTurnCost > 0 then
Controls.MaintenanceLabel:SetText( tostring(perTurnCost).." [ICON_GOLD]" );
Controls.MaintenanceFrame:SetHide( false );
end
-- update the Happiness
local iHappiness = thisBuilding.Happiness;
if iHappiness > 0 then
Controls.HappinessLabel:SetText( "+" .. tostring(iHappiness).." [ICON_HAPPINESS_1]" );
Controls.HappinessFrame:SetHide( false );
end
-- Unmodded Happiness
iHappiness = thisBuilding.UnmoddedHappiness;
if iHappiness > 0 then
Controls.UnmoddedHappinessLabel:SetText( "+" .. tostring(iHappiness).." [ICON_HAPPINESS_1]" );
Controls.UnmoddedHappinessFrame:SetHide( false );
end
local GetBuildingYieldChange = function(buildingID, yieldType)
if(Game ~= nil) then
return Game.GetBuildingYieldChange(buildingID, YieldTypes[yieldType]);
else
local yieldModifier = 0;
local buildingType = GameInfo.Buildings[buildingID].Type;
for row in GameInfo.Building_YieldChanges{BuildingType = buildingType, YieldType = yieldType} do
yieldModifier = yieldModifier + row.Yield;
end
return yieldModifier;
end
end
-- update the Culture
local iCulture = GetBuildingYieldChange(buildingID, "YIELD_CULTURE");
if iCulture > 0 then
Controls.CultureLabel:SetText( "+" .. tostring(iCulture).." [ICON_CULTURE]" );
Controls.CultureFrame:SetHide( false );
end
-- update the Faith
local iFaith = GetBuildingYieldChange(buildingID, "YIELD_FAITH");
if iFaith > 0 then
Controls.FaithLabel:SetText( "+" .. tostring(iFaith).." [ICON_PEACE]" );
Controls.FaithFrame:SetHide( false );
end
-- update the Defense
local defenseEntries = {};
local iDefense = thisBuilding.Defense;
if iDefense > 0 then
table.insert(defenseEntries, tostring(iDefense / 100).." [ICON_STRENGTH]");
end
local iExtraHitPoints = thisBuilding.ExtraCityHitPoints;
if(iExtraHitPoints > 0) then
table.insert(defenseEntries, Locale.Lookup("TXT_KEY_PEDIA_DEFENSE_HITPOINTS", iExtraHitPoints));
end
if(#defenseEntries > 0) then
Controls.DefenseLabel:SetText(table.concat(defenseEntries, ", "));
Controls.DefenseFrame:SetHide(false);
else
Controls.DefenseFrame:SetHide(true);
end
local GetBuildingYieldModifier = function(buildingID, yieldType)
if(Game ~= nil) then
return Game.GetBuildingYieldModifier(buildingID, YieldTypes[yieldType]);
else
local yieldModifier = 0;
local buildingType = GameInfo.Buildings[buildingID].Type;
for row in GameInfo.Building_YieldModifiers{BuildingType = buildingType, YieldType = yieldType} do
yieldModifier = yieldModifier + row.Yield;
end
return yieldModifier;
end
end
-- Use Game to calculate Yield Changes and modifiers.
-- update the Food Change
local iFood = GetBuildingYieldChange(buildingID, "YIELD_FOOD");
if (iFood > 0) then
Controls.FoodLabel:SetText( "+" .. tostring(iFood).." [ICON_FOOD]" );
Controls.FoodFrame:SetHide( false );
end
-- update the Gold Change
local iGold = GetBuildingYieldChange(buildingID, "YIELD_GOLD");
if (iGold > 0) then
Controls.GoldChangeLabel:SetText( "+" .. tostring(iGold).." [ICON_GOLD]" );
Controls.GoldChangeFrame:SetHide( false );
end
-- update the Gold
local iGold = GetBuildingYieldModifier(buildingID, "YIELD_GOLD");
if (iGold > 0) then
Controls.GoldLabel:SetText( "+" .. tostring(iGold).."% [ICON_GOLD]" );
Controls.GoldFrame:SetHide( false );
end
-- update the Science
local scienceItems = {};
local iScience = GetBuildingYieldModifier(buildingID, "YIELD_SCIENCE");
if(iScience > 0) then
table.insert(scienceItems, "+" .. tostring(iScience).."% [ICON_RESEARCH]" );
end
-- update the Science Change
local iScience = GetBuildingYieldChange(buildingID, "YIELD_SCIENCE");
if(iScience > 0) then
table.insert(scienceItems, "+" .. tostring(iScience).." [ICON_RESEARCH]" );
end
if(#scienceItems > 0) then
Controls.ScienceLabel:SetText( table.concat(scienceItems, ", ") );
Controls.ScienceFrame:SetHide( false );
end
-- update the Production % mods
local productionItems = {};
local iProduction = GetBuildingYieldModifier(buildingID, "YIELD_PRODUCTION");
if(iProduction > 0) then
table.insert(productionItems, "+" .. tostring(iProduction).."% [ICON_PRODUCTION]");
end
-- update the Production
local iProduction = GetBuildingYieldChange(buildingID, "YIELD_PRODUCTION");
if(iProduction > 0) then
table.insert(productionItems, "+" .. tostring(iProduction).." [ICON_PRODUCTION]");
end
if(#productionItems > 0) then
Controls.ProductionLabel:SetText( table.concat(productionItems, ", ") );
Controls.ProductionFrame:SetHide( false );
end
-- update the Great People
local iGPType = thisBuilding.SpecialistType;
if iGPType ~= nil then
local iNumPoints = thisBuilding.GreatPeopleRateChange;
if (iNumPoints > 0) then
local strLabel = Locale.ConvertTextKey(GameInfo.Specialists[iGPType].GreatPeopleTitle);
Controls.GPTitle:SetText( strLabel );
Controls.GreatPeopleLabel:SetText( "+" .. tostring(iNumPoints).." [ICON_GREAT_PEOPLE]" );
Controls.GreatPeopleFrame:SetHide( false );
end
end
-- MOD - update construction restrictions
local condition = "BuildingType = '" .. thisBuilding.Type .. "'";
local bRestriction = false;
local strRestriction = "";
if thisBuilding.Water then
if (not bRestriction) then
bRestriction = true;
strRestriction = Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_WATER" );
else
strRestriction = strRestriction .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_WATER" );
end
end
if thisBuilding.River then
if (not bRestriction) then
bRestriction = true;
strRestriction = Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_RIVER" );
else
strRestriction = strRestriction .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_RIVER" );
end
end
if thisBuilding.FreshWater then
if (not bRestriction) then
bRestriction = true;
strRestriction = Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_FRESH_WATER" );
else
strRestriction = strRestriction .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_FRESH_WATER" );
end
end
if thisBuilding.Mountain then
if (not bRestriction) then
bRestriction = true;
strRestriction = Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_FRESH_MOUNTAIN" );
else
strRestriction = strRestriction .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_FRESH_MOUNTAIN" );
end
end
if thisBuilding.NearbyMountainRequired then
if (not bRestriction) then
bRestriction = true;
strRestriction = Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_NEAR_MOUNTAIN" );
else
strRestriction = strRestriction .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_NEAR_MOUNTAIN" );
end
end
if thisBuilding.Hill then
if (not bRestriction) then
bRestriction = true;
strRestriction = Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_HILL" );
else
strRestriction = strRestriction .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_HILL" );
end
end
if thisBuilding.Flat then
if (not bRestriction) then
bRestriction = true;
strRestriction = Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_FLAT" );
else
strRestriction = strRestriction .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_FLAT" );
end
end
if thisBuilding.FoundsReligion then
if (not bRestriction) then
bRestriction = true;
strRestriction = Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_RELIGION" );
else
strRestriction = strRestriction .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_RELIGION" );
end
end
if (thisBuilding.NearbyTerrainRequired ~= nil) then
local description = Locale.ConvertTextKey( GameInfo.Terrains[thisBuilding.NearbyTerrainRequired].Description );
if (not bRestriction) then
bRestriction = true;
strRestriction = Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_REQUIRE_TERRAIN", description );
else
strRestriction = strRestriction .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_REQUIRE_TERRAIN", description );
end
end
if (thisBuilding.ProhibitedCityTerrain ~= nil) then
local description = Locale.ConvertTextKey( GameInfo.Terrains[thisBuilding.ProhibitedCityTerrain].Description );
if (not bRestriction) then
bRestriction = true;
strRestriction = Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_PROHIBIT_TERRAIN", description );
else
strRestriction = strRestriction .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_PROHIBIT_TERRAIN", description );
end
end
local bResource = false
for row in GameInfo.Building_LocalResourceAnds( condition ) do
if (not bRestriction) and (not bResource) then
bRestriction = true;
strRestriction = Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_RESOURCE_AND" );
bResource = true;
elseif (not bResource) then
strRestriction = strRestriction .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_RESOURCE_AND" );
bResource = true;
end
strRestriction = strRestriction .. "[NEWLINE] [ICON_BULLET]" .. Locale.ConvertTextKey( GameInfo.Resources[row.ResourceType].Description );
end
bResource = false
for row in GameInfo.Building_LocalResourceOrs( condition ) do
if (not bRestriction) and (not bResource) then
bRestriction = true;
strRestriction = Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_RESOURCE_OR" );
bResource = true;
elseif (not bResource) then
strRestriction = strRestriction .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_CONSTRUCTION_RESOURCE_OR" );
bResource = true;
end
strRestriction = strRestriction .. "[NEWLINE] [ICON_BULLET]" .. Locale.ConvertTextKey( GameInfo.Resources[row.ResourceType].Description );
end
if bRestriction then
UpdateNarrowTextBlock( strRestriction, Controls.ConstructionRestrictionsLabel, Controls.ConstructionResInnerFrame, Controls.ConstructionRestrictionsFrame );
end
local contentSize;
local frameSize = {};
local buttonAdded = 0;
-- update the prereq techs
g_PrereqTechManager:ResetInstances();
if thisBuilding.PrereqTech then
local prereq = GameInfo.Technologies[thisBuilding.PrereqTech];
if prereq then
local thisPrereqInstance = g_PrereqTechManager:GetInstance();
if thisPrereqInstance then
local textureOffset, textureSheet = IconLookup( prereq.PortraitIndex, buttonSize, prereq.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisPrereqInstance.PrereqTechImage, thisPrereqInstance.PrereqTechButton, textureSheet, textureOffset, CategoryTech, Locale.ConvertTextKey( prereq.Description ), prereq.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.PrereqTechInnerFrame, Controls.PrereqTechFrame );
-- MOD - update the obsolete techs
g_ObsoleteTechManager:ResetInstances();
buttonAdded = 0;
if thisBuilding.ObsoleteTech then
local obs = GameInfo.Technologies[thisBuilding.ObsoleteTech];
if obs then
local thisTechInstance = g_ObsoleteTechManager:GetInstance();
if thisTechInstance then
local textureOffset, textureSheet = IconLookup( obs.PortraitIndex, buttonSize, obs.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisTechInstance.ObsoleteTechImage, thisTechInstance.ObsoleteTechButton, textureSheet, textureOffset, CategoryTech, Locale.ConvertTextKey( obs.Description ), obs.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.ObsoleteTechInnerFrame, Controls.ObsoleteTechFrame );
-- SpecialistType
g_SpecialistsManager:ResetInstances();
buttonAdded = 0;
if (thisBuilding.SpecialistCount > 0 and thisBuilding.SpecialistType) then
local thisSpec = GameInfo.Specialists[thisBuilding.SpecialistType];
if(thisSpec) then
for i = 1, thisBuilding.SpecialistCount, 1 do
local thisSpecialistInstance = g_SpecialistsManager:GetInstance();
if thisSpecialistInstance then
local textureOffset, textureSheet = IconLookup( thisSpec.PortraitIndex, buttonSize, thisSpec.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisSpecialistInstance.SpecialistImage, thisSpecialistInstance.SpecialistButton, textureSheet, textureOffset, CategoryPeople, Locale.ConvertTextKey( thisSpec.Description ), thisSpec.ID );
buttonAdded = buttonAdded + 1;
end
end
end
end
UpdateButtonFrame( buttonAdded, Controls.SpecialistsInnerFrame, Controls.SpecialistsFrame );
-- required buildings
g_RequiredBuildingsManager:ResetInstances();
buttonAdded = 0;
for row in GameInfo.Building_ClassesNeededInCity( condition ) do
local buildingClass = GameInfo.BuildingClasses[row.BuildingClassType];
if(buildingClass) then
local thisBuildingInfo = GameInfo.Buildings[buildingClass.DefaultBuilding];
if (thisBuildingInfo) then
local thisBuildingInstance = g_RequiredBuildingsManager:GetInstance();
if thisBuildingInstance then
if not IconHookup( thisBuildingInfo.PortraitIndex, buttonSize, thisBuildingInfo.IconAtlas, thisBuildingInstance.RequiredBuildingImage ) then
thisBuildingInstance.RequiredBuildingImage:SetTexture( defaultErrorTextureSheet );
thisBuildingInstance.RequiredBuildingImage:SetTextureOffset( nullOffset );
end
--move this button
thisBuildingInstance.RequiredBuildingButton:SetOffsetVal( (buttonAdded % numberOfButtonsPerRow) * buttonSize + buttonPadding, math.floor(buttonAdded / numberOfButtonsPerRow) * buttonSize + buttonPadding );
thisBuildingInstance.RequiredBuildingButton:SetToolTipString( Locale.ConvertTextKey( thisBuildingInfo.Description ) );
thisBuildingInstance.RequiredBuildingButton:SetVoids( thisBuildingInfo.ID, addToList );
local thisBuildingClass = GameInfo.BuildingClasses[thisBuildingInfo.BuildingClass];
if thisBuildingClass.MaxGlobalInstances > 0 or (thisBuildingClass.MaxPlayerInstances == 1 and thisBuildingInfo.SpecialistCount == 0) or thisBuildingClass.MaxTeamInstances > 0 then
thisBuildingInstance.RequiredBuildingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryWonders].SelectArticle );
else
thisBuildingInstance.RequiredBuildingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryBuildings].SelectArticle );
end
buttonAdded = buttonAdded + 1;
end
end
end
end
UpdateButtonFrame( buttonAdded, Controls.RequiredBuildingsInnerFrame, Controls.RequiredBuildingsFrame );
-- MOD - needed local resources
g_LocalResourcesManager:ResetInstances();
buttonAdded = 0;
for row in GameInfo.Building_LocalResourceAnds( condition ) do
local requiredResource = GameInfo.Resources[row.ResourceType];
if requiredResource then
local thisLocalResourceInstance = g_LocalResourcesManager:GetInstance();
if thisLocalResourceInstance then
local textureOffset, textureSheet = IconLookup( requiredResource.PortraitIndex, buttonSize, requiredResource.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisLocalResourceInstance.LocalResourceImage, thisLocalResourceInstance.LocalResourceButton, textureSheet, textureOffset, CategoryResources, Locale.ConvertTextKey( requiredResource.Description ), requiredResource.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.LocalResourcesInnerFrame, Controls.LocalResourcesFrame );
-- MOD - update the required resources
Controls.RequiredResourcesLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_REQ_RESRC_LABEL" ) );
g_RequiredResourcesManager:ResetInstances();
buttonAdded = 0;
for row in GameInfo.Building_ResourceQuantityRequirements( condition ) do
local requiredResource = GameInfo.Resources[row.ResourceType];
if requiredResource then
local thisRequiredResourceInstance = g_RequiredResourcesManager:GetInstance();
if thisRequiredResourceInstance then
local textureOffset, textureSheet = IconLookup( requiredResource.PortraitIndex, buttonSize, requiredResource.IconAtlas );
local description = row.Cost .. " " .. Locale.ConvertTextKey( requiredResource.Description );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisRequiredResourceInstance.RequiredResourceImage, thisRequiredResourceInstance.RequiredResourceButton, textureSheet, textureOffset, CategoryResources, description, requiredResource.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.RequiredResourcesInnerFrame, Controls.RequiredResourcesFrame );
-- MOD - update the provided resources
g_ResourcesProvidedManager:ResetInstances();
buttonAdded = 0;
for row in GameInfo.Building_ResourceQuantity( condition ) do
local providedResource = GameInfo.Resources[row.ResourceType];
if providedResource then
local thisProvidedResourceInstance = g_ResourcesProvidedManager:GetInstance();
if thisProvidedResourceInstance then
local textureOffset, textureSheet = IconLookup( providedResource.PortraitIndex, buttonSize, providedResource.IconAtlas );
local description = row.Quantity .. " " .. Locale.ConvertTextKey( providedResource.Description );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisProvidedResourceInstance.ResourcesProvidedImage, thisProvidedResourceInstance.ResourcesProvidedButton, textureSheet, textureOffset, CategoryResources, description, providedResource.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.ResourcesProvidedInnerFrame, Controls.ResourcesProvidedFrame );
-- Are we a unique building? If so, who do I replace?
g_ReplacesManager:ResetInstances();
buttonAdded = 0;
local defaultBuilding = nil;
local thisCiv = nil;
for row in GameInfo.Civilization_BuildingClassOverrides( condition ) do
if row.CivilizationType ~= "CIVILIZATION_BARBARIAN" and row.CivilizationType ~= "CIVILIZATION_MINOR" then
local otherCondition = "Type = '" .. row.BuildingClassType .. "'";
for classrow in GameInfo.BuildingClasses( otherCondition ) do
defaultBuilding = GameInfo.Buildings[classrow.DefaultBuilding];
end
if defaultBuilding then
thisCiv = GameInfo.Civilizations[row.CivilizationType];
break;
end
end
end
if defaultBuilding then
local thisBuildingInstance = g_ReplacesManager:GetInstance();
if thisBuildingInstance then
local textureOffset, textureSheet = IconLookup( defaultBuilding.PortraitIndex, buttonSize, defaultBuilding.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisBuildingInstance.ReplaceImage, thisBuildingInstance.ReplaceButton, textureSheet, textureOffset, CategoryBuildings, Locale.ConvertTextKey( defaultBuilding.Description ), defaultBuilding.ID );
buttonAdded = buttonAdded + 1;
end
end
UpdateButtonFrame( buttonAdded, Controls.ReplacesInnerFrame, Controls.ReplacesFrame );
buttonAdded = 0;
if thisCiv then
g_CivilizationsManager:ResetInstances();
local thisCivInstance = g_CivilizationsManager:GetInstance();
if thisCivInstance then
local textureOffset, textureSheet = IconLookup( thisCiv.PortraitIndex, buttonSize, thisCiv.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisCivInstance.CivilizationImage, thisCivInstance.CivilizationButton, textureSheet, textureOffset, CategoryCivilizations, Locale.ConvertTextKey( thisCiv.ShortDescription ), thisCiv.ID );
buttonAdded = buttonAdded + 1;
end
end
UpdateButtonFrame( buttonAdded, Controls.CivilizationsInnerFrame, Controls.CivilizationsFrame );
-- MOD - If not, which buildings replaced us?
g_ReplacedByManager:ResetInstances();
buttonAdded = 0;
local bReplacedBy = false;
local replacedCondition = string.format("BuildingClassType='%s' and CivilizationType <> 'CIVILIZATION_BARBARIAN' and CivilizationType <> 'CIVILIZATION_MINOR'", thisBuilding.BuildingClass)
for row in GameInfo.Civilization_BuildingClassOverrides( replacedCondition ) do
if ( row.BuildingType ~= nil ) then
local thatBuilding = GameInfo.Buildings[row.BuildingType];
if ( thatBuilding ~= thisBuilding ) then
local thisReplacedByInstance = g_ReplacedByManager:GetInstance();
if thisReplacedByInstance then
local textureOffset, textureSheet = IconLookup( thatBuilding.PortraitIndex, buttonSize, thatBuilding.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisReplacedByInstance.ReplacedByImage, thisReplacedByInstance.ReplacedByButton, textureSheet, textureOffset, CategoryBuildings, Locale.ConvertTextKey( thatBuilding.Description ), thatBuilding.ID );
buttonAdded = buttonAdded + 1;
end
end
end
end
if (buttonAdded ~= 0) then
UpdateButtonFrame( buttonAdded, Controls.ReplacedByInnerFrame, Controls.ReplacedByFrame );
end
-- update the great works box
buttonAdded = 0;
g_GreatWorksManager:ResetInstances();
if(thisBuilding.GreatWorkCount > 0) then
for i = 1, thisBuilding.GreatWorkCount, 1 do
local greatWorkSlot = GameInfo.GreatWorkSlots[thisBuilding.GreatWorkSlotType];
local emptyTexture = greatWorkSlot.EmptyIcon;
local thisGreatWorksInstance = g_GreatWorksManager:GetInstance();
UpdateSmallButton( buttonAdded, thisGreatWorksInstance.GreatWorksImage, thisGreatWorksInstance.GreatWorksButton, emptyTexture, nil, nil, Locale.Lookup(greatWorkSlot.EmptyToolTipText), nil);
buttonAdded = buttonAdded + 1;
end
end
UpdateButtonFrame( buttonAdded, Controls.GreatWorksInnerFrame, Controls.GreatWorksFrame );
-- update the game info
if thisBuilding.Help then
-- Don't add text if it's the same as the strategy text
if (thisBuilding.Help ~= thisBuilding.Strategy) then
UpdateTextBlock( Locale.ConvertTextKey( thisBuilding.Help ), Controls.GameInfoLabel, Controls.GameInfoInnerFrame, Controls.GameInfoFrame );
end
end
-- update the strategy info
if thisBuilding.Strategy then
UpdateTextBlock( Locale.ConvertTextKey( thisBuilding.Strategy ), Controls.StrategyLabel, Controls.StrategyInnerFrame, Controls.StrategyFrame );
end
-- update the historical info
if thisBuilding.Civilopedia then
UpdateTextBlock( Locale.ConvertTextKey( thisBuilding.Civilopedia ), Controls.HistoryLabel, Controls.HistoryInnerFrame, Controls.HistoryFrame );
end
if thisBuilding.Quote then
UpdateTextBlock( Locale.ConvertTextKey( thisBuilding.Quote ), Controls.SilentQuoteLabel, Controls.SilentQuoteInnerFrame, Controls.SilentQuoteFrame );
end
-- update the related images
Controls.RelatedImagesFrame:SetHide( true );
end
end
CivilopediaCategory[CategoryBuildings].SelectArticle = function( buildingID, shouldAddToList )
print("CivilopediaCategory[CategoryBuildings].SelectArticle");
if selectedCategory ~= CategoryBuildings then
SetSelectedCategory(CategoryBuildings);
end
ClearArticle();
if shouldAddToList == addToList then
currentTopic = currentTopic + 1;
listOfTopicsViewed[currentTopic] = categorizedList[(CategoryBuildings * absurdlyLargeNumTopicsInCategory) + buildingID];
for i = currentTopic + 1, endTopic, 1 do
listOfTopicsViewed[i] = nil;
end
endTopic = currentTopic;
end
SelectBuildingOrWonderArticle( buildingID );
ResizeEtc();
end
CivilopediaCategory[CategoryWonders].SelectArticle = function( wonderID, shouldAddToList )
print("CivilopediaCategory[CategoryWonders].SelectArticle");
if selectedCategory ~= CategoryWonders then
SetSelectedCategory(CategoryWonders);
end
ClearArticle();
if shouldAddToList == addToList then
currentTopic = currentTopic + 1;
listOfTopicsViewed[currentTopic] = categorizedList[(CategoryWonders * absurdlyLargeNumTopicsInCategory) + wonderID];
for i = currentTopic + 1, endTopic, 1 do
listOfTopicsViewed[i] = nil;
end
endTopic = currentTopic;
end
if wonderID < 1000 then
SelectBuildingOrWonderArticle( wonderID );
else
local projectID = wonderID - 1000;
if projectID ~= -1 then
local thisProject = GameInfo.Projects[projectID];
-- update the name
local name = Locale.ConvertTextKey( thisProject.Description );
Controls.ArticleID:SetText( name );
-- update the portrait
if IconHookup( thisProject.PortraitIndex, portraitSize, thisProject.IconAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
-- update the cost
Controls.CostFrame:SetHide( false );
local cost = thisProject.Cost;
if(cost > 0 and Game ~= nil) then
cost = Players[Game.GetActivePlayer()]:GetProjectProductionNeeded( projectID );
end
if(cost > 0) then
Controls.CostLabel:SetText( tostring(cost).." [ICON_PRODUCTION]" );
elseif(cost == 0) then
Controls.CostLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_FREE" ) );
else
Controls.CostFrame:SetHide(true);
end
local contentSize;
local frameSize = {};
local buttonAdded = 0;
-- update the prereq techs
g_PrereqTechManager:ResetInstances();
buttonAdded = 0;
if thisProject.TechPrereq then
local prereq = GameInfo.Technologies[thisProject.TechPrereq];
if prereq then
local thisPrereqInstance = g_PrereqTechManager:GetInstance();
if thisPrereqInstance then
local textureOffset, textureSheet = IconLookup( prereq.PortraitIndex, buttonSize, prereq.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisPrereqInstance.PrereqTechImage, thisPrereqInstance.PrereqTechButton, textureSheet, textureOffset, CategoryTech, Locale.ConvertTextKey( prereq.Description ), prereq.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.PrereqTechInnerFrame, Controls.PrereqTechFrame );
local condition = "BuildingType = '" .. thisProject.Type .. "'";
-- required buildings
g_RequiredBuildingsManager:ResetInstances();
buttonAdded = 0;
for row in GameInfo.Building_ClassesNeededInCity( condition ) do
local buildingClass = GameInfo.BuildingClasses[row.BuildingClassType];
if(buildingClass ~= nil) then
local thisBuildingInfo = GameInfo.Buildings[buildingClass.DefaultBuilding];
if(thisBuildingInfo ~= nil) then
local thisBuildingInstance = g_RequiredBuildingsManager:GetInstance();
if thisBuildingInstance then
if not IconHookup( thisBuildingInfo.PortraitIndex, buttonSize, thisBuildingInfo.IconAtlas, thisBuildingInstance.RequiredBuildingImage ) then
thisBuildingInstance.RequiredBuildingImage:SetTexture( defaultErrorTextureSheet );
thisBuildingInstance.RequiredBuildingImage:SetTextureOffset( nullOffset );
end
--move this button
thisBuildingInstance.RequiredBuildingButton:SetOffsetVal( (buttonAdded % numberOfButtonsPerRow) * buttonSize + buttonPadding, math.floor(buttonAdded / numberOfButtonsPerRow) * buttonSize + buttonPadding );
thisBuildingInstance.RequiredBuildingButton:SetToolTipString( Locale.ConvertTextKey( thisBuildingInfo.Description ) );
thisBuildingInstance.RequiredBuildingButton:SetVoids( thisBuildingInfo.ID, addToList );
local thisBuildingClass = GameInfo.BuildingClasses[thisBuildingInfo.BuildingClass];
if thisBuildingClass.MaxGlobalInstances > 0 or (thisBuildingClass.MaxPlayerInstances == 1 and thisBuildingInfo.SpecialistCount == 0) or thisBuildingClass.MaxTeamInstances > 0 then
thisBuildingInstance.RequiredBuildingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryWonders].SelectArticle );
else
thisBuildingInstance.RequiredBuildingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryBuildings].SelectArticle );
end
buttonAdded = buttonAdded + 1;
end
end
end
end
UpdateButtonFrame( buttonAdded, Controls.RequiredBuildingsInnerFrame, Controls.RequiredBuildingsFrame );
-- MOD - Advanced Civilopedia
local prereqCondition = "ProjectPrereq = '" .. thisProject.Type .. "'";
-- update the units unlocked
g_UnlockedUnitsManager:ResetInstances();
buttonAdded = 0;
for thisUnitInfo in GameInfo.Units( prereqCondition ) do
if thisUnitInfo.ShowInPedia then
local thisUnitInstance = g_UnlockedUnitsManager:GetInstance();
if thisUnitInstance then
local textureOffset, textureSheet = IconLookup( thisUnitInfo.PortraitIndex, buttonSize, thisUnitInfo.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisUnitInstance.UnlockedUnitImage, thisUnitInstance.UnlockedUnitButton, textureSheet, textureOffset, CategoryUnits, Locale.ConvertTextKey( thisUnitInfo.Description ), thisUnitInfo.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.UnlockedUnitsInnerFrame, Controls.UnlockedUnitsFrame );
-- MOD - Advanced Civilopedia
local thisCondition = "PrereqProjectType = '" .. thisProject.Type .. "'";
-- update the projects unlocked
g_UnlockedProjectsManager:ResetInstances();
buttonAdded = 0;
for row in GameInfo.Project_Prereqs( thisCondition ) do
local otherProject = GameInfo.Projects[row.ProjectType];
if (otherProject) then
local bIgnore = projectsToIgnore[otherProject.Type];
if(bIgnore ~= true) then
local thisProjectInstance = g_UnlockedProjectsManager:GetInstance();
if thisProjectInstance then
local textureOffset, textureSheet = IconLookup( otherProject.PortraitIndex, buttonSize, otherProject.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisProjectInstance.UnlockedProjectImage, thisProjectInstance.UnlockedProjectButton, textureSheet, textureOffset, CategoryWonders, Locale.ConvertTextKey( otherProject.Description ), otherProject.ID + 1000);
buttonAdded = buttonAdded + 1;
end
end
end
end
UpdateButtonFrame( buttonAdded, Controls.UnlockedProjectsInnerFrame, Controls.UnlockedProjectsFrame );
thisCondition = "ProjectType = '" .. thisProject.Type .. "'";
-- update the prereq projects
g_PrereqProjectManager:ResetInstances();
buttonAdded = 0;
for row in GameInfo.Project_Prereqs( thisCondition ) do
local otherProject = GameInfo.Projects[row.PrereqProjectType];
if (otherProject) then
local bIgnore = projectsToIgnore[otherProject.Type];
if(bIgnore ~= true) then
local thisProjectInstance = g_PrereqProjectManager:GetInstance();
if thisProjectInstance then
local textureOffset, textureSheet = IconLookup( otherProject.PortraitIndex, buttonSize, otherProject.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisProjectInstance.PrereqProjectImage, thisProjectInstance.PrereqProjectButton, textureSheet, textureOffset, CategoryWonders, Locale.ConvertTextKey( otherProject.Description ), otherProject.ID + 1000);
buttonAdded = buttonAdded + 1;
end
end
end
end
UpdateButtonFrame( buttonAdded, Controls.PrereqProjectInnerFrame, Controls.PrereqProjectFrame );
-- update the game info
if thisProject.Help then
UpdateTextBlock( Locale.ConvertTextKey( thisProject.Help ), Controls.GameInfoLabel, Controls.GameInfoInnerFrame, Controls.GameInfoFrame );
end
-- update the strategy info
if (thisProject.Strategy) then
UpdateTextBlock( Locale.ConvertTextKey( thisProject.Strategy ), Controls.StrategyLabel, Controls.StrategyInnerFrame, Controls.StrategyFrame );
end
-- update the historical info
if (thisProject.Civilopedia) then
UpdateTextBlock( Locale.ConvertTextKey( thisProject.Civilopedia ), Controls.HistoryLabel, Controls.HistoryInnerFrame, Controls.HistoryFrame );
end
-- update the related images
Controls.RelatedImagesFrame:SetHide( true );
end
end
ResizeEtc();
end
CivilopediaCategory[CategoryPolicies].SelectArticle = function( policyID, shouldAddToList )
print("CivilopediaCategory[CategoryPolicies].SelectArticle");
if selectedCategory ~= CategoryPolicies then
SetSelectedCategory(CategoryPolicies);
end
ClearArticle();
if shouldAddToList == addToList then
currentTopic = currentTopic + 1;
listOfTopicsViewed[currentTopic] = categorizedList[(CategoryPolicies * absurdlyLargeNumTopicsInCategory) + policyID];
for i = currentTopic + 1, endTopic, 1 do
listOfTopicsViewed[i] = nil;
end
endTopic = currentTopic;
end
if policyID ~= -1 then
local thisPolicy = GameInfo.Policies[policyID];
-- update the name
local name = Locale.ConvertTextKey( thisPolicy.Description );
Controls.ArticleID:SetText( name );
-- update the portrait
if IconHookup( thisPolicy.PortraitIndex, portraitSize, thisPolicy.IconAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
-- update the policy branch
if thisPolicy.PolicyBranchType then
local branch = GameInfo.PolicyBranchTypes[thisPolicy.PolicyBranchType];
if branch then
local branchName = Locale.ConvertTextKey( branch.Description );
Controls.PolicyBranchLabel:SetText( branchName );
Controls.PolicyBranchFrame:SetHide( false );
-- update the prereq era
if branch.EraPrereq then
local era = GameInfo.Eras[branch.EraPrereq];
if era then
local eraName = Locale.ConvertTextKey( era.Description );
Controls.PrereqEraLabel:SetText( eraName );
Controls.PrereqEraFrame:SetHide( false );
end
end
end
end
local contentSize;
local frameSize = {};
local buttonAdded = 0;
-- update the prereq policies
g_RequiredPoliciesManager:ResetInstances();
buttonAdded = 0;
local condition = "PolicyType = '" .. thisPolicy.Type .. "'";
for row in GameInfo.Policy_PrereqPolicies( condition ) do
local requiredPolicy = GameInfo.Policies[row.PrereqPolicy];
if requiredPolicy then
local thisRequiredPolicyInstance = g_RequiredPoliciesManager:GetInstance();
if thisRequiredPolicyInstance then
local textureOffset, textureSheet = IconLookup( requiredPolicy.PortraitIndex, buttonSize, requiredPolicy.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisRequiredPolicyInstance.RequiredPolicyImage, thisRequiredPolicyInstance.RequiredPolicyButton, textureSheet, textureOffset, CategoryPolicies, Locale.ConvertTextKey( requiredPolicy.Description ), requiredPolicy.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.RequiredPoliciesInnerFrame, Controls.RequiredPoliciesFrame );
local tenetLevelLabels = {
"TXT_KEY_POLICYSCREEN_L1_TENET",
"TXT_KEY_POLICYSCREEN_L2_TENET",
"TXT_KEY_POLICYSCREEN_L3_TENET",
}
local tenetLevel = tonumber(thisPolicy.Level);
if(tenetLevel ~= nil and tenetLevel > 0) then
Controls.TenetLevelLabel:LocalizeAndSetText(tenetLevelLabels[tenetLevel]);
Controls.TenetLevelFrame:SetHide(false);
else
Controls.TenetLevelFrame:SetHide(true);
end
-- update the game info
if thisPolicy.Help then
UpdateTextBlock( Locale.ConvertTextKey( thisPolicy.Help ), Controls.GameInfoLabel, Controls.GameInfoInnerFrame, Controls.GameInfoFrame );
end
-- update the strategy info
--UpdateTextBlock( Locale.ConvertTextKey( thisPolicy.Strategy ), Controls.StrategyLabel, Controls.StrategyInnerFrame, Controls.StrategyFrame );
-- update the historical info
if (thisPolicy.Civilopedia) then
UpdateTextBlock( Locale.ConvertTextKey( thisPolicy.Civilopedia ), Controls.HistoryLabel, Controls.HistoryInnerFrame, Controls.HistoryFrame );
end
-- update the related images
Controls.RelatedImagesFrame:SetHide( true );
end
ResizeEtc();
end
CivilopediaCategory[CategoryPeople].SelectArticle = function( rawPeopleID, shouldAddToList )
print("CivilopediaCategory[CategoryPeople].SelectArticle");
if selectedCategory ~= CategoryPeople then
SetSelectedCategory(CategoryPeople);
end
ClearArticle();
if shouldAddToList == addToList then
currentTopic = currentTopic + 1;
listOfTopicsViewed[currentTopic] = categorizedList[(CategoryPeople * absurdlyLargeNumTopicsInCategory) + rawPeopleID];
for i = currentTopic + 1, endTopic, 1 do
listOfTopicsViewed[i] = nil;
end
endTopic = currentTopic;
end
if rawPeopleID < 1000 then
if rawPeopleID ~= -1 then
local thisPerson = GameInfo.Specialists[rawPeopleID];
-- update the name
local name = Locale.ConvertTextKey( thisPerson.Description );
Controls.ArticleID:SetText( name );
if IconHookup( thisPerson.PortraitIndex, portraitSize, thisPerson.IconAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
local buttonAdded = 0;
-- list the buildings that this can work in
-- update the game info
if thisPerson.Help then
UpdateTextBlock( Locale.ConvertTextKey( thisPerson.Help ), Controls.GameInfoLabel, Controls.GameInfoInnerFrame, Controls.GameInfoFrame );
end
-- update the strategy info
if thisPerson.Strategy then
UpdateTextBlock( Locale.ConvertTextKey( thisPerson.Strategy ), Controls.StrategyLabel, Controls.StrategyInnerFrame, Controls.StrategyFrame );
end
-- update the historical info
if thisPerson.Civilopedia then
UpdateTextBlock( Locale.ConvertTextKey( thisPerson.Civilopedia ), Controls.HistoryLabel, Controls.HistoryInnerFrame, Controls.HistoryFrame );
end
-- update the related images
Controls.RelatedImagesFrame:SetHide( true );
end
else
local greatPersonID = rawPeopleID - 1000;
if greatPersonID ~= -1 then
local thisPerson = GameInfo.Units[greatPersonID];
-- update the name
local name = Locale.ConvertTextKey( thisPerson.Description );
Controls.ArticleID:SetText( name );
-- update the portrait
if IconHookup( thisPerson.PortraitIndex, portraitSize, thisPerson.IconAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
local buttonAdded = 0;
-- list the buildings that can spawn this unit
-- update the game info
if thisPerson.Help then
UpdateTextBlock( Locale.ConvertTextKey( thisPerson.Help ), Controls.GameInfoLabel, Controls.GameInfoInnerFrame, Controls.GameInfoFrame );
end
-- update the strategy info
if (thisPerson.Strategy) then
UpdateTextBlock( Locale.ConvertTextKey( thisPerson.Strategy ), Controls.StrategyLabel, Controls.StrategyInnerFrame, Controls.StrategyFrame );
end
-- update the historical info
if (thisPerson.Civilopedia) then
UpdateTextBlock( Locale.ConvertTextKey( thisPerson.Civilopedia ), Controls.HistoryLabel, Controls.HistoryInnerFrame, Controls.HistoryFrame );
end
-- update the related images
Controls.RelatedImagesFrame:SetHide( true );
end
end
ResizeEtc();
end
-- MOD - Advanced Civilopedia
function SelectStartRegionPriorityArticle( condition, civilizationType )
local textKey = "TXT_KEY_PEDIA_CIVILIZATIONS_START_PRIORITY_NULL";
for row in GameInfo.Civilization_Start_Along_Ocean( condition ) do
-- if row.StartAlongOcean then
textKey = "TXT_KEY_PEDIA_CIVILIZATIONS_START_PRIORITY_OCEAN";
return textKey;
-- end
end
for row in GameInfo.Civilization_Start_Along_River( condition ) do
textKey = "TXT_KEY_PEDIA_CIVILIZATIONS_START_PRIORITY_RIVER";
return textKey;
end
for row in GameInfo.Civilization_Start_Region_Priority( condition ) do
textKey = "TXT_KEY_PEDIA_CIVILIZATIONS_START_PRIORITY_" .. row.RegionType;
return textKey;
end
for row in GameInfo.Civilization_Start_Region_Avoid( condition ) do
textKey = "TXT_KEY_PEDIA_CIVILIZATIONS_START_AVOID_" .. row.RegionType;
return textKey;
end
return textKey;
end
CivilopediaCategory[CategoryCivilizations].SelectArticle = function( rawCivID, shouldAddToList )
print("CivilopediaCategory[CategoryCivilizations].SelectArticle");
if selectedCategory ~= CategoryCivilizations then
SetSelectedCategory(CategoryCivilizations);
end
ClearArticle();
if shouldAddToList == addToList then
currentTopic = currentTopic + 1;
listOfTopicsViewed[currentTopic] = categorizedList[(CategoryCivilizations * absurdlyLargeNumTopicsInCategory) + rawCivID];
for i = currentTopic + 1, endTopic, 1 do
listOfTopicsViewed[i] = nil;
end
endTopic = currentTopic;
end
if rawCivID < 1000 then
if rawCivID ~= -1 then
local thisCiv = GameInfo.Civilizations[rawCivID];
if thisCiv and thisCiv.Type ~= "CIVILIZATION_MINOR" and thisCiv.Type ~= "CIVILIZATION_BARBARIAN" then
-- update the name
local name = Locale.ConvertTextKey( thisCiv.ShortDescription )
Controls.ArticleID:SetText( name );
-- update the portrait
if IconHookup( thisCiv.PortraitIndex, portraitSize, thisCiv.IconAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
local buttonAdded = 0;
local condition = "CivilizationType = '" .. thisCiv.Type .. "'";
-- add a list of leaders
g_LeadersManager:ResetInstances();
buttonAdded = 0;
local leader = GameInfo.Leaders[GameInfo.Civilization_Leaders( "CivilizationType = '" .. thisCiv.Type .. "'" )().LeaderheadType]; -- todo: add support for multiple leaders
local thisLeaderInstance = g_LeadersManager:GetInstance();
if thisLeaderInstance then
local textureOffset, textureSheet = IconLookup( leader.PortraitIndex, buttonSize, leader.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisLeaderInstance.LeaderImage, thisLeaderInstance.LeaderButton, textureSheet, textureOffset, CategoryCivilizations, Locale.ConvertTextKey( leader.Description ), thisCiv.ID + 1000 );
buttonAdded = buttonAdded + 1;
end
UpdateButtonFrame( buttonAdded, Controls.LeadersInnerFrame, Controls.LeadersFrame );
-- list of UUs
g_UniqueUnitsManager:ResetInstances();
buttonAdded = 0;
for thisOverride in GameInfo.Civilization_UnitClassOverrides( condition ) do
if thisOverride.UnitType ~= nil then
local thisUnitInfo = GameInfo.Units[thisOverride.UnitType];
if thisUnitInfo then
local thisUnitInstance = g_UniqueUnitsManager:GetInstance();
if thisUnitInstance then
local textureOffset, textureSheet = IconLookup( thisUnitInfo.PortraitIndex, buttonSize, thisUnitInfo.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
local unitCategory = CategoryUnits;
local unitEntryID = thisUnitInfo.ID;
--if(thisUnitInfo.Special == "SPECIALUNIT_PEOPLE") then
---- Either a great person or specialist.
--unitCategory = CategoryPeople;
--
---- Figure out which one it is!
--local bIsSpecialist = false;
--for row in GameInfo.Specialists{GreatPeopleUnitClass = thisUnitInfo.Class} do
--bIsSpecialist = true;
--break;
--end
--
--if(bIsSpecialist == false) then
--unitEntryID = unitEntryID + 1000;
--end
--end
UpdateSmallButton( buttonAdded, thisUnitInstance.UniqueUnitImage, thisUnitInstance.UniqueUnitButton, textureSheet, textureOffset, unitCategory, Locale.ConvertTextKey( thisUnitInfo.Description ), unitEntryID);
buttonAdded = buttonAdded + 1;
end
end
end
end
UpdateButtonFrame( buttonAdded, Controls.UniqueUnitsInnerFrame, Controls.UniqueUnitsFrame );
-- list of UBs
g_UniqueBuildingsManager:ResetInstances();
buttonAdded = 0;
for thisOverride in GameInfo.Civilization_BuildingClassOverrides( condition ) do
if(thisOverride.BuildingType ~= nil) then
local thisBuildingInfo = GameInfo.Buildings[thisOverride.BuildingType];
if thisBuildingInfo then
local thisBuildingInstance = g_UniqueBuildingsManager:GetInstance();
if thisBuildingInstance then
if not IconHookup( thisBuildingInfo.PortraitIndex, buttonSize, thisBuildingInfo.IconAtlas, thisBuildingInstance.UniqueBuildingImage ) then
thisBuildingInstance.UniqueBuildingImage:SetTexture( defaultErrorTextureSheet );
thisBuildingInstance.UniqueBuildingImage:SetTextureOffset( nullOffset );
end
--move this button
thisBuildingInstance.UniqueBuildingButton:SetOffsetVal( (buttonAdded % numberOfButtonsPerRow) * buttonSize + buttonPadding, math.floor(buttonAdded / numberOfButtonsPerRow) * buttonSize + buttonPadding );
thisBuildingInstance.UniqueBuildingButton:SetToolTipString( Locale.ConvertTextKey( thisBuildingInfo.Description ) );
thisBuildingInstance.UniqueBuildingButton:SetVoids( thisBuildingInfo.ID, addToList );
local thisBuildingClass = GameInfo.BuildingClasses[thisBuildingInfo.BuildingClass];
if thisBuildingClass.MaxGlobalInstances > 0 or (thisBuildingClass.MaxPlayerInstances == 1 and thisBuildingInfo.SpecialistCount == 0) or thisBuildingClass.MaxTeamInstances > 0 then
thisBuildingInstance.UniqueBuildingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryWonders].SelectArticle );
else
thisBuildingInstance.UniqueBuildingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryBuildings].SelectArticle );
end
buttonAdded = buttonAdded + 1;
end
end
end
end
UpdateButtonFrame( buttonAdded, Controls.UniqueBuildingsInnerFrame, Controls.UniqueBuildingsFrame );
-- list of unique improvements
g_UniqueImprovementsManager:ResetInstances();
buttonAdded = 0;
for thisImprovement in GameInfo.Improvements( condition ) do
local thisImprovementInstance = g_UniqueImprovementsManager:GetInstance();
if thisImprovementInstance then
if not IconHookup( thisImprovement.PortraitIndex, buttonSize, thisImprovement.IconAtlas, thisImprovementInstance.UniqueImprovementImage ) then
thisImprovementInstance.UniqueImprovementImage:SetTexture( defaultErrorTextureSheet );
thisImprovementInstance.UniqueImprovementImage:SetTextureOffset( nullOffset );
end
--move this button
thisImprovementInstance.UniqueImprovementButton:SetOffsetVal( (buttonAdded % numberOfButtonsPerRow) * buttonSize + buttonPadding, math.floor(buttonAdded / numberOfButtonsPerRow) * buttonSize + buttonPadding );
thisImprovementInstance.UniqueImprovementButton:SetToolTipString( Locale.ConvertTextKey( thisImprovement.Description ) );
thisImprovementInstance.UniqueImprovementButton:SetVoids( thisImprovement.ID, addToList );
thisImprovementInstance.UniqueImprovementButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryImprovements].SelectArticle );
buttonAdded = buttonAdded + 1;
end
end
UpdateButtonFrame( buttonAdded, Controls.UniqueImprovementsInnerFrame, Controls.UniqueImprovementsFrame );
-- list of special abilities
buttonAdded = 0;
-- MOD - Advanced Civilopedia
-- add start region priority
g_CivLeaderInfoTextManager:ResetInstances();
if thisCiv then
local bNewBlock = true;
local headerTag = Locale.ConvertTextKey("TXT_KEY_PEDIA_CIVILIZATIONS_START_PRIORITY");
local bodyString = SelectStartRegionPriorityArticle( condition, thisCiv.Type );
-- for row in GameInfo.Leader_MajorCivApproachBiases( condition ) do
-- local approachTag = "TXT_KEY_PEDIA_LEADER_" .. row.MajorCivApproachType;
-- local iBias = row.Bias;
-- if (not bNewBlock) then
-- bodyString = bodyString .. "[NEWLINE]";
-- else
-- bNewBlock = false;
-- end
-- bodyString = bodyString .. Locale.ConvertTextKey(approachTag) .. " " .. tostring(iBias);
-- end
local thisFreeFormTextInstance = g_CivLeaderInfoTextManager:GetInstance();
if thisFreeFormTextInstance then
thisFreeFormTextInstance.CivLeaderInfoTextHeader:SetText( Locale.ConvertTextKey( headerTag ));
UpdateNarrowTextBlock( Locale.ConvertTextKey( bodyString ), thisFreeFormTextInstance.CivLeaderInfoTextLabel, thisFreeFormTextInstance.CivLeaderInfoTextInnerFrame, thisFreeFormTextInstance.CivLeaderInfoTextFrame );
end
Controls.CivLeaderInfoTextStack:SetHide( false );
end
-- add the free form text
g_FreeFormTextManager:ResetInstances();
local tagString = thisCiv.CivilopediaTag;
if tagString then
local headerString = tagString .. "_HEADING_";
local bodyString = tagString .. "_TEXT_";
local notFound = false;
local i = 1;
repeat
local headerTag = headerString .. tostring( i );
local bodyTag = bodyString .. tostring( i );
if TagExists( headerTag ) and TagExists( bodyTag ) then
local thisFreeFormTextInstance = g_FreeFormTextManager:GetInstance();
if thisFreeFormTextInstance then
thisFreeFormTextInstance.FFTextHeader:SetText( Locale.ConvertTextKey( headerTag ));
UpdateTextBlock( Locale.ConvertTextKey( bodyTag ), thisFreeFormTextInstance.FFTextLabel, thisFreeFormTextInstance.FFTextInnerFrame, thisFreeFormTextInstance.FFTextFrame );
end
else
notFound = true;
end
i = i + 1;
until notFound;
local factoidHeaderString = tagString .. "_FACTOID_HEADING";
local factoidBodyString = tagString .. "_FACTOID_TEXT";
if TagExists( factoidHeaderString ) and TagExists( factoidBodyString ) then
local thisFreeFormTextInstance = g_FreeFormTextManager:GetInstance();
if thisFreeFormTextInstance then
thisFreeFormTextInstance.FFTextHeader:SetText( Locale.ConvertTextKey( factoidHeaderString ));
UpdateTextBlock( Locale.ConvertTextKey( factoidBodyString ), thisFreeFormTextInstance.FFTextLabel, thisFreeFormTextInstance.FFTextInnerFrame, thisFreeFormTextInstance.FFTextFrame );
end
end
Controls.FFTextStack:SetHide( false );
end
-- update the related images
Controls.RelatedImagesFrame:SetHide( true );
end
end
else
local civID = rawCivID - 1000;
if civID ~= -1 then
local thisCiv = GameInfo.Civilizations[civID];
if thisCiv and thisCiv.Type ~= "CIVILIZATION_MINOR" and thisCiv.Type ~= "CIVILIZATION_BARBARIAN" then
local leader = GameInfo.Leaders[GameInfo.Civilization_Leaders( "CivilizationType = '" .. thisCiv.Type .. "'" )().LeaderheadType];
-- update the name
local tagString = leader.CivilopediaTag;
if tagString then
local name = Locale.ConvertTextKey( tagString.."_NAME" );
Controls.ArticleID:SetText( name );
Controls.SubtitleLabel:SetText( Locale.ConvertTextKey( tagString.."_SUBTITLE" ) );
Controls.SubtitleID:SetHide( false );
else
local name = Locale.ConvertTextKey( leader.Description )
Controls.ArticleID:SetText( name );
end
-- update the portrait
if IconHookup( leader.PortraitIndex, portraitSize, leader.IconAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
local buttonAdded = 0;
-- add titles etc.
if tagString then
Controls.LivedLabel:SetText( Locale.ConvertTextKey( tagString.."_LIVED" ) );
Controls.LivedFrame:SetHide( false );
local titlesString = tagString .. "_TITLES_";
local notFound = false;
local i = 1;
local titles = "";
local numTitles = 0;
repeat
local titlesTag = titlesString .. tostring( i );
if TagExists( titlesTag ) then
if numTitles > 0 then
titles = titles .. "[NEWLINE][NEWLINE]";
end
numTitles = numTitles + 1;
titles = titles .. Locale.ConvertTextKey( titlesTag );
else
notFound = true;
end
i = i + 1;
until notFound;
if numTitles > 0 then
UpdateNarrowTextBlock( Locale.ConvertTextKey( titles ), Controls.TitlesLabel, Controls.TitlesInnerFrame, Controls.TitlesFrame );
end
end
local condition = "LeaderType = '" .. leader.Type .. "'";
-- list of traits
--g_TraitsManager:ResetInstances();
--buttonAdded = 0;
--for row in GameInfo.Leader_Traits( condition ) do
--local thisTrait = GameInfo.Traits[row.TraitType];
--if thisTrait then
--local thisTraitInstance = g_TraitsManager:GetInstance();
--if thisTraitInstance then
--local textureSheet;
--local textureOffset;
--textureSheet = defaultErrorTextureSheet;
--textureOffset = nullOffset;
--UpdateSmallButton( buttonAdded, thisTraitInstance.TraitImage, thisTraitInstance.TraitButton, textureSheet, textureOffset, CategoryGameConcepts, Locale.ConvertTextKey( thisTrait.ShortDescription ), thisTrait.ID ); -- todo: add a fudge factor
--buttonAdded = buttonAdded + 1;
--end
--end
--end
--UpdateButtonFrame( buttonAdded, Controls.TraitsInnerFrame, Controls.TraitsFrame );
--
-- add the civ icon
g_CivilizationsManager:ResetInstances();
buttonAdded = 0;
local thisCivInstance = g_CivilizationsManager:GetInstance();
if thisCivInstance then
local textureOffset, textureSheet = IconLookup( thisCiv.PortraitIndex, buttonSize, thisCiv.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisCivInstance.CivilizationImage, thisCivInstance.CivilizationButton, textureSheet, textureOffset, CategoryCivilizations, Locale.ConvertTextKey( thisCiv.ShortDescription ), thisCiv.ID );
buttonAdded = buttonAdded + 1;
end
UpdateButtonFrame( buttonAdded, Controls.CivilizationsInnerFrame, Controls.CivilizationsFrame );
-- update the game info
local leaderTrait = GameInfo.Leader_Traits(condition)();
if leaderTrait then
local trait = leaderTrait.TraitType;
local traitString = Locale.ConvertTextKey( GameInfo.Traits[trait].ShortDescription ).."[NEWLINE][NEWLINE]"..Locale.ConvertTextKey( GameInfo.Traits[trait].Description );
UpdateTextBlock( traitString, Controls.GameInfoLabel, Controls.GameInfoInnerFrame, Controls.GameInfoFrame );
end
-- MOD - Advanced Civilopedia
g_CivLeaderInfoTextManager:ResetInstances();
if tagString then
local bNewBlock = true;
-- add leader's biases towards Majors
local headerTag = Locale.ConvertTextKey("TXT_KEY_PEDIA_LEADER_APPROACH_BIASES_MAJOR");
local bodyString = "";
for row in GameInfo.Leader_MajorCivApproachBiases( condition ) do
local approachTag = "TXT_KEY_PEDIA_LEADER_" .. row.MajorCivApproachType;
local iBias = row.Bias;
if (not bNewBlock) then
bodyString = bodyString .. "[NEWLINE]";
else
bNewBlock = false;
end
bodyString = bodyString .. Locale.ConvertTextKey(approachTag) .. " " .. tostring(iBias);
end
local thisFreeFormTextInstance = g_CivLeaderInfoTextManager:GetInstance();
if thisFreeFormTextInstance then
thisFreeFormTextInstance.CivLeaderInfoTextHeader:SetText( Locale.ConvertTextKey( headerTag ));
UpdateNarrowTextBlock( bodyString, thisFreeFormTextInstance.CivLeaderInfoTextLabel, thisFreeFormTextInstance.CivLeaderInfoTextInnerFrame, thisFreeFormTextInstance.CivLeaderInfoTextFrame );
end
-- add leader's biases towards Minors
bNewBlock = true;
headerTag = Locale.ConvertTextKey("TXT_KEY_PEDIA_LEADER_APPROACH_BIASES_MINOR");
bodyString = "";
for row in GameInfo.Leader_MinorCivApproachBiases( condition ) do
local approachTag = "TXT_KEY_PEDIA_LEADER_" .. row.MinorCivApproachType;
local iBias = row.Bias;
if (not bNewBlock) then
bodyString = bodyString .. "[NEWLINE]";
else
bNewBlock = false;
end
bodyString = bodyString .. Locale.ConvertTextKey(approachTag) .. " " .. tostring(iBias);
end
local thisFreeFormTextInstance = g_CivLeaderInfoTextManager:GetInstance();
if thisFreeFormTextInstance then
thisFreeFormTextInstance.CivLeaderInfoTextHeader:SetText( Locale.ConvertTextKey( headerTag ));
UpdateNarrowTextBlock( bodyString, thisFreeFormTextInstance.CivLeaderInfoTextLabel, thisFreeFormTextInstance.CivLeaderInfoTextInnerFrame, thisFreeFormTextInstance.CivLeaderInfoTextFrame );
end
-- add leader's flavors
bNewBlock = true;
headerTag = Locale.ConvertTextKey("TXT_KEY_PEDIA_LEADER_FLAVORS");
bodyString = "";
local iCount = 1;
local stringTable = {};
for row in GameInfo.Leader_Flavors( condition ) do
local flavorTag = "TXT_KEY_PEDIA_LEADER_" .. row.FlavorType;
local rowID = GameInfo.Flavors[row.FlavorType].ID;
local rowTag = Locale.ConvertTextKey(flavorTag) .. " " .. tostring( row.Flavor );
table.insert(stringTable, { ID=rowID, strTag=rowTag });
iCount = iCount + 1;
end
-- sort the table
print("Sorting the table...");
table.sort(stringTable, function(a, b)
return a.ID < b.ID;
end);
if (iCount ~= 39) then
print("Ur-oh, there seems to be an error, or player added more entries to this table!");
iCount = 39;
end
for i = 1, iCount-1, 1 do
if (not bNewBlock) then
bodyString = bodyString .. "[NEWLINE]";
else
bNewBlock = false;
end
if (i == 1) or (i == 5) or (i == 9) or (i == 18) or (i == 31) or (i == 35) then
local titleTag = "TXT_KEY_PEDIA_LEADER_FLAVORS_TITLE_" .. tostring(i);
bodyString = bodyString .. Locale.ConvertTextKey(titleTag);
end
local iNumber = flavorList[i];
if (stringTable[iNumber] ~= nil) then
bodyString = bodyString .. stringTable[iNumber].strTag;
else
bodyString = bodyString .. "???";
end
end
local thisFreeFormTextInstance = g_CivLeaderInfoTextManager:GetInstance();
if thisFreeFormTextInstance then
thisFreeFormTextInstance.CivLeaderInfoTextHeader:SetText( Locale.ConvertTextKey( headerTag ));
UpdateNarrowTextBlock( bodyString, thisFreeFormTextInstance.CivLeaderInfoTextLabel, thisFreeFormTextInstance.CivLeaderInfoTextInnerFrame, thisFreeFormTextInstance.CivLeaderInfoTextFrame );
end
Controls.CivLeaderInfoTextStack:SetHide( false );
end
-- add the free form text
g_FreeFormTextManager:ResetInstances();
if tagString then
local headerString = tagString .. "_HEADING_";
local bodyString = tagString .. "_TEXT_";
local notFound = false;
local i = 1;
repeat
local headerTag = headerString .. tostring( i );
local bodyTag = bodyString .. tostring( i );
if TagExists( headerTag ) and TagExists( bodyTag ) then
local thisFreeFormTextInstance = g_FreeFormTextManager:GetInstance();
if thisFreeFormTextInstance then
thisFreeFormTextInstance.FFTextHeader:SetText( Locale.ConvertTextKey( headerTag ));
UpdateTextBlock( Locale.ConvertTextKey( bodyTag ), thisFreeFormTextInstance.FFTextLabel, thisFreeFormTextInstance.FFTextInnerFrame, thisFreeFormTextInstance.FFTextFrame );
end
else
notFound = true;
end
i = i + 1;
until notFound;
notFound = false;
i = 1;
repeat
local bodyString = tagString .. "_FACT_";
local bodyTag = bodyString .. tostring( i );
if TagExists( bodyTag ) then
local thisFreeFormTextInstance = g_FreeFormTextManager:GetInstance();
if thisFreeFormTextInstance then
thisFreeFormTextInstance.FFTextHeader:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_FACTOID" ));
UpdateTextBlock( Locale.ConvertTextKey( bodyTag ), thisFreeFormTextInstance.FFTextLabel, thisFreeFormTextInstance.FFTextInnerFrame, thisFreeFormTextInstance.FFTextFrame );
end
else
notFound = true;
end
i = i + 1;
until notFound;
Controls.FFTextStack:SetHide( false );
end
-- update the related images
Controls.RelatedImagesFrame:SetHide( true );
end
end
end
ResizeEtc();
end
CivilopediaCategory[CategoryCityStates].SelectArticle = function( cityStateID, shouldAddToList )
print("CivilopediaCategory[CategoryCityStates].SelectArticle");
if selectedCategory ~= CategoryCityStates then
SetSelectedCategory(CategoryCityStates);
end
ClearArticle();
if shouldAddToList == addToList then
currentTopic = currentTopic + 1;
listOfTopicsViewed[currentTopic] = categorizedList[(CategoryCityStates * absurdlyLargeNumTopicsInCategory) + cityStateID];
for i = currentTopic + 1, endTopic, 1 do
listOfTopicsViewed[i] = nil;
end
endTopic = currentTopic;
end
if cityStateID ~= -1 then
local thisCityState = GameInfo.MinorCivilizations[cityStateID];
-- update the name
local name = Locale.ConvertTextKey( thisCityState.Description );
Controls.ArticleID:SetText( name );
-- portrait -- need to update this once they're in.
--Controls.PortraitFrame:SetHide( false );
local contentSize;
local frameSize = {};
local buttonAdded = 0;
local condition = "MinorCivType = '" .. thisCityState.Type .. "'";
-- update the game info
-- MOD - update Minor Civ bonuses
g_FreeFormTextManager:ResetInstances();
local traitType = GameInfo.MinorCivTraits[thisCityState.MinorCivTrait];
local bodyString = "";
local headString = "";
if (traitType == GameInfo.MinorCivTraits.MINOR_TRAIT_CULTURED) then
headString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_CULTURED" );
local nNum = {};
nNum[1] = GameInfo.Defines( "Name='FRIENDS_CULTURE_BONUS_AMOUNT_ANCIENT'" )().Value;
nNum[2] = GameInfo.Defines( "Name='FRIENDS_CULTURE_BONUS_AMOUNT_MEDIEVAL'" )().Value;
nNum[3] = GameInfo.Defines( "Name='FRIENDS_CULTURE_BONUS_AMOUNT_INDUSTRIAL'" )().Value;
nNum[4] = nNum[1] + GameInfo.Defines( "Name='ALLIES_CULTURE_BONUS_AMOUNT_ANCIENT'" )().Value;
nNum[5] = nNum[2] + GameInfo.Defines( "Name='ALLIES_CULTURE_BONUS_AMOUNT_MEDIEVAL'" )().Value;
nNum[6] = nNum[3] + GameInfo.Defines( "Name='ALLIES_CULTURE_BONUS_AMOUNT_INDUSTRIAL'" )().Value;
bodyString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_FRIEND" );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_CULTURED_ANCIENT", nNum[1] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_CULTURED_MEDIEVAL", nNum[2] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_CULTURED_INDUSTRIAL", nNum[3] );
bodyString = bodyString .. "[NEWLINE][NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_ALLY" );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_CULTURED_ANCIENT", nNum[4] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_CULTURED_MEDIEVAL", nNum[5] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_CULTURED_INDUSTRIAL", nNum[6] );
elseif (traitType == GameInfo.MinorCivTraits.MINOR_TRAIT_MARITIME) then
headString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MARITIME" );
local nNum = {};
nNum[1] = GameInfo.Defines( "Name='FRIENDS_CAPITAL_FOOD_BONUS_AMOUNT_PRE_RENAISSANCE'" )().Value / 100;
nNum[2] = GameInfo.Defines( "Name='FRIENDS_CAPITAL_FOOD_BONUS_AMOUNT_POST_RENAISSANCE'" )().Value / 100;
nNum[3] = GameInfo.Defines( "Name='FRIENDS_OTHER_CITIES_FOOD_BONUS_AMOUNT_PRE_RENAISSANCE'" )().Value / 100;
nNum[4] = GameInfo.Defines( "Name='FRIENDS_OTHER_CITIES_FOOD_BONUS_AMOUNT_POST_RENAISSANCE'" )().Value / 100;
nNum[5] = GameInfo.Defines( "Name='ALLIES_CAPITAL_FOOD_BONUS_AMOUNT'" )().Value / 100;
nNum[6] = GameInfo.Defines( "Name='ALLIES_OTHER_CITIES_FOOD_BONUS_AMOUNT'" )().Value / 100;
bodyString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_FRIEND" );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MARITIME_CAPITAL_PRE_RENAISSANCE", nNum[1] + nNum[3] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MARITIME_CAPITAL_POST_RENAISSANCE", nNum[2] + nNum[4] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MARITIME_OTHER_PRE_RENAISSANCE", nNum[3] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MARITIME_OTHER_POST_RENAISSANCE", nNum[4] );
bodyString = bodyString .. "[NEWLINE][NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_ALLY" );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MARITIME_CAPITAL_PRE_RENAISSANCE", nNum[1] + nNum[3] + nNum[5] + nNum[6] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MARITIME_CAPITAL_POST_RENAISSANCE", nNum[2] + nNum[4] + nNum[5] + nNum[6] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MARITIME_OTHER_PRE_RENAISSANCE", nNum[3] + nNum[6] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MARITIME_OTHER_POST_RENAISSANCE", nNum[4] + nNum[6] );
elseif (traitType == GameInfo.MinorCivTraits.MINOR_TRAIT_MILITARISTIC) then
headString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MILITARISTIC" );
local nNum = {};
if ( Game ~= nil) then
nNum[0] = GameInfo.GameSpeeds[Game.GetGameSpeedType()].GreatPeoplePercent / 100;
else
nNum[0] = 1;
end
nNum[1] = GameInfo.Defines( "Name='FRIENDS_BASE_TURNS_UNIT_SPAWN'" )().Value * nNum[0] ;
nNum[2] = GameInfo.Defines( "Name='FRIENDS_RAND_TURNS_UNIT_SPAWN'" )().Value * nNum[0];
nNum[3] = GameInfo.Defines( "Name='ALLIES_EXTRA_TURNS_UNIT_SPAWN'" )().Value * nNum[0];
nNum[4] = GameInfo.Defines( "Name='UNIT_SPAWN_BIAS_MULTIPLIER'" )().Value / 100;
if Game and ( Game.IsGameMultiPlayer() ) then
nNum[1] = nNum[1] * nNum[4];
nNum[2] = nNum[2] * nNum[4];
nNum[3] = nNum[3] * nNum[4];
end
bodyString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_FRIEND" );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MILITARISTIC_FRIENDS", nNum[1], nNum[2] );
bodyString = bodyString .. "[NEWLINE][NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_ALLY" );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MILITARISTIC_ALLIES", nNum[1] + nNum[3], nNum[2] );
elseif (traitType == GameInfo.MinorCivTraits.MINOR_TRAIT_MERCANTILE) then
headString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MERCANTILE" );
local nNum = {};
nNum[1] = GameInfo.Defines( "Name='FRIENDS_HAPPINESS_FLAT_BONUS_AMOUNT_ANCIENT'" )().Value;
nNum[2] = GameInfo.Defines( "Name='FRIENDS_HAPPINESS_FLAT_BONUS_AMOUNT_MEDIEVAL'" )().Value;
nNum[3] = GameInfo.Defines( "Name='FRIENDS_HAPPINESS_FLAT_BONUS_AMOUNT_INDUSTRIAL'" )().Value;
nNum[4] = GameInfo.Defines( "Name='ALLIES_HAPPINESS_FLAT_BONUS_AMOUNT_ANCIENT'" )().Value;
nNum[5] = GameInfo.Defines( "Name='ALLIES_HAPPINESS_FLAT_BONUS_AMOUNT_MEDIEVAL'" )().Value;
nNum[6] = GameInfo.Defines( "Name='ALLIES_HAPPINESS_FLAT_BONUS_AMOUNT_INDUSTRIAL'" )().Value;
nNum[7] = GameInfo.Defines( "Name='FRIENDS_HAPPINESS_PER_LUXURY_BONUS_AMOUNT_ANCIENT'" )().Value;
nNum[8] = GameInfo.Defines( "Name='FRIENDS_HAPPINESS_PER_LUXURY_BONUS_AMOUNT_MEDIEVAL'" )().Value;
nNum[9] = GameInfo.Defines( "Name='FRIENDS_HAPPINESS_PER_LUXURY_BONUS_AMOUNT_INDUSTRIAL'" )().Value;
nNum[10] = GameInfo.Defines( "Name='ALLIES_HAPPINESS_PER_LUXURY_BONUS_AMOUNT_ANCIENT'" )().Value;
nNum[11] = GameInfo.Defines( "Name='ALLIES_HAPPINESS_PER_LUXURY_BONUS_AMOUNT_MEDIEVAL'" )().Value;
nNum[12] = GameInfo.Defines( "Name='ALLIES_HAPPINESS_PER_LUXURY_BONUS_AMOUNT_INDUSTRIAL'" )().Value;
bodyString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_FRIEND" );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MERCANTILE_ANCIENT", nNum[1] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MERCANTILE_MEDIEVAL", nNum[2] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MERCANTILE_INDUSTRIAL", nNum[3] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MERCANTILE_ANCIENT_LUXURY", nNum[7] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MERCANTILE_MEDIEVAL_LUXURY", nNum[8] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MERCANTILE_INDUSTRIAL_LUXURY", nNum[9] );
bodyString = bodyString .. "[NEWLINE][NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_ALLY" );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MERCANTILE_ANCIENT", nNum[1] + nNum[4] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MERCANTILE_MEDIEVAL", nNum[2] + nNum[5] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MERCANTILE_INDUSTRIAL", nNum[3] + nNum[6] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MERCANTILE_ANCIENT_LUXURY", nNum[7] + nNum[10] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MERCANTILE_MEDIEVAL_LUXURY", nNum[8] + nNum[11] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_MERCANTILE_INDUSTRIAL_LUXURY", nNum[9] + nNum[12] );
elseif (traitType == GameInfo.MinorCivTraits.MINOR_TRAIT_RELIGIOUS) then
headString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_RELIGIOUS" );
local nNum = {};
nNum[1] = GameInfo.Defines( "Name='FRIENDS_FAITH_FLAT_BONUS_AMOUNT_ANCIENT'" )().Value;
nNum[2] = GameInfo.Defines( "Name='FRIENDS_FAITH_FLAT_BONUS_AMOUNT_CLASSICAL'" )().Value;
nNum[3] = GameInfo.Defines( "Name='FRIENDS_FAITH_FLAT_BONUS_AMOUNT_MEDIEVAL'" )().Value;
nNum[4] = GameInfo.Defines( "Name='FRIENDS_FAITH_FLAT_BONUS_AMOUNT_RENAISSANCE'" )().Value;
nNum[5] = GameInfo.Defines( "Name='FRIENDS_FAITH_FLAT_BONUS_AMOUNT_INDUSTRIAL'" )().Value;
nNum[6] = GameInfo.Defines( "Name='ALLIES_FAITH_FLAT_BONUS_AMOUNT_ANCIENT'" )().Value;
nNum[7] = GameInfo.Defines( "Name='ALLIES_FAITH_FLAT_BONUS_AMOUNT_CLASSICAL'" )().Value;
nNum[8] = GameInfo.Defines( "Name='ALLIES_FAITH_FLAT_BONUS_AMOUNT_MEDIEVAL'" )().Value;
nNum[9] = GameInfo.Defines( "Name='ALLIES_FAITH_FLAT_BONUS_AMOUNT_RENAISSANCE'" )().Value;
nNum[10]= GameInfo.Defines( "Name='ALLIES_FAITH_FLAT_BONUS_AMOUNT_INDUSTRIAL'" )().Value;
bodyString = Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_FRIEND" );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_RELIGIOUS_ANCIENT", nNum[1] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_RELIGIOUS_CLASSICAL", nNum[2] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_RELIGIOUS_MEDIEVAL", nNum[3] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_RELIGIOUS_RENAISSANCE", nNum[4] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_RELIGIOUS_INDUSTRIAL", nNum[5] );
bodyString = bodyString .. "[NEWLINE][NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_ALLY" );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_RELIGIOUS_ANCIENT", nNum[1] + nNum[6] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_RELIGIOUS_CLASSICAL", nNum[2] + nNum[7] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_RELIGIOUS_MEDIEVAL", nNum[3] + nNum[8] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_RELIGIOUS_RENAISSANCE", nNum[4] + nNum[9] );
bodyString = bodyString .. "[NEWLINE]" .. Locale.ConvertTextKey( "TXT_KEY_PEDIA_CONSTRUCTION_MINORBONUS_RELIGIOUS_INDUSTRIAL", nNum[5] + nNum[10] );
end
if ( headString ~= "" ) then
local thisFreeFormTextInstance = g_FreeFormTextManager:GetInstance();
if thisFreeFormTextInstance then
thisFreeFormTextInstance.FFTextHeader:SetText( headString );
UpdateTextBlock( bodyString, thisFreeFormTextInstance.FFTextLabel, thisFreeFormTextInstance.FFTextInnerFrame, thisFreeFormTextInstance.FFTextFrame );
end
end
-- MOD - Advanced Civilopedia
headString = Locale.ConvertTextKey("TXT_KEY_PEDIA_MINOR_FLAVORS");
bodyString = "";
local bNewBlock = true;
for row in GameInfo.MinorCivilization_Flavors( condition ) do
local flavorTag = "TXT_KEY_PEDIA_LEADER_" .. row.FlavorType;
local rowID = GameInfo.Flavors[row.FlavorType].ID;
if (row.Flavor > 0) then
local rowTag = Locale.ConvertTextKey(flavorTag) .. " " .. tostring( row.Flavor );
if (bNewBlock) then
bodyString = bodyString .. rowTag;
bNewBlock = false;
else
bodyString = bodyString .. "[NEWLINE]" .. rowTag;
end
end
end
if ( bodyString ~= "" ) then
local thisFreeFormTextInstance = g_FreeFormTextManager:GetInstance();
if thisFreeFormTextInstance then
thisFreeFormTextInstance.FFTextHeader:SetText( Locale.ConvertTextKey( headString ));
UpdateTextBlock( bodyString, thisFreeFormTextInstance.FFTextLabel, thisFreeFormTextInstance.FFTextInnerFrame, thisFreeFormTextInstance.FFTextFrame );
end
end
Controls.FFTextStack:SetHide( false );
-- update the historical info
if (thisCityState.Civilopedia) then
UpdateTextBlock( Locale.ConvertTextKey( thisCityState.Civilopedia ), Controls.HistoryLabel, Controls.HistoryInnerFrame, Controls.HistoryFrame );
end
end
ResizeEtc();
end
CivilopediaCategory[CategoryTerrain].SelectArticle = function( rawTerrainID, shouldAddToList )
print("CivilopediaCategory[CategoryTerrain].SelectArticle");
if selectedCategory ~= CategoryTerrain then
SetSelectedCategory(CategoryTerrain);
end
ClearArticle();
if shouldAddToList == addToList then
currentTopic = currentTopic + 1;
listOfTopicsViewed[currentTopic] = categorizedList[(CategoryTerrain * absurdlyLargeNumTopicsInCategory) + rawTerrainID];
for i = currentTopic + 1, endTopic, 1 do
listOfTopicsViewed[i] = nil;
end
endTopic = currentTopic;
end
if rawTerrainID < 1000 then
local terrainId = rawTerrainID;
if terrainId ~= -1 then
local thisTerrain = GameInfo.Terrains[terrainId];
if thisTerrain then
-- update the name
local name = Locale.ConvertTextKey( thisTerrain.Description )
Controls.ArticleID:SetText( name );
-- update the portrait
if IconHookup( thisTerrain.PortraitIndex, portraitSize, thisTerrain.IconAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
local buttonAdded = 0;
local condition = "TerrainType = '" .. thisTerrain.Type .. "'";
-- City Yield
Controls.YieldFrame:SetHide( false );
local numYields = 0;
local yieldString = "";
for row in GameInfo.Terrain_Yields( condition ) do
numYields = numYields + 1;
yieldString = yieldString..tostring(row.Yield).." ";
yieldString = yieldString..GameInfo.Yields[row.YieldType].IconString.." ";
end
-- special case hackery for hills
if thisTerrain.Type == "TERRAIN_HILL" then
--for row in GameInfo.Yields() do
--if row.HillsChange ~= 0 then
--numYields = numYields + 1;
--if row.HillsChange > 0 then
--yieldString = yieldString.."+";
--end
--yieldString = yieldString..tostring(row.HillsChange).." ";
--yieldString = yieldString..row.IconString.." ";
--end
--end
numYields = 1;
yieldString = "2 [ICON_PRODUCTION]"
end
if numYields == 0 then
Controls.YieldLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_NO_YIELD" ) );
else
Controls.YieldLabel:SetText( Locale.ConvertTextKey( yieldString ) );
end
-- Movement
Controls.MovementCostFrame:SetHide( false );
local moveCost = thisTerrain.Movement;
-- special case hackery for hills
if thisTerrain.Type == "TERRAIN_HILL" then
moveCost = moveCost + GameDefines.HILLS_EXTRA_MOVEMENT;
end
if thisTerrain.Type == "TERRAIN_MOUNTAIN" then
Controls.MovementCostLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_IMPASSABLE" ) );
else
Controls.MovementCostLabel:SetText( Locale.ConvertTextKey( moveCost ).."[ICON_MOVES]" );
end
-- Combat Modifier
Controls.CombatModFrame:SetHide( false );
local combatModifier = 0;
local combatModString = "";
if thisTerrain.Type == "TERRAIN_HILL" or thisTerrain.Type == "TERRAIN_MOUNTAIN" then
combatModifier = GameDefines.HILLS_EXTRA_DEFENSE;
elseif thisTerrain.Water then
combatModifier = 0;
else
combatModifier = GameDefines.FLAT_LAND_EXTRA_DEFENSE;
end
if combatModifier > 0 then
combatModString = "+";
end
combatModString = combatModString..tostring(combatModifier).."%";
Controls.CombatModLabel:SetText( combatModString );
-- Features that can exist on this terrain
g_FeaturesManager:ResetInstances();
buttonAdded = 0;
for row in GameInfo.Feature_TerrainBooleans( condition ) do
local thisFeature = GameInfo.Features[row.FeatureType];
if thisFeature then
local thisFeatureInstance = g_FeaturesManager:GetInstance();
if thisFeatureInstance then
local textureOffset, textureSheet = IconLookup( thisFeature.PortraitIndex, buttonSize, thisFeature.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisFeatureInstance.FeatureImage, thisFeatureInstance.FeatureButton, textureSheet, textureOffset, CategoryTerrain, Locale.ConvertTextKey( thisFeature.Description ), thisFeature.ID + 1000 ); -- todo: add a fudge factor
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.FeaturesInnerFrame, Controls.FeaturesFrame );
-- MOD - Resources that can exist on this terrain
Controls.ResourcesFoundLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_RESOURCESFOUND_LABEL" ) );
g_ResourcesFoundManager:ResetInstances();
buttonAdded = 0;
for row in GameInfo.Resource_TerrainBooleans( condition ) do
local thisResource = GameInfo.Resources[row.ResourceType];
if thisResource then
local thisResourceInstance = g_ResourcesFoundManager:GetInstance();
if thisResourceInstance then
local textureOffset, textureSheet = IconLookup( thisResource.PortraitIndex, buttonSize, thisResource.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButtonWide( buttonAdded, thisResourceInstance.ResourceFoundImage, thisResourceInstance.ResourceFoundButton, textureSheet, textureOffset, CategoryResources, Locale.ConvertTextKey( thisResource.Description ), thisResource.ID );
buttonAdded = buttonAdded + 1;
end
end
end
-- special case hackery for hills
if thisTerrain.Type == "TERRAIN_HILL" then
for thisResource in GameInfo.Resources() do
if thisResource and thisResource.Hills then
local thisResourceInstance = g_ResourcesFoundManager:GetInstance();
if thisResourceInstance then
local textureOffset, textureSheet = IconLookup( thisResource.PortraitIndex, buttonSize, thisResource.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButtonWide( buttonAdded, thisResourceInstance.ResourceFoundImage, thisResourceInstance.ResourceFoundButton, textureSheet, textureOffset, CategoryResources, Locale.ConvertTextKey( thisResource.Description ), thisResource.ID );
buttonAdded = buttonAdded + 1;
end
end
end
end
UpdateWideButtonFrame( buttonAdded, Controls.ResourcesFoundInnerFrame, Controls.ResourcesFoundFrame );
-- generic text
if (thisTerrain.Civilopedia) then
UpdateTextBlock( Locale.ConvertTextKey( thisTerrain.Civilopedia ), Controls.GameInfoLabel, Controls.GameInfoInnerFrame, Controls.GameInfoFrame );
end
-- MOD - update supporting buildings
g_SupportingBuildingManager:ResetInstances();
buttonAdded = 0;
local supportingBuilding = {};
local debugTable = {}; -- I bet in some certain solutions this is not useful... well, who knows?
local iDebug = 0;
for row in GameInfo.Building_TerrainYieldChanges( condition ) do
local building = GameInfo.Buildings[row.BuildingType];
if (building) and (building.Civilopedia ~= nil) then
local iAlready = -1;
local bDebug = false;
for i = 0, buttonAdded-1, 1 do
if supportingBuilding[i] then
if (supportingBuilding[i].ID == building.ID) then
for j = 0, iDebug-1, 1 do
if ( (debugTable[j].ID == building.ID) and (debugTable[j].Yield == row.YieldType) ) then
bDebug = true;
break;
end
end
if (not bDebug) then
iAlready = i;
end
break;
end
end
end
if (not bDebug) then
if (iAlready ~= -1) then
local description = "";
if (row.Yield > 0) then
description = supportingBuilding[iAlready].Text .. ", +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString;
else
description = supportingBuilding[iAlready].Text .. ", [COLOR_NEGATIVE_TEXT]" .. tostring(row.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row.YieldType].IconString;
end
supportingBuilding[iAlready].Text = description;
debugTable[iDebug] = { ID=building.ID, Yield=row.YieldType };
iDebug = iDebug + 1;
else
local thisBuildingInstance = g_SupportingBuildingManager:GetInstance();
if thisBuildingInstance then
local textureOffset, textureSheet = IconLookup( building.PortraitIndex, buttonSize, building.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
local description = "";
if (row.Yield > 0) then
description = Locale.ConvertTextKey( building.Description ) .. ": +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString;
else
description = Locale.ConvertTextKey( building.Description ) .. ": [COLOR_NEGATIVE_TEXT]" .. tostring(row.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row.YieldType].IconString;
end
supportingBuilding[buttonAdded] = { Num=buttonAdded, Image=thisBuildingInstance.SupportingBuildingImage, Button=thisBuildingInstance.SupportingBuildingButton, Icon=textureSheet, Offset=textureOffset, Category=CategoryBuildings, Text=description, ID=building.ID};
debugTable[iDebug] = { ID=building.ID, Yield=row.YieldType };
buttonAdded = buttonAdded + 1;
iDebug = iDebug + 1;
end
end
end
end
end
-- for sea plots
if (thisTerrain.Type == "TERRAIN_COAST") or (thisTerrain.Type == "TERRAIN_OCEAN") then
for row in GameInfo.Building_SeaPlotYieldChanges() do
local building = GameInfo.Buildings[row.BuildingType];
if (building) and (building.Civilopedia ~= nil) then
local iAlready = -1;
local bDebug = false;
for i = 0, buttonAdded-1, 1 do
if supportingBuilding[i] then
if (supportingBuilding[i].ID == building.ID) then
for j = 0, iDebug-1, 1 do
if ( (debugTable[j].ID == building.ID) and (debugTable[j].Yield == row.YieldType) ) then
bDebug = true;
break;
end
end
if (not bDebug) then
iAlready = i;
end
break;
end
end
end
if (not bDebug) then
if (iAlready ~= -1) then
local description = "";
if (row.Yield > 0) then
description = supportingBuilding[iAlready].Text .. ", +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString;
else
description = supportingBuilding[iAlready].Text .. ", [COLOR_NEGATIVE_TEXT]" .. tostring(row.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row.YieldType].IconString;
end
supportingBuilding[iAlready].Text = description;
debugTable[iDebug] = { ID=building.ID, Yield=row.YieldType };
iDebug = iDebug + 1;
else
local thisBuildingInstance = g_SupportingBuildingManager:GetInstance();
if thisBuildingInstance then
local textureOffset, textureSheet = IconLookup( building.PortraitIndex, buttonSize, building.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
local description = "";
if (row.Yield > 0) then
description = Locale.ConvertTextKey( building.Description ) .. ": +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString;
else
description = Locale.ConvertTextKey( building.Description ) .. ": [COLOR_NEGATIVE_TEXT]" .. tostring(row.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row.YieldType].IconString;
end
supportingBuilding[buttonAdded] = { Num=buttonAdded, Image=thisBuildingInstance.SupportingBuildingImage, Button=thisBuildingInstance.SupportingBuildingButton, Icon=textureSheet, Offset=textureOffset, Category=CategoryBuildings, Text=description, ID=building.ID};
debugTable[iDebug] = { ID=building.ID, Yield=row.YieldType };
buttonAdded = buttonAdded + 1;
iDebug = iDebug + 1;
end
end
end
end
end
end
if (buttonAdded ~= 0) then
for i = 0, buttonAdded-1, 1 do
UpdateSmallButtonWide( supportingBuilding[i].Num, supportingBuilding[i].Image, supportingBuilding[i].Button, supportingBuilding[i].Icon, supportingBuilding[i].Offset, supportingBuilding[i].Category, supportingBuilding[i].Text, supportingBuilding[i].ID );
end
end
UpdateWideButtonFrame( buttonAdded, Controls.SupportingBuildingInnerFrame, Controls.SupportingBuildingFrame );
-- update the related images
Controls.RelatedImagesFrame:SetHide( true );
end
end
else
local featureID = rawTerrainID - 1000;
if featureID ~= -1 then
local thisFeature;
if featureID < 1000 then
thisFeature = GameInfo.Features[featureID];
else
thisFeature = GameInfo.FakeFeatures[featureID-1000];
end
if thisFeature then
-- update the name
local name = Locale.ConvertTextKey( thisFeature.Description )
Controls.ArticleID:SetText( name );
-- update the portrait
if IconHookup( thisFeature.PortraitIndex, portraitSize, thisFeature.IconAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
local buttonAdded = 0;
local condition = "FeatureType = '" .. thisFeature.Type .. "'";
-- City Yield
Controls.YieldFrame:SetHide( false );
local numYields = 0;
local yieldString = "";
for row in GameInfo.Feature_YieldChanges( condition ) do
numYields = numYields + 1;
yieldString = yieldString..tostring(row.Yield).." ";
yieldString = yieldString..GameInfo.Yields[row.YieldType].IconString.." ";
end
-- add happiness since it is a quasi-yield
if thisFeature.InBorderHappiness and thisFeature.InBorderHappiness ~= 0 then
numYields = numYields + 1;
yieldString = yieldString.." ";
yieldString = yieldString..tostring(thisFeature.InBorderHappiness).."[ICON_HAPPINESS_1]".." ";
end
if numYields == 0 then
Controls.YieldLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_NO_YIELD" ) );
else
Controls.YieldLabel:SetText( Locale.ConvertTextKey( yieldString ) );
end
-- Movement
Controls.MovementCostFrame:SetHide( false );
local moveCost = thisFeature.Movement;
if thisFeature.Impassable then
Controls.MovementCostLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_IMPASSABLE" ) );
else
Controls.MovementCostLabel:SetText( Locale.ConvertTextKey( moveCost ).."[ICON_MOVES]" );
end
-- Combat Modifier
Controls.CombatModFrame:SetHide( false );
local combatModifier = thisFeature.Defense;
local combatModString = "";
if combatModifier > 0 then
combatModString = "+";
end
combatModString = combatModString..tostring(combatModifier).."%";
Controls.CombatModLabel:SetText( combatModString );
-- Features that can exist on this terrain
g_FeaturesManager:ResetInstances();
buttonAdded = 0;
for row in GameInfo.Feature_TerrainBooleans( condition ) do
local thisTerrain = GameInfo.Features[row.TerrainType];
if thisTerrain then
local thisTerrainInstance = g_FeaturesManager:GetInstance();
if thisTerrainInstance then
local textureOffset, textureSheet = IconLookup( thisTerrain.PortraitIndex, buttonSize, thisTerrain.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisTerrainInstance.FeatureImage, thisTerrainInstance.FeatureButton, textureSheet, textureOffset, CategoryTerrain, Locale.ConvertTextKey( thisTerrain.Description ), thisTerrain.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.TerrainsInnerFrame, Controls.TerrainsFrame );
-- MOD - Resources that can exist on this feature
Controls.ResourcesFoundLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_RESOURCESFOUND_LABEL" ) );
g_ResourcesFoundManager:ResetInstances();
buttonAdded = 0;
for row in GameInfo.Resource_FeatureBooleans( condition ) do
local thisResource = GameInfo.Resources[row.ResourceType];
if thisResource then
local thisResourceInstance = g_ResourcesFoundManager:GetInstance();
if thisResourceInstance then
local textureOffset, textureSheet = IconLookup( thisResource.PortraitIndex, buttonSize, thisResource.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButtonWide( buttonAdded, thisResourceInstance.ResourceFoundImage, thisResourceInstance.ResourceFoundButton, textureSheet, textureOffset, CategoryResources, Locale.ConvertTextKey( thisResource.Description ), thisResource.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateWideButtonFrame( buttonAdded, Controls.ResourcesFoundInnerFrame, Controls.ResourcesFoundFrame );
if(featureID < 1000) then
-- generic text
if (thisFeature.Help) then
UpdateTextBlock( Locale.ConvertTextKey( thisFeature.Help ), Controls.GameInfoLabel, Controls.GameInfoInnerFrame, Controls.GameInfoFrame );
end
if (thisFeature.Civilopedia) then
UpdateTextBlock( Locale.ConvertTextKey( thisFeature.Civilopedia ), Controls.HistoryLabel, Controls.HistoryInnerFrame, Controls.HistoryFrame );
end
else
if (thisFeature.Civilopedia) then
UpdateTextBlock( Locale.ConvertTextKey( thisFeature.Civilopedia ), Controls.GameInfoLabel, Controls.GameInfoInnerFrame, Controls.GameInfoFrame );
end
end
-- MOD - update supporting buildings
g_SupportingBuildingManager:ResetInstances();
buttonAdded = 0;
local supportingBuilding = {};
local debugTable = {}; -- I bet in some certain solutions this is not useful... well, who knows?
local iDebug = 0;
for row in GameInfo.Building_FeatureYieldChanges( condition ) do
local building = GameInfo.Buildings[row.BuildingType];
if (building) and (building.Civilopedia ~= nil) then
local iAlready = -1;
local bDebug = false;
for i = 0, buttonAdded-1, 1 do
if supportingBuilding[i] then
if (supportingBuilding[i].ID == building.ID) then
for j = 0, iDebug-1, 1 do
if ( (debugTable[j].ID == building.ID) and (debugTable[j].Yield == row.YieldType) ) then
bDebug = true;
break;
end
end
if (not bDebug) then
iAlready = i;
end
break;
end
end
end
if (not bDebug) then
if (iAlready ~= -1) then
local description = "";
if (row.Yield > 0) then
description = supportingBuilding[iAlready].Text .. ", +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString;
else
description = supportingBuilding[iAlready].Text .. ", [COLOR_NEGATIVE_TEXT]" .. tostring(row.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row.YieldType].IconString;
end
supportingBuilding[iAlready].Text = description;
debugTable[iDebug] = { ID=building.ID, Yield=row.YieldType };
iDebug = iDebug + 1;
else
local thisBuildingInstance = g_SupportingBuildingManager:GetInstance();
if thisBuildingInstance then
local textureOffset, textureSheet = IconLookup( building.PortraitIndex, buttonSize, building.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
local description = "";
if (row.Yield > 0) then
description = Locale.ConvertTextKey( building.Description ) .. ": +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString;
else
description = Locale.ConvertTextKey( building.Description ) .. ": [COLOR_NEGATIVE_TEXT]" .. tostring(row.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row.YieldType].IconString;
end
supportingBuilding[buttonAdded] = { Num=buttonAdded, Image=thisBuildingInstance.SupportingBuildingImage, Button=thisBuildingInstance.SupportingBuildingButton, Icon=textureSheet, Offset=textureOffset, Category=CategoryBuildings, Text=description, ID=building.ID};
debugTable[iDebug] = { ID=building.ID, Yield=row.YieldType };
buttonAdded = buttonAdded + 1;
iDebug = iDebug + 1;
end
end
end
end
end
-- for rivers and lakes
if (thisFeature.Type == "FEATURE_RIVER") then
for row in GameInfo.Building_RiverPlotYieldChanges() do
local building = GameInfo.Buildings[row.BuildingType];
if (building) and (building.Civilopedia ~= nil) then
local iAlready = -1;
local bDebug = false;
for i = 0, buttonAdded-1, 1 do
if supportingBuilding[i] then
if (supportingBuilding[i].ID == building.ID) then
for j = 0, iDebug-1, 1 do
if ( (debugTable[j].ID == building.ID) and (debugTable[j].Yield == row.YieldType) ) then
bDebug = true;
break;
end
end
if (not bDebug) then
iAlready = i;
end
break;
end
end
end
if (not bDebug) then
if (iAlready ~= -1) then
local description = "";
if (row.Yield > 0) then
description = supportingBuilding[iAlready].Text .. ", +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString;
else
description = supportingBuilding[iAlready].Text .. ", [COLOR_NEGATIVE_TEXT]" .. tostring(row.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row.YieldType].IconString;
end
supportingBuilding[iAlready].Text = description;
debugTable[iDebug] = { ID=building.ID, Yield=row.YieldType };
iDebug = iDebug + 1;
else
local thisBuildingInstance = g_SupportingBuildingManager:GetInstance();
if thisBuildingInstance then
local textureOffset, textureSheet = IconLookup( building.PortraitIndex, buttonSize, building.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
local description = "";
if (row.Yield > 0) then
description = Locale.ConvertTextKey( building.Description ) .. ": +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString;
else
description = Locale.ConvertTextKey( building.Description ) .. ": [COLOR_NEGATIVE_TEXT]" .. tostring(row.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row.YieldType].IconString;
end
supportingBuilding[buttonAdded] = { Num=buttonAdded, Image=thisBuildingInstance.SupportingBuildingImage, Button=thisBuildingInstance.SupportingBuildingButton, Icon=textureSheet, Offset=textureOffset, Category=CategoryBuildings, Text=description, ID=building.ID};
debugTable[iDebug] = { ID=building.ID, Yield=row.YieldType };
buttonAdded = buttonAdded + 1;
iDebug = iDebug + 1;
end
end
end
end
end
end
if (thisFeature.Type == "FEATURE_LAKE") then
for row in GameInfo.Building_LakePlotYieldChanges() do
local building = GameInfo.Buildings[row.BuildingType];
if (building) and (building.Civilopedia ~= nil) then
local iAlready = -1;
local bDebug = false;
for i = 0, buttonAdded-1, 1 do
if supportingBuilding[i] then
if (supportingBuilding[i].ID == building.ID) then
for j = 0, iDebug-1, 1 do
if ( (debugTable[j].ID == building.ID) and (debugTable[j].Yield == row.YieldType) ) then
bDebug = true;
break;
end
end
if (not bDebug) then
iAlready = i;
end
break;
end
end
end
if (not bDebug) then
if (iAlready ~= -1) then
local description = "";
if (row.Yield > 0) then
description = supportingBuilding[iAlready].Text .. ", +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString;
else
description = supportingBuilding[iAlready].Text .. ", [COLOR_NEGATIVE_TEXT]" .. tostring(row.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row.YieldType].IconString;
end
supportingBuilding[iAlready].Text = description;
debugTable[iDebug] = { ID=building.ID, Yield=row.YieldType };
iDebug = iDebug + 1;
else
local thisBuildingInstance = g_SupportingBuildingManager:GetInstance();
if thisBuildingInstance then
local textureOffset, textureSheet = IconLookup( building.PortraitIndex, buttonSize, building.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
local description = "";
if (row.Yield > 0) then
description = Locale.ConvertTextKey( building.Description ) .. ": +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString;
else
description = Locale.ConvertTextKey( building.Description ) .. ": [COLOR_NEGATIVE_TEXT]" .. tostring(row.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row.YieldType].IconString;
end
supportingBuilding[buttonAdded] = { Num=buttonAdded, Image=thisBuildingInstance.SupportingBuildingImage, Button=thisBuildingInstance.SupportingBuildingButton, Icon=textureSheet, Offset=textureOffset, Category=CategoryBuildings, Text=description, ID=building.ID};
debugTable[iDebug] = { ID=building.ID, Yield=row.YieldType };
buttonAdded = buttonAdded + 1;
iDebug = iDebug + 1;
end
end
end
end
end
end
if (buttonAdded ~= 0) then
for i = 0, buttonAdded-1, 1 do
UpdateSmallButtonWide( supportingBuilding[i].Num, supportingBuilding[i].Image, supportingBuilding[i].Button, supportingBuilding[i].Icon, supportingBuilding[i].Offset, supportingBuilding[i].Category, supportingBuilding[i].Text, supportingBuilding[i].ID );
end
end
UpdateWideButtonFrame( buttonAdded, Controls.SupportingBuildingInnerFrame, Controls.SupportingBuildingFrame );
-- update the related images
Controls.RelatedImagesFrame:SetHide( true );
end
end
end
ResizeEtc();
end
CivilopediaCategory[CategoryResources].SelectArticle = function( resourceID, shouldAddToList )
print("CivilopediaCategory[CategoryResources].SelectArticle");
if selectedCategory ~= CategoryResources then
SetSelectedCategory(CategoryResources);
end
ClearArticle();
if shouldAddToList == addToList then
currentTopic = currentTopic + 1;
listOfTopicsViewed[currentTopic] = categorizedList[(CategoryResources * absurdlyLargeNumTopicsInCategory) + resourceID];
for i = currentTopic + 1, endTopic, 1 do
listOfTopicsViewed[i] = nil;
end
endTopic = currentTopic;
end
if resourceID ~= -1 then
local thisResource = GameInfo.Resources[resourceID];
if thisResource then
-- update the name
local name = Locale.ConvertTextKey( thisResource.Description )
Controls.ArticleID:SetText( name );
-- update the portrait
if IconHookup( thisResource.PortraitIndex, portraitSize, thisResource.IconAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
local buttonAdded = 0;
local condition = "ResourceType = '" .. thisResource.Type .. "'";
-- tech visibility
g_RevealTechsManager:ResetInstances();
buttonAdded = 0;
if thisResource.TechReveal then
local prereq = GameInfo.Technologies[thisResource.TechReveal];
local thisPrereqInstance = g_RevealTechsManager:GetInstance();
if thisPrereqInstance then
local textureOffset, textureSheet = IconLookup( prereq.PortraitIndex, buttonSize, prereq.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisPrereqInstance.RevealTechImage, thisPrereqInstance.RevealTechButton, textureSheet, textureOffset, CategoryTech, Locale.ConvertTextKey( prereq.Description ), prereq.ID );
buttonAdded = buttonAdded + 1;
end
UpdateButtonFrame( buttonAdded, Controls.RevealTechsInnerFrame, Controls.RevealTechsFrame );
end
-- City Yield
Controls.YieldFrame:SetHide( false );
local numYields = 0;
local yieldString = "";
for row in GameInfo.Resource_YieldChanges( condition ) do
numYields = numYields + 1;
if row.Yield > 0 then
yieldString = yieldString.."+";
end
yieldString = yieldString..tostring(row.Yield)..GameInfo.Yields[row.YieldType].IconString.." ";
end
if numYields == 0 then
Controls.YieldLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_NO_YIELD" ) );
else
Controls.YieldLabel:SetText( Locale.ConvertTextKey( yieldString ) );
end
-- found on
Controls.ResourcesFoundLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_TERRAINS_LABEL" ) );
g_ResourcesFoundManager:ResetInstances(); -- okay, this is supposed to be a resource, but for now a round button is a round button
buttonAdded = 0;
for row in GameInfo.Resource_FeatureBooleans( condition ) do
local thisFeature = GameInfo.Features[row.FeatureType];
if thisFeature then
local thisFeatureInstance = g_ResourcesFoundManager:GetInstance();
if thisFeatureInstance then
local textureOffset, textureSheet = IconLookup( thisFeature.PortraitIndex, buttonSize, thisFeature.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButtonWide( buttonAdded, thisFeatureInstance.ResourceFoundImage, thisFeatureInstance.ResourceFoundButton, textureSheet, textureOffset, CategoryTerrain, Locale.ConvertTextKey( thisFeature.Description ), thisFeature.ID + 1000 ); -- todo: add a fudge factor
buttonAdded = buttonAdded + 1;
end
end
end
local bAlreadyShowingHills = false;
for row in GameInfo.Resource_TerrainBooleans( condition ) do
local thisTerrain = GameInfo.Terrains[row.TerrainType];
if thisTerrain then
local thisTerrainInstance = g_ResourcesFoundManager:GetInstance();
if thisTerrainInstance then
if(row.TerrainType == "TERRAIN_HILL") then
bAlreadyShowingHills = true;
end
local textureOffset, textureSheet = IconLookup( thisTerrain.PortraitIndex, buttonSize, thisTerrain.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButtonWide( buttonAdded, thisTerrainInstance.ResourceFoundImage, thisTerrainInstance.ResourceFoundButton, textureSheet, textureOffset, CategoryTerrain, Locale.ConvertTextKey( thisTerrain.Description ), thisTerrain.ID );
buttonAdded = buttonAdded + 1;
end
end
end
-- hackery for hills
if thisResource and thisResource.Hills and not bAlreadyShowingHills then
local thisTerrain = GameInfo.Terrains["TERRAIN_HILL"];
local thisTerrainInstance = g_ResourcesFoundManager:GetInstance();
if thisTerrainInstance then
local textureOffset, textureSheet = IconLookup( thisTerrain.PortraitIndex, buttonSize, thisTerrain.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButtonWide( buttonAdded, thisTerrainInstance.ResourceFoundImage, thisTerrainInstance.ResourceFoundButton, textureSheet, textureOffset, CategoryTerrain, Locale.ConvertTextKey( thisTerrain.Description ), thisTerrain.ID );
buttonAdded = buttonAdded + 1;
end
end
UpdateWideButtonFrame( buttonAdded, Controls.ResourcesFoundInnerFrame, Controls.ResourcesFoundFrame );
-- MOD - improvement
g_ImprovementsManager:ResetInstances();
buttonAdded = 0;
for row in GameInfo.Improvement_ResourceTypes( condition ) do
local thisImprovement = GameInfo.Improvements[row.ImprovementType];
if thisImprovement then
local thisImprovementInstance = g_ImprovementsManager:GetInstance();
if thisImprovementInstance then
local textureOffset, textureSheet = IconLookup( thisImprovement.PortraitIndex, buttonSize, thisImprovement.IconAtlas );
local description = Locale.ConvertTextKey( thisImprovement.Description );
local bNew = true;
for row2 in GameInfo.Improvement_ResourceType_Yields( "ResourceType = '" .. thisResource.Type .. "' and ImprovementType = '" .. row.ImprovementType .."'" ) do
if bNew then
if (row2.Yield > 0) then
description = description .. ": +" .. tostring(row2.Yield) .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_ADDITIONAL" ) .. GameInfo.Yields[row2.YieldType].IconString;
else
description = description .. ": [COLOR_NEGATIVE_TEXT]" .. tostring(row2.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row2.YieldType].IconString;
end
bNew = false;
else
if (row2.Yield > 0) then
description = description .. ", +" .. tostring(row2.Yield) .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_ADDITIONAL" ) .. GameInfo.Yields[row2.YieldType].IconString;
else
description = description .. ", [COLOR_NEGATIVE_TEXT]" .. tostring(row2.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row2.YieldType].IconString;
end
end
end
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisImprovementInstance.ImprovementImage, thisImprovementInstance.ImprovementButton, textureSheet, textureOffset, CategoryImprovements, description, thisImprovement.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.ImprovementsInnerFrame, Controls.ImprovementsFrame );
-- game info
if (thisResource.Help) then
UpdateTextBlock( Locale.ConvertTextKey( thisResource.Help ), Controls.GameInfoLabel, Controls.GameInfoInnerFrame, Controls.GameInfoFrame );
end
-- MOD - update supporting buildings
g_SupportingBuildingManager:ResetInstances();
buttonAdded = 0;
local supportingBuilding = {};
local debugTable = {}; -- I bet in some certain solutions this is not useful... well, who knows?
local iDebug = 0;
for row in GameInfo.Building_ResourceYieldChanges( condition ) do
local building = GameInfo.Buildings[row.BuildingType];
if (building) and (building.Civilopedia ~= nil) then
local iAlready = -1;
local bDebug = false;
for i = 0, buttonAdded-1, 1 do
if supportingBuilding[i] then
if (supportingBuilding[i].ID == building.ID) then
for j = 0, iDebug-1, 1 do
if ( (debugTable[j].ID == building.ID) and (debugTable[j].Yield == row.YieldType) ) then
bDebug = true;
break;
end
end
if (not bDebug) then
iAlready = i;
end
break;
end
end
end
if (not bDebug) then
if (iAlready ~= -1) then
local description = "";
if (row.Yield > 0) then
description = supportingBuilding[iAlready].Text .. ", +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString;
else
description = supportingBuilding[iAlready].Text .. ", [COLOR_NEGATIVE_TEXT]" .. tostring(row.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row.YieldType].IconString;
end
supportingBuilding[iAlready].Text = description;
debugTable[iDebug] = { ID=building.ID, Yield=row.YieldType };
iDebug = iDebug + 1;
else
local thisBuildingInstance = g_SupportingBuildingManager:GetInstance();
if thisBuildingInstance then
local textureOffset, textureSheet = IconLookup( building.PortraitIndex, buttonSize, building.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
local description = "";
if (row.Yield > 0) then
description = Locale.ConvertTextKey( building.Description ) .. ": +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString;
else
description = Locale.ConvertTextKey( building.Description ) .. ": [COLOR_NEGATIVE_TEXT]" .. tostring(row.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row.YieldType].IconString;
end
supportingBuilding[buttonAdded] = { Num=buttonAdded, Image=thisBuildingInstance.SupportingBuildingImage, Button=thisBuildingInstance.SupportingBuildingButton, Icon=textureSheet, Offset=textureOffset, Category=CategoryBuildings, Text=description, ID=building.ID};
debugTable[iDebug] = { ID=building.ID, Yield=row.YieldType };
buttonAdded = buttonAdded + 1;
iDebug = iDebug + 1;
end
end
end
end
end
-- for culture and faith
for row in GameInfo.Building_ResourceCultureChanges( condition ) do
local building = GameInfo.Buildings[row.BuildingType];
if (building) and (building.Civilopedia ~= nil) then
local iAlready = -1;
local bDebug = false;
for i = 0, buttonAdded-1, 1 do
if supportingBuilding[i] then
if (supportingBuilding[i].ID == building.ID) then
for j = 0, iDebug-1, 1 do
if ( (debugTable[j].ID == building.ID) and (debugTable[j].Yield == YieldTypes.YIELD_CULTURE) ) then
bDebug = true;
break;
end
end
if (not bDebug) then
iAlready = i;
end
break;
end
end
end
if (not bDebug) then
if (iAlready ~= -1) then
local description = "";
if (row.CultureChange > 0) then
description = supportingBuilding[iAlready].Text .. ", +" .. tostring(row.CultureChange) .. GameInfo.Yields[YieldTypes.YIELD_CULTURE].IconString;
else
description = supportingBuilding[iAlready].Text .. ", [COLOR_NEGATIVE_TEXT]" .. tostring(row.CultureChange) .. "[ENDCOLOR]" .. GameInfo.Yields[YieldTypes.YIELD_CULTURE].IconString;
end
supportingBuilding[iAlready].Text = description;
debugTable[iDebug] = { ID=building.ID, Yield=YieldTypes.YIELD_CULTURE };
iDebug = iDebug + 1;
else
local thisBuildingInstance = g_SupportingBuildingManager:GetInstance();
if thisBuildingInstance then
local textureOffset, textureSheet = IconLookup( building.PortraitIndex, buttonSize, building.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
local description = "";
if (row.CultureChange > 0) then
description = Locale.ConvertTextKey( building.Description ) .. ": +" .. tostring(row.CultureChange) .. GameInfo.Yields[YieldTypes.YIELD_CULTURE].IconString;
else
description = Locale.ConvertTextKey( building.Description ) .. ": [COLOR_NEGATIVE_TEXT]" .. tostring(row.CultureChange) .. "[ENDCOLOR]" .. GameInfo.Yields[YieldTypes.YIELD_CULTURE].IconString;
end
supportingBuilding[buttonAdded] = { Num=buttonAdded, Image=thisBuildingInstance.SupportingBuildingImage, Button=thisBuildingInstance.SupportingBuildingButton, Icon=textureSheet, Offset=textureOffset, Category=CategoryBuildings, Text=description, ID=building.ID};
debugTable[iDebug] = { ID=building.ID, Yield=YieldTypes.YIELD_CULTURE };
buttonAdded = buttonAdded + 1;
iDebug = iDebug + 1;
end
end
end
end
end
for row in GameInfo.Building_ResourceFaithChanges( condition ) do
local building = GameInfo.Buildings[row.BuildingType];
if (building) and (building.Civilopedia ~= nil) then
local iAlready = -1;
local bDebug = false;
for i = 0, buttonAdded-1, 1 do
if supportingBuilding[i] then
if (supportingBuilding[i].ID == building.ID) then
for j = 0, iDebug-1, 1 do
if ( (debugTable[j].ID == building.ID) and (debugTable[j].Yield == YieldTypes.YIELD_FAITH) ) then
bDebug = true;
break;
end
end
if (not bDebug) then
iAlready = i;
end
break;
end
end
end
if (not bDebug) then
if (iAlready ~= -1) then
local description = "";
if (row.FaithChange > 0) then
description = supportingBuilding[iAlready].Text .. ", +" .. tostring(row.FaithChange) .. GameInfo.Yields[YieldTypes.YIELD_FAITH].IconString;
else
description = supportingBuilding[iAlready].Text .. ", [COLOR_NEGATIVE_TEXT]" .. tostring(row.FaithChange) .. "[ENDCOLOR]" .. GameInfo.Yields[YieldTypes.YIELD_FAITH].IconString;
end
supportingBuilding[iAlready].Text = description;
debugTable[iDebug] = { ID=building.ID, Yield=YieldTypes.YIELD_FAITH };
iDebug = iDebug + 1;
else
local thisBuildingInstance = g_SupportingBuildingManager:GetInstance();
if thisBuildingInstance then
local textureOffset, textureSheet = IconLookup( building.PortraitIndex, buttonSize, building.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
local description = "";
if (row.FaithChange > 0) then
description = Locale.ConvertTextKey( building.Description ) .. ": +" .. tostring(row.FaithChange) .. GameInfo.Yields[YieldTypes.YIELD_FAITH].IconString;
else
description = Locale.ConvertTextKey( building.Description ) .. ": [COLOR_NEGATIVE_TEXT]" .. tostring(row.FaithChange) .. "[ENDCOLOR]" .. GameInfo.Yields[YieldTypes.YIELD_FAITH].IconString;
end
supportingBuilding[buttonAdded] = { Num=buttonAdded, Image=thisBuildingInstance.SupportingBuildingImage, Button=thisBuildingInstance.SupportingBuildingButton, Icon=textureSheet, Offset=textureOffset, Category=CategoryBuildings, Text=description, ID=building.ID};
debugTable[iDebug] = { ID=building.ID, Yield=YieldTypes.YIELD_FAITH };
buttonAdded = buttonAdded + 1;
iDebug = iDebug + 1;
end
end
end
end
end
-- for sea resources
local bSea = false;
for row in GameInfo.Improvement_ResourceTypes( condition ) do
local thisImprovement = GameInfo.Improvements[row.ImprovementType];
if (thisImprovement) and (thisImprovement.Water == true) then
bSea = true;
break;
end
end
if (bSea) then
for row in GameInfo.Building_SeaResourceYieldChanges() do
local building = GameInfo.Buildings[row.BuildingType];
if (building) and (building.Civilopedia ~= nil) then
local iAlready = -1;
local bDebug = false;
for i = 0, buttonAdded-1, 1 do
if supportingBuilding[i] then
if (supportingBuilding[i].ID == building.ID) then
for j = 0, iDebug-1, 1 do
if ( (debugTable[j].ID == building.ID) and (debugTable[j].Yield == row.YieldType) ) then
bDebug = true;
break;
end
end
if (not bDebug) then
iAlready = i;
end
break;
end
end
end
if (not bDebug) then
if (iAlready ~= -1) then
local description = "";
if (row.Yield > 0) then
description = supportingBuilding[iAlready].Text .. ", +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_IN_SEA" );
else
description = supportingBuilding[iAlready].Text .. ", [COLOR_NEGATIVE_TEXT]" .. tostring(row.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row.YieldType].IconString .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_IN_SEA" );
end
supportingBuilding[iAlready].Text = description;
debugTable[iDebug] = { ID=building.ID, Yield=row.YieldType };
iDebug = iDebug + 1;
else
local thisBuildingInstance = g_SupportingBuildingManager:GetInstance();
if thisBuildingInstance then
local textureOffset, textureSheet = IconLookup( building.PortraitIndex, buttonSize, building.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
local description = "";
if (row.Yield > 0) then
description = Locale.ConvertTextKey( building.Description ) .. ": +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_IN_SEA" );
else
description = Locale.ConvertTextKey( building.Description ) .. ": [COLOR_NEGATIVE_TEXT]" .. tostring(row.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row.YieldType].IconString .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_IN_SEA" );
end
supportingBuilding[buttonAdded] = { Num=buttonAdded, Image=thisBuildingInstance.SupportingBuildingImage, Button=thisBuildingInstance.SupportingBuildingButton, Icon=textureSheet, Offset=textureOffset, Category=CategoryBuildings, Text=description, ID=building.ID};
debugTable[iDebug] = { ID=building.ID, Yield=row.YieldType };
buttonAdded = buttonAdded + 1;
iDebug = iDebug + 1;
end
end
end
end
end
end
-- for modifired rate, though it is not being used
debugTable = {};
iDebug = 0;
for row in GameInfo.Building_ResourceYieldModifiers( condition ) do
local building = GameInfo.Buildings[row.BuildingType];
if (building) and (building.Civilopedia ~= nil) then
local iAlready = -1;
local bDebug = false;
for i = 0, buttonAdded-1, 1 do
if supportingBuilding[i] then
if (supportingBuilding[i].ID == building.ID) then
for j = 0, iDebug-1, 1 do
if ( (debugTable[j].ID == building.ID) and (debugTable[j].Yield == row.YieldType) ) then
bDebug = true;
break;
end
end
if (not bDebug) then
iAlready = i;
end
break;
end
end
end
if (not bDebug) then
if (iAlready ~= -1) then
local description = "";
if (row.Yield > 0) then
description = supportingBuilding[iAlready].Text .. ", +" .. tostring(row.Yield) .. "%" .. GameInfo.Yields[row.YieldType].IconString;
else
description = supportingBuilding[iAlready].Text .. ", [COLOR_NEGATIVE_TEXT]" .. tostring(row.Yield) .. "%" .. "[ENDCOLOR]" .. GameInfo.Yields[row.YieldType].IconString;
end
supportingBuilding[iAlready].Text = description;
debugTable[iDebug] = { ID=building.ID, Yield=row.YieldType };
iDebug = iDebug + 1;
else
local thisBuildingInstance = g_SupportingBuildingManager:GetInstance();
if thisBuildingInstance then
local textureOffset, textureSheet = IconLookup( building.PortraitIndex, buttonSize, building.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
local description = "";
if (row.Yield > 0) then
description = Locale.ConvertTextKey( building.Description ) .. ": +" .. tostring(row.Yield) .. "%" .. GameInfo.Yields[row.YieldType].IconString;
else
description = Locale.ConvertTextKey( building.Description ) .. ": [COLOR_NEGATIVE_TEXT]" .. tostring(row.Yield) .. "%" .. "[ENDCOLOR]" .. GameInfo.Yields[row.YieldType].IconString;
end
supportingBuilding[buttonAdded] = { Num=buttonAdded, Image=thisBuildingInstance.SupportingBuildingImage, Button=thisBuildingInstance.SupportingBuildingButton, Icon=textureSheet, Offset=textureOffset, Category=CategoryBuildings, Text=description, ID=building.ID};
debugTable[iDebug] = { ID=building.ID, Yield=row.YieldType };
buttonAdded = buttonAdded + 1;
iDebug = iDebug + 1;
end
end
end
end
end
if (buttonAdded ~= 0) then
for i = 0, buttonAdded-1, 1 do
UpdateSmallButtonWide( supportingBuilding[i].Num, supportingBuilding[i].Image, supportingBuilding[i].Button, supportingBuilding[i].Icon, supportingBuilding[i].Offset, supportingBuilding[i].Category, supportingBuilding[i].Text, supportingBuilding[i].ID );
end
end
UpdateWideButtonFrame( buttonAdded, Controls.SupportingBuildingInnerFrame, Controls.SupportingBuildingFrame );
-- generic text
if (thisResource.Civilopedia) then
UpdateTextBlock( Locale.ConvertTextKey( thisResource.Civilopedia ), Controls.HistoryLabel, Controls.HistoryInnerFrame, Controls.HistoryFrame );
end
-- update the related images
Controls.RelatedImagesFrame:SetHide( true );
end
end
ResizeEtc();
end
CivilopediaCategory[CategoryImprovements].SelectArticle = function( improvementID, shouldAddToList )
print("CivilopediaCategory[CategoryImprovements].SelectArticle");
if selectedCategory ~= CategoryImprovements then
SetSelectedCategory(CategoryImprovements);
end
ClearArticle();
if shouldAddToList == addToList then
currentTopic = currentTopic + 1;
listOfTopicsViewed[currentTopic] = categorizedList[(CategoryImprovements * absurdlyLargeNumTopicsInCategory) + improvementID];
for i = currentTopic + 1, endTopic, 1 do
listOfTopicsViewed[i] = nil;
end
endTopic = currentTopic;
end
if improvementID ~= -1 and improvementID < 1000 then
local thisImprovement = GameInfo.Improvements[improvementID];
if thisImprovement then
-- update the name
local name = Locale.ConvertTextKey( thisImprovement.Description )
Controls.ArticleID:SetText( name );
-- update the portrait
if IconHookup( thisImprovement.PortraitIndex, portraitSize, thisImprovement.IconAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
local buttonAdded = 0;
local condition = "ImprovementType = '" .. thisImprovement.Type .. "'";
-- tech visibility
g_PrereqTechManager:ResetInstances();
buttonAdded = 0;
local prereq = nil;
for row in GameInfo.Builds( condition ) do
if row.PrereqTech then
prereq = GameInfo.Technologies[row.PrereqTech];
end
end
if prereq then
local thisPrereqInstance = g_PrereqTechManager:GetInstance();
if thisPrereqInstance then
local textureOffset, textureSheet = IconLookup( prereq.PortraitIndex, buttonSize, prereq.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisPrereqInstance.PrereqTechImage, thisPrereqInstance.PrereqTechButton, textureSheet, textureOffset, CategoryTech, Locale.ConvertTextKey( prereq.Description ), prereq.ID );
buttonAdded = buttonAdded + 1;
UpdateButtonFrame( buttonAdded, Controls.PrereqTechInnerFrame, Controls.PrereqTechFrame );
end
end
-- City Yield
local numYields = 0;
local yieldString = "";
for row in GameInfo.Improvement_Yields( condition ) do
numYields = numYields + 1;
if row.Yield > 0 then
yieldString = yieldString.."+";
end
yieldString = yieldString..tostring(row.Yield)..GameInfo.Yields[row.YieldType].IconString.." ";
end
if numYields == 0 then
Controls.YieldLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_NO_YIELD" ) );
else
Controls.YieldLabel:SetText( Locale.ConvertTextKey( yieldString ) );
Controls.YieldFrame:SetHide( false );
end
-- add in mountain adjacency yield
numYields = 0;
yieldString = "";
for row in GameInfo.Improvement_AdjacentMountainYieldChanges( condition ) do
numYields = numYields + 1;
if row.Yield > 0 then
yieldString = yieldString.."+";
end
yieldString = yieldString..tostring(row.Yield)..GameInfo.Yields[row.YieldType].IconString.." ";
end
if numYields == 0 then
Controls.MountainYieldFrame:SetHide( true );
else
Controls.MountainYieldLabel:SetText( Locale.ConvertTextKey( yieldString ) );
Controls.MountainYieldFrame:SetHide( false );
end
buttonAdded = 0;
if thisImprovement.CivilizationType then
local thisCiv = GameInfo.Civilizations[thisImprovement.CivilizationType];
if thisCiv then
g_CivilizationsManager:ResetInstances();
local thisCivInstance = g_CivilizationsManager:GetInstance();
if thisCivInstance then
local textureOffset, textureSheet = IconLookup( thisCiv.PortraitIndex, buttonSize, thisCiv.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisCivInstance.CivilizationImage, thisCivInstance.CivilizationButton, textureSheet, textureOffset, CategoryCivilizations, Locale.ConvertTextKey( thisCiv.ShortDescription ), thisCiv.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.CivilizationsInnerFrame, Controls.CivilizationsFrame );
-- found on
Controls.ResourcesFoundLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_FOUNDON_LABEL" ) );
g_ResourcesFoundManager:ResetInstances(); -- okay, this is supposed to be a resource, but for now a round button is a round button
buttonAdded = 0;
for row in GameInfo.Improvement_ValidFeatures( condition ) do
local thisFeature = GameInfo.Features[row.FeatureType];
if thisFeature then
local thisFeatureInstance = g_ResourcesFoundManager:GetInstance();
if thisFeatureInstance then
local textureOffset, textureSheet = IconLookup( thisFeature.PortraitIndex, buttonSize, thisFeature.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButtonWide( buttonAdded, thisFeatureInstance.ResourceFoundImage, thisFeatureInstance.ResourceFoundButton, textureSheet, textureOffset, CategoryTerrain, Locale.ConvertTextKey( thisFeature.Description ), thisFeature.ID + 1000 ); -- todo: add a fudge factor
buttonAdded = buttonAdded + 1;
end
end
end
for row in GameInfo.Improvement_ValidTerrains( condition ) do
local thisTerrain = GameInfo.Terrains[row.TerrainType];
if thisTerrain then
local thisTerrainInstance = g_ResourcesFoundManager:GetInstance();
if thisTerrainInstance then
local textureOffset, textureSheet = IconLookup( thisTerrain.PortraitIndex, buttonSize, thisTerrain.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButtonWide( buttonAdded, thisTerrainInstance.ResourceFoundImage, thisTerrainInstance.ResourceFoundButton, textureSheet, textureOffset, CategoryTerrain, Locale.ConvertTextKey( thisTerrain.Description ), thisTerrain.ID );
buttonAdded = buttonAdded + 1;
end
end
end
-- hackery for hills
--if thisImprovement and thisImprovement.HillsMakesValid then
--local thisTerrain = GameInfo.Terrains["TERRAIN_HILL"];
--local thisTerrainInstance = g_ResourcesFoundManager:GetInstance();
--if thisTerrainInstance then
--local textureSheet;
--local textureOffset;
--textureSheet = defaultErrorTextureSheet;
--textureOffset = nullOffset;
--UpdateSmallButton( buttonAdded, thisTerrainInstance.ResourceFoundImage, thisTerrainInstance.ResourceFoundButton, textureSheet, textureOffset, CategoryTerrain, Locale.ConvertTextKey( thisTerrain.Description ), thisTerrain.ID );
--buttonAdded = buttonAdded + 1;
--end
--end
UpdateWideButtonFrame( buttonAdded, Controls.ResourcesFoundInnerFrame, Controls.ResourcesFoundFrame );
-- MOD - found on resources
Controls.RequiredResourcesLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_IMPROVES_RESRC_LABEL" ) );
g_RequiredResourcesManager:ResetInstances();
buttonAdded = 0;
for row in GameInfo.Improvement_ResourceTypes( condition ) do
local requiredResource = GameInfo.Resources[row.ResourceType];
if requiredResource then
local thisRequiredResourceInstance = g_RequiredResourcesManager:GetInstance();
if thisRequiredResourceInstance then
local textureOffset, textureSheet = IconLookup( requiredResource.PortraitIndex, buttonSize, requiredResource.IconAtlas );
local description = Locale.ConvertTextKey( requiredResource.Description );
local bNew = true;
for row2 in GameInfo.Improvement_ResourceType_Yields( "ResourceType = '" .. row.ResourceType .. "' and ImprovementType = '" .. thisImprovement.Type .."'" ) do
if bNew then
if (row2.Yield > 0) then
description = description .. ": +" .. tostring(row2.Yield) .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_ADDITIONAL" ) .. GameInfo.Yields[row2.YieldType].IconString;
else
description = description .. ": [COLOR_NEGATIVE_TEXT]" .. tostring(row2.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row2.YieldType].IconString;
end
bNew = false;
else
if (row2.Yield > 0) then
description = description .. ", +" .. tostring(row2.Yield) .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_ADDITIONAL" ) .. GameInfo.Yields[row2.YieldType].IconString;
else
description = description .. ", [COLOR_NEGATIVE_TEXT]" .. tostring(row2.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row2.YieldType].IconString;
end
end
end
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisRequiredResourceInstance.RequiredResourceImage, thisRequiredResourceInstance.RequiredResourceButton, textureSheet, textureOffset, CategoryResources, description, requiredResource.ID );
buttonAdded = buttonAdded + 1;
end
end
end
UpdateButtonFrame( buttonAdded, Controls.RequiredResourcesInnerFrame, Controls.RequiredResourcesFrame );
-- update the game info
if (thisImprovement.Help) then
UpdateTextBlock( Locale.ConvertTextKey( thisImprovement.Help ), Controls.GameInfoLabel, Controls.GameInfoInnerFrame, Controls.GameInfoFrame );
end
-- generic text
if (thisImprovement.Civilopedia) then
UpdateTextBlock( Locale.ConvertTextKey( thisImprovement.Civilopedia ), Controls.GameInfoLabel, Controls.GameInfoInnerFrame, Controls.GameInfoFrame );
end
-- MOD - update supporting techs
g_SupportingTechManager:ResetInstances();
buttonAdded = 0;
local supportingTech = {};
local debugTable = {}; -- I bet in some certain solutions this is not useful... well, who knows?
local iDebug = 0;
for row in GameInfo.Improvement_TechYieldChanges( condition ) do
local tech = GameInfo.Technologies[row.TechType];
if tech then
local iAlready = -1;
local bDebug = false;
for i = 0, buttonAdded-1, 1 do
if supportingTech[i] then
if (supportingTech[i].ID == tech.ID) then
for j = 0, iDebug-1, 1 do
if ( (debugTable[j].ID == tech.ID) and (debugTable[j].Yield == row.YieldType) ) then
bDebug = true;
break;
end
end
if (not bDebug) then
iAlready = i;
end
break;
end
end
end
if (not bDebug) then
if (iAlready ~= -1) then
local description = "";
if (row.Yield > 0) then
description = supportingTech[iAlready].Text .. ", +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString;
else
description = supportingTech[iAlready].Text .. ", [COLOR_NEGATIVE_TEXT]" .. tostring(row.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row.YieldType].IconString;
end
supportingTech[iAlready].Text = description;
debugTable[iDebug] = { ID=tech.ID, Yield=row.YieldType };
iDebug = iDebug + 1;
else
local thisTechInstance = g_SupportingTechManager:GetInstance();
if thisTechInstance then
local textureOffset, textureSheet = IconLookup( tech.PortraitIndex, buttonSize, tech.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
local description = "";
if (row.Yield > 0) then
description = Locale.ConvertTextKey( tech.Description ) .. ": +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString;
else
description = Locale.ConvertTextKey( tech.Description ) .. ": [COLOR_NEGATIVE_TEXT]" .. tostring(row.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row.YieldType].IconString;
end
supportingTech[buttonAdded] = { Num=buttonAdded, Image=thisTechInstance.SupportingTechImage, Button=thisTechInstance.SupportingTechButton, Icon=textureSheet, Offset=textureOffset, Category=CategoryTech, Text=description, ID=tech.ID};
debugTable[iDebug] = { ID=tech.ID, Yield=row.YieldType };
buttonAdded = buttonAdded + 1;
iDebug = iDebug + 1;
end
end
end
end
end
-- for fresh water and non-fresh water tiles
for row in GameInfo.Improvement_TechFreshWaterYieldChanges( condition ) do
local tech = GameInfo.Technologies[row.TechType];
if tech then
local iAlready = -1;
local bDebug = false;
for i = 0, buttonAdded-1, 1 do
if supportingTech[i] then
if (supportingTech[i].ID == tech.ID) then
for j = 0, iDebug-1, 1 do
if ( (debugTable[j].ID == tech.ID) and (debugTable[j].Yield == row.YieldType) ) then
bDebug = true;
break;
end
end
if (not bDebug) then
iAlready = i;
end
break;
end
end
end
if (not bDebug) then
if (iAlready ~= -1) then
local description = supportingTech[iAlready].Text .. ", +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_WITH_FRESH_WATER" );
supportingTech[iAlready].Text = description;
debugTable[iDebug] = { ID=tech.ID, Yield=row.YieldType };
iDebug = iDebug + 1;
else
local thisTechInstance = g_SupportingTechManager:GetInstance();
if thisTechInstance then
local textureOffset, textureSheet = IconLookup( tech.PortraitIndex, buttonSize, tech.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
local description = Locale.ConvertTextKey( tech.Description ) .. ": +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_WITH_FRESH_WATER" );
supportingTech[buttonAdded] = { Num=buttonAdded, Image=thisTechInstance.SupportingTechImage, Button=thisTechInstance.SupportingTechButton, Icon=textureSheet, Offset=textureOffset, Category=CategoryTech, Text=description, ID=tech.ID};
debugTable[iDebug] = { ID=tech.ID, Yield=row.YieldType };
buttonAdded = buttonAdded + 1;
iDebug = iDebug + 1;
end
end
end
end
end
for row in GameInfo.Improvement_TechNoFreshWaterYieldChanges( condition ) do
local tech = GameInfo.Technologies[row.TechType];
if tech then
local iAlready = -1;
local bDebug = false;
for i = 0, buttonAdded-1, 1 do
if supportingTech[i] then
if (supportingTech[i].ID == tech.ID) then
for j = 0, iDebug-1, 1 do
if ( (debugTable[j].ID == tech.ID) and (debugTable[j].Yield == row.YieldType) ) then
bDebug = true;
break;
end
end
if (not bDebug) then
iAlready = i;
end
break;
end
end
end
if (not bDebug) then
if (iAlready ~= -1) then
local description = supportingTech[iAlready].Text .. ", +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_WITHOUT_FRESH_WATER" );
supportingTech[iAlready].Text = description;
debugTable[iDebug] = { ID=tech.ID, Yield=row.YieldType };
iDebug = iDebug + 1;
else
local thisTechInstance = g_SupportingTechManager:GetInstance();
if thisTechInstance then
local textureOffset, textureSheet = IconLookup( tech.PortraitIndex, buttonSize, tech.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
local description = Locale.ConvertTextKey( tech.Description ) .. ": +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString .. Locale.ConvertTextKey( "TXT_KEY_CIVILOPEDIA_WITHOUT_FRESH_WATER" );
supportingTech[buttonAdded] = { Num=buttonAdded, Image=thisTechInstance.SupportingTechImage, Button=thisTechInstance.SupportingTechButton, Icon=textureSheet, Offset=textureOffset, Category=CategoryTech, Text=description, ID=tech.ID};
debugTable[iDebug] = { ID=tech.ID, Yield=row.YieldType };
buttonAdded = buttonAdded + 1;
iDebug = iDebug + 1;
end
end
end
end
end
if (buttonAdded ~= 0) then
for i = 0, buttonAdded-1, 1 do
UpdateSmallButtonWide( supportingTech[i].Num, supportingTech[i].Image, supportingTech[i].Button, supportingTech[i].Icon, supportingTech[i].Offset, supportingTech[i].Category, supportingTech[i].Text, supportingTech[i].ID );
end
end
UpdateWideButtonFrame( buttonAdded, Controls.SupportingTechInnerFrame, Controls.SupportingTechFrame );
-- MOD - update supporting policies
g_SupportingPolicyManager:ResetInstances();
buttonAdded = 0;
local supportingPolicy = {};
debugTable = {};
iDebug = 0;
for row in GameInfo.Policy_ImprovementYieldChanges( condition ) do
local policy = GameInfo.Policies[row.PolicyType];
if (policy) and (policy.Civilopedia) then
local iAlready = -1;
local bDebug = false;
for i = 0, buttonAdded-1, 1 do
if supportingPolicy[i] then
if (supportingPolicy[i].ID == policy.ID) then
for j = 0, iDebug-1, 1 do
if ( (debugTable[j].ID == policy.ID) and (debugTable[j].Yield == row.YieldType) ) then
bDebug = true;
break;
end
end
if (not bDebug) then
iAlready = i;
end
break;
end
end
end
if (not bDebug) then
if (iAlready ~= -1) then
local description = "";
if (row.Yield > 0) then
description = supportingPolicy[iAlready].Text .. ", +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString;
else
description = supportingPolicy[iAlready].Text .. ", [COLOR_NEGATIVE_TEXT]" .. tostring(row.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row.YieldType].IconString;
end
supportingPolicy[iAlready].Text = description;
debugTable[iDebug] = { ID=policy.ID, Yield=row.YieldType };
iDebug = iDebug + 1;
else
local thisPolicyInstance = g_SupportingPolicyManager:GetInstance();
if thisPolicyInstance then
local textureOffset, textureSheet = IconLookup( policy.PortraitIndex, buttonSize, policy.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
local description = "";
if (row.Yield > 0) then
description = Locale.ConvertTextKey( policy.Description ) .. ": +" .. tostring(row.Yield) .. GameInfo.Yields[row.YieldType].IconString;
else
description = Locale.ConvertTextKey( policy.Description ) .. ": [COLOR_NEGATIVE_TEXT]" .. tostring(row.Yield) .. "[ENDCOLOR]" .. GameInfo.Yields[row.YieldType].IconString;
end
supportingPolicy[buttonAdded] = { Num=buttonAdded, Image=thisPolicyInstance.SupportingPolicyImage, Button=thisPolicyInstance.SupportingPolicyButton, Icon=textureSheet, Offset=textureOffset, Category=CategoryPolicies, Text=description, ID=policy.ID};
debugTable[iDebug] = { ID=policy.ID, Yield=row.YieldType };
buttonAdded = buttonAdded + 1;
iDebug = iDebug + 1;
end
end
end
end
end
-- for culture
for row in GameInfo.Policy_ImprovementCultureChanges( condition ) do
local policy = GameInfo.Policies[row.PolicyType];
if (policy) and (policy.Civilopedia) then
local iAlready = -1;
local bDebug = false;
for i = 0, buttonAdded-1, 1 do
if supportingPolicy[i] then
if (supportingPolicy[i].ID == policy.ID) then
for j = 0, iDebug-1, 1 do
if ( (debugTable[j].ID == policy.ID) and (debugTable[j].Yield == YieldTypes.YIELD_CULTURE) ) then
bDebug = true;
break;
end
end
if (not bDebug) then
iAlready = i;
end
break;
end
end
end
if (not bDebug) then
if (iAlready ~= -1) then
local description = "";
if (row.CultureChange > 0) then
description = supportingPolicy[iAlready].Text .. ", +" .. tostring(row.CultureChange) .. GameInfo.Yields[YieldTypes.YIELD_CULTURE].IconString;
else
description = supportingPolicy[iAlready].Text .. ", [COLOR_NEGATIVE_TEXT]" .. tostring(row.CultureChange) .. "[ENDCOLOR]" .. GameInfo.Yields[YieldTypes.YIELD_CULTURE].IconString;
end
supportingPolicy[iAlready].Text = description;
debugTable[iDebug] = { ID=policy.ID, Yield=YieldTypes.YIELD_CULTURE };
iDebug = iDebug + 1;
else
local thisPolicyInstance = g_SupportingPolicyManager:GetInstance();
if thisPolicyInstance then
local textureOffset, textureSheet = IconLookup( policy.PortraitIndex, buttonSize, policy.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
local description = "";
-------BUG fix---------
if YieldTypes == nil then
return
end
-------BUG fix END---------
if (row.CultureChange > 0) then
description = Locale.ConvertTextKey( policy.Description ) .. ": +" .. tostring(row.CultureChange) .. GameInfo.Yields[YieldTypes.YIELD_CULTURE].IconString;
else
description = Locale.ConvertTextKey( policy.Description ) .. ": [COLOR_NEGATIVE_TEXT]" .. tostring(row.CultureChange) .. "[ENDCOLOR]" .. GameInfo.Yields[YieldTypes.YIELD_CULTURE].IconString;
end
supportingPolicy[buttonAdded] = { Num=buttonAdded, Image=thisPolicyInstance.SupportingPolicyImage, Button=thisPolicyInstance.SupportingPolicyButton, Icon=textureSheet, Offset=textureOffset, Category=CategoryPolicies, Text=description, ID=policy.ID};
debugTable[iDebug] = { ID=policy.ID, Yield=YieldTypes.YIELD_CULTURE };
buttonAdded = buttonAdded + 1;
iDebug = iDebug + 1;
end
end
end
end
end
if (buttonAdded ~= 0) then
for i = 0, buttonAdded-1, 1 do
UpdateSmallButtonWide( supportingPolicy[i].Num, supportingPolicy[i].Image, supportingPolicy[i].Button, supportingPolicy[i].Icon, supportingPolicy[i].Offset, supportingPolicy[i].Category, supportingPolicy[i].Text, supportingPolicy[i].ID );
end
end
UpdateWideButtonFrame( buttonAdded, Controls.SupportingPolicyInnerFrame, Controls.SupportingPolicyFrame );
-- update the related images
Controls.RelatedImagesFrame:SetHide( true );
end
--Roads and Railroads
elseif improvementID ~= -1 then
improvementID = improvementID - 1000;
local thisImprovement = GameInfo.Routes[improvementID];
if thisImprovement then
-- update the name
local name = Locale.ConvertTextKey( thisImprovement.Description )
Controls.ArticleID:SetText( name );
if IconHookup( thisImprovement.PortraitIndex, portraitSize, thisImprovement.IconAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
local buttonAdded = 0;
local condition = "RouteType = '" .. thisImprovement.Type .. "'";
-- tech visibility
g_PrereqTechManager:ResetInstances();
buttonAdded = 0;
local prereq = nil;
for row in GameInfo.Builds( condition ) do
if row.PrereqTech then
prereq = GameInfo.Technologies[row.PrereqTech];
end
end
if prereq then
local thisPrereqInstance = g_PrereqTechManager:GetInstance();
if thisPrereqInstance then
local textureOffset, textureSheet = IconLookup( prereq.PortraitIndex, buttonSize, prereq.IconAtlas );
if textureOffset == nil then
textureSheet = defaultErrorTextureSheet;
textureOffset = nullOffset;
end
UpdateSmallButton( buttonAdded, thisPrereqInstance.PrereqTechImage, thisPrereqInstance.PrereqTechButton, textureSheet, textureOffset, CategoryTech, Locale.ConvertTextKey( prereq.Description ), prereq.ID );
buttonAdded = buttonAdded + 1;
UpdateButtonFrame( buttonAdded, Controls.PrereqTechInnerFrame, Controls.PrereqTechFrame );
end
end
-- generic text
if (thisImprovement.Civilopedia) then
UpdateTextBlock( Locale.ConvertTextKey( thisImprovement.Civilopedia ), Controls.GameInfoLabel, Controls.GameInfoInnerFrame, Controls.GameInfoFrame );
end
-- update the related images
Controls.RelatedImagesFrame:SetHide( true );
end
end
ResizeEtc();
end
CivilopediaCategory[CategoryBeliefs].SelectArticle = function(entryID, shouldAddToList)
if selectedCategory ~= CategoryBeliefs then
SetSelectedCategory(CategoryBeliefs);
end
ClearArticle();
local offset = 0;
if(entryID[1] == "Beliefs") then
offset = #GameInfo.Religions;
end
offset = offset + entryID[2];
if shouldAddToList == addToList then
currentTopic = currentTopic + 1;
listOfTopicsViewed[currentTopic] = categorizedList[(CategoryBeliefs * absurdlyLargeNumTopicsInCategory) + offset];
for i = currentTopic + 1, endTopic, 1 do
listOfTopicsViewed[i] = nil;
end
endTopic = currentTopic;
end
if (entryID ~= nil) then
local t = entryID[1];
local id = entryID[2];
if(t == "Religions") then
local thisReligion = GameInfo[t][id];
if (thisReligion ~= nil) then
-- update the name
Controls.ArticleID:LocalizeAndSetText(thisReligion.Description);
-- update the summary
if (thisReligion.Civilopedia ~= nil) then
UpdateTextBlock( Locale.ConvertTextKey( thisReligion.Civilopedia ), Controls.SummaryLabel, Controls.SummaryInnerFrame, Controls.SummaryFrame );
end
end
else
local thisBelief = GameInfo[t][id];
if (thisBelief ~= nil) then
-- update the name
Controls.ArticleID:LocalizeAndSetText(thisBelief.ShortDescription);
-- update the summary
if (thisBelief.Description ~= nil) then
UpdateTextBlock( Locale.ConvertTextKey( thisBelief.Description ), Controls.SummaryLabel, Controls.SummaryInnerFrame, Controls.SummaryFrame );
end
end
end
end
ResizeEtc();
end
CivilopediaCategory[CategoryWorldCongress].SelectArticle = function(entryID, shouldAddToList)
if selectedCategory ~= CategoryWorldCongress then
SetSelectedCategory(CategoryWorldCongress);
end
ClearArticle();
local offset = 0;
offset = offset + entryID[2];
if shouldAddToList == addToList then
currentTopic = currentTopic + 1;
listOfTopicsViewed[currentTopic] = categorizedList[(CategoryWorldCongress * absurdlyLargeNumTopicsInCategory) + offset];
for i = currentTopic + 1, endTopic, 1 do
listOfTopicsViewed[i] = nil;
end
endTopic = currentTopic;
end
if (entryID ~= nil) then
local t = entryID[1];
local id = entryID[2];
if(t == "Resolutions") then
local thisResolution = GameInfo[t][id];
if (thisResolution ~= nil) then
Controls.Portrait:SetTexture("WorldCongressPortrait256_EXP2.dds");
Controls.Portrait:SetTextureOffsetVal(0,0);
Controls.PortraitFrame:SetHide(false);
-- update the name
Controls.ArticleID:LocalizeAndSetText(thisResolution.Description);
-- update the summary
if (thisResolution.Help ~= nil) then
UpdateTextBlock( Locale.ConvertTextKey( thisResolution.Help ), Controls.SummaryLabel, Controls.SummaryInnerFrame, Controls.SummaryFrame );
end
end
elseif(t == "LeagueProjects") then
local thisLeagueProject = GameInfo[t][id];
if (thisLeagueProject ~= nil) then
-- update the portrait
if IconHookup( thisLeagueProject.PortraitIndex, portraitSize, thisLeagueProject.IconAtlas, Controls.Portrait ) then
Controls.PortraitFrame:SetHide( false );
else
Controls.PortraitFrame:SetHide( true );
end
-- update the name
Controls.ArticleID:LocalizeAndSetText(thisLeagueProject.Description);
-- update the summary
local sSummary = GetLeagueProjectPediaText(id);
if (sSummary ~= nil and sSummary ~= "") then
UpdateTextBlock( sSummary , Controls.SummaryLabel, Controls.SummaryInnerFrame, Controls.SummaryFrame );
end
-- update the cost
local cost = thisLeagueProject.CostPerPlayer;
if(Game ~= nil and Game.GetNumActiveLeagues() > 0) then
local pLeague = Game.GetActiveLeague();
if (pLeague ~= nil) then
cost = pLeague:GetProjectCostPerPlayer(id) / 100;
end
end
if (cost > 0) then
Controls.CostFrame:SetHide( false );
Controls.CostLabel:SetText( Locale.ConvertTextKey("TXT_KEY_LEAGUE_PROJECT_COST_PER_PLAYER", cost));
end
end
end
end
ResizeEtc();
end
function GetLeagueProjectPediaText(iLeagueProjectID)
local s = "";
local TrophyIcons = {
"[ICON_TROPHY_BRONZE]",
"[ICON_TROPHY_SILVER]",
"[ICON_TROPHY_GOLD]",
};
local tProject = GameInfo.LeagueProjects[iLeagueProjectID];
if (tProject ~= nil) then
for i = 3, 1, -1 do
local reward = tProject["RewardTier" .. i];
if (reward ~= nil) then
local tReward = GameInfo.LeagueProjectRewards[reward];
if (tReward ~= nil) then
if (tReward.Description ~= nil and tReward.Help ~= nil) then
s = s .. Locale.Lookup("TXT_KEY_PEDIA_LEAGUE_PROJECT_REWARD", TrophyIcons[i], tReward.Description, tReward.Help);
end
end
end
if (i > 1) then
s = s .. "[NEWLINE][NEWLINE]";
end
end
end
return s;
end
---------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
function SortFunction( a, b )
local aVal = otherSortedList[ tostring( a ) ];
local bVal = otherSortedList[ tostring( b ) ];
if (aVal == nil) or (bVal == nil) then
--print("nil : "..tostring( a ).." = "..tostring(aVal).." : "..tostring( b ).." = "..tostring(bVal))
if aVal and (bVal == nil) then
return false;
elseif (aVal == nil) and bVal then
return true;
else
return tostring(a) < tostring(b); -- gotta do something deterministic
end;
else
return aVal < bVal;
end
end
---------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
CivilopediaCategory[CategoryHomePage].SelectHeading = function( selectedEraID, dummy )
print("CivilopediaCategory[CategoryHomePage].SelectHeading");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first era
--local thisListInstance = g_ListItemManager:GetInstance();
--if thisListInstance then
-- sortOrder = sortOrder + 1;
-- thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_HOME_PAGE_LABEL" ));
-- thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
-- thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryHomePage].buttonClicked );
-- thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
-- otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
--end
Controls.ListOfArticles:CalculateSize();
Controls.ScrollPanel:CalculateInternalSize();
end
CivilopediaCategory[CategoryGameConcepts].SelectHeading = function( selectedEraID, dummy )
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
sortedList[CategoryGameConcepts][selectedEraID].headingOpen = not sortedList[CategoryGameConcepts][selectedEraID].headingOpen; -- ain't lua great
--start working here on making the display not f up when closes
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first era
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_GAME_CONCEPT_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryGameConcepts].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
local numConcepts = #sortedList[CategoryGameConcepts];
for section = 1, numConcepts, 1 do
-- add a section header
local thisHeaderInstance = g_ListHeadingManager:GetInstance();
if thisHeaderInstance then
sortOrder = sortOrder + 1;
if sortedList[CategoryGameConcepts][section].headingOpen then
local textString = "TXT_KEY_GAME_CONCEPT_SECTION_"..tostring( section );
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
else
local textString = "TXT_KEY_GAME_CONCEPT_SECTION_"..tostring( section );
local localizedLabel = "[ICON_PLUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
end
thisHeaderInstance.ListHeadingButton:SetVoids( section, 0 );
thisHeaderInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryGameConcepts].SelectHeading );
otherSortedList[tostring( thisHeaderInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
if sortedList[CategoryGameConcepts][section].headingOpen then
for i, v in ipairs(sortedList[CategoryGameConcepts][section]) do
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryGameConcepts].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryTech].SelectHeading = function( selectedEraID, dummy )
print("CivilopediaCategory[CategoryTech].SelectHeading");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
sortedList[CategoryTech][selectedEraID].headingOpen = not sortedList[CategoryTech][selectedEraID].headingOpen; -- ain't lua great
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first era
local thisTechInstance = g_ListItemManager:GetInstance();
if thisTechInstance then
sortOrder = sortOrder + 1;
thisTechInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_TECH_PAGE_LABEL" ));
thisTechInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisTechInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryTech].buttonClicked );
thisTechInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisTechInstance.ListItemButton )] = sortOrder;
end
for era in GameInfo.Eras() do
local eraID = era.ID;
-- add an era header
local thisEraInstance = g_ListHeadingManager:GetInstance();
if thisEraInstance then
sortOrder = sortOrder + 1;
if sortedList[CategoryTech][eraID].headingOpen then
local textString = era.Description;
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisEraInstance.ListHeadingLabel:SetText( localizedLabel );
else
local textString = era.Description;
local localizedLabel = "[ICON_PLUS] "..Locale.ConvertTextKey( textString );
thisEraInstance.ListHeadingLabel:SetText( localizedLabel );
end
thisEraInstance.ListHeadingButton:SetVoids( eraID, 0 );
thisEraInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryTech].SelectHeading );
otherSortedList[tostring( thisEraInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
if sortedList[CategoryTech][eraID].headingOpen then
for i, v in ipairs(sortedList[CategoryTech][eraID]) do
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryTech].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryUnits].SelectHeading = function( selectedEraID, dummy )
print("CivilopediaCategory[CategoryUnits].SelectHeading");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
sortedList[CategoryUnits][selectedEraID].headingOpen = not sortedList[CategoryUnits][selectedEraID].headingOpen; -- ain't lua great
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first era
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_UNITS_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryUnits].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
function PopulateHeaderAndItems(categoryID, headingName)
local thisEraInstance = g_ListHeadingManager:GetInstance();
if thisEraInstance then
sortOrder = sortOrder + 1;
if sortedList[CategoryUnits][categoryID].headingOpen then
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( headingName );
thisEraInstance.ListHeadingLabel:SetText( localizedLabel );
else
local localizedLabel = "[ICON_PLUS] "..Locale.ConvertTextKey( headingName );
thisEraInstance.ListHeadingLabel:SetText( localizedLabel );
end
thisEraInstance.ListHeadingButton:SetVoids( categoryID, 0 );
thisEraInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryUnits].SelectHeading );
otherSortedList[tostring( thisEraInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
if sortedList[CategoryUnits][categoryID].headingOpen then
for i, v in ipairs(sortedList[CategoryUnits][categoryID]) do
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryUnits].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
end
local sectionID = 0;
if(Game == nil or not Game.IsOption(GameOptionTypes.GAMEOPTION_NO_RELIGION)) then
PopulateHeaderAndItems(sectionID, "TXT_KEY_PEDIA_RELIGIOUS");
sectionID = sectionID + 1;
end
for era in GameInfo.Eras() do
local eraID = era.ID;
local headingName = era.Description;
PopulateHeaderAndItems(sectionID, headingName);
sectionID = sectionID + 1;
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryPromotions].SelectHeading = function( selectedSection, dummy )
print("CivilopediaCategory[CategoryPromotions].SelectHeading");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
sortedList[CategoryPromotions][selectedSection].headingOpen = not sortedList[CategoryPromotions][selectedSection].headingOpen; -- ain't lua great
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first era
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_PROMOTIONS_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryPromotions].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
for section = 1, 8, 1 do
-- add a section header
local thisHeaderInstance = g_ListHeadingManager:GetInstance();
if thisHeaderInstance then
sortOrder = sortOrder + 1;
if sortedList[CategoryPromotions][section].headingOpen then
local textString = "TXT_KEY_PROMOTIONS_SECTION_"..tostring( section );
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
else
local textString = "TXT_KEY_PROMOTIONS_SECTION_"..tostring( section );
local localizedLabel = "[ICON_PLUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
end
thisHeaderInstance.ListHeadingButton:SetVoids( section, 0 );
thisHeaderInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryPromotions].SelectHeading );
otherSortedList[tostring( thisHeaderInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
if sortedList[CategoryPromotions][section].headingOpen then
for i, v in ipairs(sortedList[CategoryPromotions][section]) do
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryPromotions].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryBuildings].SelectHeading = function( selectedEraID, dummy )
print("CivilopediaCategory[CategoryBuildings].SelectHeading");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
sortedList[CategoryBuildings][selectedEraID].headingOpen = not sortedList[CategoryBuildings][selectedEraID].headingOpen; -- ain't lua great
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first era
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_BUILDINGS_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryBuildings].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
function PopulateAndAdd(categoryID, headingName)
-- add an era header
local thisEraInstance = g_ListHeadingManager:GetInstance();
if thisEraInstance then
sortOrder = sortOrder + 1;
if sortedList[CategoryBuildings][categoryID].headingOpen then
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey(headingName);
thisEraInstance.ListHeadingLabel:SetText( localizedLabel );
else
local localizedLabel = "[ICON_PLUS] "..Locale.ConvertTextKey(headingName);
thisEraInstance.ListHeadingLabel:SetText( localizedLabel );
end
thisEraInstance.ListHeadingButton:SetVoids( categoryID, 0 );
thisEraInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryBuildings].SelectHeading );
otherSortedList[tostring( thisEraInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
if sortedList[CategoryBuildings][categoryID].headingOpen then
for i, v in ipairs(sortedList[CategoryBuildings][categoryID]) do
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryBuildings].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
end
local sectionID = 0;
if(Game == nil or not Game.IsOption(GameOptionTypes.GAMEOPTION_NO_RELIGION)) then
PopulateAndAdd(sectionID, "TXT_KEY_PEDIA_RELIGIOUS");
sectionID = sectionID + 1;
end
for era in GameInfo.Eras() do
local eraID = era.ID;
local headingName = era.Description;
PopulateAndAdd(sectionID, headingName);
sectionID = sectionID + 1;
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryWonders].SelectHeading = function( selectedSectionID, dummy )
print("CivilopediaCategory[CategoryWonders].SelectHeading");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
sortedList[CategoryWonders][selectedSectionID].headingOpen = not sortedList[CategoryWonders][selectedSectionID].headingOpen; -- ain't lua great
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first section
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_WONDERS_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryWonders].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
for section = 1, 3, 1 do
-- add a section header
local thisHeaderInstance = g_ListHeadingManager:GetInstance();
if thisHeaderInstance then
sortOrder = sortOrder + 1;
if sortedList[CategoryWonders][section].headingOpen then
local textString = "TXT_KEY_WONDER_SECTION_"..tostring( section );
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
else
local textString = "TXT_KEY_WONDER_SECTION_"..tostring( section );
local localizedLabel = "[ICON_PLUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
end
thisHeaderInstance.ListHeadingButton:SetVoids( section, 0 );
thisHeaderInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryWonders].SelectHeading );
otherSortedList[tostring( thisHeaderInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
if sortedList[CategoryWonders][section].headingOpen then
for i, v in ipairs(sortedList[CategoryWonders][section]) do
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryWonders].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryPolicies].SelectHeading = function( selectedBranchID, dummy )
print("CivilopediaCategory[CategoryPolicies].SelectHeading");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
sortedList[CategoryPolicies][selectedBranchID].headingOpen = not sortedList[CategoryPolicies][selectedBranchID].headingOpen; -- ain't lua great
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first branch
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_POLICIES_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryPolicies].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
for branch in GameInfo.PolicyBranchTypes() do
local branchID = branch.ID;
-- add a branch header
local thisHeadingInstance = g_ListHeadingManager:GetInstance();
if thisHeadingInstance then
sortOrder = sortOrder + 1;
if sortedList[CategoryPolicies][branchID].headingOpen then
local textString = branch.Description;
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeadingInstance.ListHeadingLabel:SetText( localizedLabel );
else
local textString = branch.Description;
local localizedLabel = "[ICON_PLUS] "..Locale.ConvertTextKey( textString );
thisHeadingInstance.ListHeadingLabel:SetText( localizedLabel );
end
thisHeadingInstance.ListHeadingButton:SetVoids( branchID, 0 );
thisHeadingInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryPolicies].SelectHeading );
otherSortedList[tostring( thisHeadingInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
if sortedList[CategoryPolicies][branchID].headingOpen then
for i, v in ipairs(sortedList[CategoryPolicies][branchID]) do
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryPolicies].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryPeople].SelectHeading = function( selectedSectionID, dummy )
print("CivilopediaCategory[CategoryPeople].SelectHeading");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
sortedList[CategoryPeople][selectedSectionID].headingOpen = not sortedList[CategoryPeople][selectedSectionID].headingOpen; -- ain't lua great
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first section
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_PEOPLE_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryPeople].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
for section = 1, 2, 1 do
-- add a section header
local thisHeaderInstance = g_ListHeadingManager:GetInstance();
if thisHeaderInstance then
sortOrder = sortOrder + 1;
if sortedList[CategoryPeople][section].headingOpen then
local textString = "TXT_KEY_PEOPLE_SECTION_"..tostring( section );
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
else
local textString = "TXT_KEY_PEOPLE_SECTION_"..tostring( section );
local localizedLabel = "[ICON_PLUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
end
thisHeaderInstance.ListHeadingButton:SetVoids( section, 0 );
thisHeaderInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryPeople].SelectHeading );
otherSortedList[tostring( thisHeaderInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
if sortedList[CategoryPeople][section].headingOpen then
for i, v in ipairs(sortedList[CategoryPeople][section]) do
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryPeople].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryCivilizations].SelectHeading = function( selectedSectionID, dummy )
print("CivilopediaCategory[CategoryCivilizations].SelectHeading");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
sortedList[CategoryCivilizations][selectedSectionID].headingOpen = not sortedList[CategoryCivilizations][selectedSectionID].headingOpen; -- ain't lua great
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first section
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_CIVILIZATIONS_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryCivilizations].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
for section = 1, 2, 1 do
-- add a section header
local thisHeaderInstance = g_ListHeadingManager:GetInstance();
if thisHeaderInstance then
sortOrder = sortOrder + 1;
if sortedList[CategoryCivilizations][section].headingOpen then
local textString = "TXT_KEY_CIVILIZATION_SECTION_"..tostring( section );
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
else
local textString = "TXT_KEY_CIVILIZATION_SECTION_"..tostring( section );
local localizedLabel = "[ICON_PLUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
end
thisHeaderInstance.ListHeadingButton:SetVoids( section, 0 );
thisHeaderInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryCivilizations].SelectHeading );
otherSortedList[tostring( thisHeaderInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
if sortedList[CategoryCivilizations][section].headingOpen then
for i, v in ipairs(sortedList[CategoryCivilizations][section]) do
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryCivilizations].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryCityStates].SelectHeading = function( selectedSectionID, dummy )
print("CivilopediaCategory[CategoryCityStates].SelectHeading");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
sortedList[CategoryCityStates][selectedSectionID].headingOpen = not sortedList[CategoryCityStates][selectedSectionID].headingOpen; -- ain't lua great
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first section
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_CITY_STATES_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryCityStates].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
-- for each trait
for trait in GameInfo.MinorCivTraits() do
local traitID = trait.ID;
local thisHeadingInstance = g_ListHeadingManager:GetInstance();
if thisHeadingInstance then
sortOrder = sortOrder + 1;
if sortedList[CategoryCityStates][traitID].headingOpen then
local textString = trait.Description;
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeadingInstance.ListHeadingLabel:SetText( localizedLabel );
else
local textString = trait.Description;
local localizedLabel = "[ICON_PLUS] "..Locale.ConvertTextKey( textString );
thisHeadingInstance.ListHeadingLabel:SetText( localizedLabel );
end
thisHeadingInstance.ListHeadingButton:SetVoids( traitID, 0 );
thisHeadingInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryCityStates].SelectHeading );
otherSortedList[tostring( thisHeadingInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
if sortedList[CategoryCityStates][traitID].headingOpen then
for i, v in ipairs(sortedList[CategoryCityStates][traitID]) do
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryCityStates].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryTerrain].SelectHeading = function( selectedSectionID, dummy )
print("CivilopediaCategory[CategoryTerrain].SelectHeading");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
sortedList[CategoryTerrain][selectedSectionID].headingOpen = not sortedList[CategoryTerrain][selectedSectionID].headingOpen; -- ain't lua great
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first section
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_TERRAIN_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryTerrain].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
for section = 1, 2, 1 do
-- add a section header
local thisHeaderInstance = g_ListHeadingManager:GetInstance();
if thisHeaderInstance then
sortOrder = sortOrder + 1;
if sortedList[CategoryTerrain][section].headingOpen then
local textString = "TXT_KEY_TERRAIN_SECTION_"..tostring( section );
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
else
local textString = "TXT_KEY_TERRAIN_SECTION_"..tostring( section );
local localizedLabel = "[ICON_PLUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
end
thisHeaderInstance.ListHeadingButton:SetVoids( section, 0 );
thisHeaderInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryTerrain].SelectHeading );
otherSortedList[tostring( thisHeaderInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
if sortedList[CategoryTerrain][section].headingOpen then
for i, v in ipairs(sortedList[CategoryTerrain][section]) do
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryTerrain].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryResources].SelectHeading = function( selectedSectionID, dummy )
print("CivilopediaCategory[CategoryResources].SelectHeading");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
sortedList[CategoryResources][selectedSectionID].headingOpen = not sortedList[CategoryResources][selectedSectionID].headingOpen; -- ain't lua great
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first section
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_RESOURCES_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryResources].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
for section = 0, 2, 1 do
-- add a section header
local thisHeaderInstance = g_ListHeadingManager:GetInstance();
if thisHeaderInstance then
sortOrder = sortOrder + 1;
if sortedList[CategoryResources][section].headingOpen then
local textString = "TXT_KEY_RESOURCES_SECTION_"..tostring( section );
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
else
local textString = "TXT_KEY_RESOURCES_SECTION_"..tostring( section );
local localizedLabel = "[ICON_PLUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
end
thisHeaderInstance.ListHeadingButton:SetVoids( section, 0 );
thisHeaderInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryResources].SelectHeading );
otherSortedList[tostring( thisHeaderInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
if sortedList[CategoryResources][section].headingOpen then
for i, v in ipairs(sortedList[CategoryResources][section]) do
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryResources].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryImprovements].SelectHeading = function( selectedSection, dummy )
print("CivilopediaCategory[CategoryImprovements].SelectHeading");
-- todo: implement if there are ever sections in the Improvements page
print("I should never get here");
ResizeEtc();
end
CivilopediaCategory[CategoryBeliefs].SelectHeading = function( selectedSectionID, dummy )
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
sortedList[CategoryBeliefs][selectedSectionID].headingOpen = not sortedList[CategoryBeliefs][selectedSectionID].headingOpen; -- ain't lua great
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first section
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_BELIEFS_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryBeliefs].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
for section = 1, 6, 1 do
-- add a section header
local thisHeaderInstance = g_ListHeadingManager:GetInstance();
if thisHeaderInstance then
sortOrder = sortOrder + 1;
if sortedList[CategoryBeliefs][section].headingOpen then
local textString = "TXT_KEY_PEDIA_BELIEFS_CATEGORY_"..tostring( section );
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
else
local textString = "TXT_KEY_PEDIA_BELIEFS_CATEGORY_"..tostring( section );
local localizedLabel = "[ICON_PLUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
end
thisHeaderInstance.ListHeadingButton:SetVoids( section, 0 );
thisHeaderInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryBeliefs].SelectHeading );
otherSortedList[tostring( thisHeaderInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
if sortedList[CategoryBeliefs][section].headingOpen then
for i, v in ipairs(sortedList[CategoryBeliefs][section]) do
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids(0, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, function(dummy, shouldAddToList) CivilopediaCategory[CategoryBeliefs].SelectArticle(v.entryID, shouldAddToList); end);
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryWorldCongress].SelectHeading = function( selectedSectionID, dummy )
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
sortedList[CategoryWorldCongress][selectedSectionID].headingOpen = not sortedList[CategoryWorldCongress][selectedSectionID].headingOpen; -- ain't lua great
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first section
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_WORLD_CONGRESS_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryWorldCongress].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
for section = 1, 2, 1 do
-- add a section header
local thisHeaderInstance = g_ListHeadingManager:GetInstance();
if thisHeaderInstance then
sortOrder = sortOrder + 1;
if sortedList[CategoryWorldCongress][section].headingOpen then
local textString = "TXT_KEY_PEDIA_WORLD_CONGRESS_CATEGORY_"..tostring( section );
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
else
local textString = "TXT_KEY_PEDIA_WORLD_CONGRESS_CATEGORY_"..tostring( section );
local localizedLabel = "[ICON_PLUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
end
thisHeaderInstance.ListHeadingButton:SetVoids( section, 0 );
thisHeaderInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryWorldCongress].SelectHeading );
otherSortedList[tostring( thisHeaderInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
if sortedList[CategoryWorldCongress][section].headingOpen then
for i, v in ipairs(sortedList[CategoryWorldCongress][section]) do
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids(0, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, function(dummy, shouldAddToList) CivilopediaCategory[CategoryWorldCongress].SelectArticle(v.entryID, shouldAddToList); end);
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
----------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------
CivilopediaCategory[CategoryHomePage].DisplayList = function( selectedSection, dummy )
print("CivilopediaCategory[CategoryHomePage].DisplayList");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the rest of the stuff
--local thisListInstance = g_ListItemManager:GetInstance();
--if thisListInstance then
-- sortOrder = sortOrder + 1;
-- thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_HOME_PAGE_LABEL" ));
-- thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
-- thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryHomePage].buttonClicked );
-- thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
-- otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
--end
-- for each element of the sorted list
for i, v in ipairs(sortedList[CategoryHomePage][1]) do
-- add an entry
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryHomePage].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryGameConcepts].DisplayList = function( selectedSection, dummy )
print("CivilopediaCategory[CategoryGameConcepts].DisplayList");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the rest of the stuff
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_GAME_CONCEPT_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryGameConcepts].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
-- for each element of the sorted list
local numSections = #sortedList[CategoryGameConcepts];
local GameConceptsList = sortedList[CategoryGameConcepts];
for section = 1,numSections,1 do
local headingOpen = GameConceptsList[section].headingOpen;
if(headingOpen == nil) then
headingOpen = true;
GameConceptsList[section].headingOpen = true;
end
local thisHeaderInstance = g_ListHeadingManager:GetInstance();
if thisHeaderInstance then
sortOrder = sortOrder + 1;
local textString = "TXT_KEY_GAME_CONCEPT_SECTION_"..tostring( section );
thisHeaderInstance.ListHeadingButton:SetVoids( section, 0 );
thisHeaderInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryGameConcepts].SelectHeading );
otherSortedList[tostring( thisHeaderInstance.ListHeadingButton )] = sortOrder;
if(headingOpen == true) then
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
else
local localizedLabel = "[ICON_PLUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
end
end
if(headingOpen == true) then
for i, v in ipairs(sortedList[CategoryGameConcepts][section]) do
-- add an entry
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryGameConcepts].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
Controls.ScrollPanel:CalculateInternalSize();
end
CivilopediaCategory[CategoryTech].DisplayList = function()
print("CivilopediaCategory[CategoryTech].DisplayList");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first era
local thisTechInstance = g_ListItemManager:GetInstance();
if thisTechInstance then
sortOrder = sortOrder + 1;
thisTechInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_TECH_PAGE_LABEL" ));
thisTechInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisTechInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryTech].buttonClicked );
thisTechInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisTechInstance.ListItemButton )] = sortOrder;
end
for era in GameInfo.Eras() do
local eraID = era.ID;
-- add an era header
local thisEraInstance = g_ListHeadingManager:GetInstance();
if thisEraInstance then
sortedList[CategoryTech][eraID].headingOpen = true; -- ain't lua great
sortOrder = sortOrder + 1;
local textString = era.Description;
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisEraInstance.ListHeadingLabel:SetText( localizedLabel );
thisEraInstance.ListHeadingButton:SetVoids( eraID, 0 );
thisEraInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryTech].SelectHeading );
otherSortedList[tostring( thisEraInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
for i, v in ipairs(sortedList[CategoryTech][eraID]) do
-- add a tech entry
local thisTechInstance = g_ListItemManager:GetInstance();
if thisTechInstance then
sortOrder = sortOrder + 1;
thisTechInstance.ListItemLabel:SetText( v.entryName );
thisTechInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisTechInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryTech].SelectArticle );
thisTechInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisTechInstance.ListItemButton )] = sortOrder;
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryUnits].DisplayList = function()
print("CivilopediaCategory[CategoryUnits].DisplayList");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first era
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_UNITS_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryUnits].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
function PopulateAndAdd(categoryID, headingName)
-- add an era header
local thisEraInstance = g_ListHeadingManager:GetInstance();
if thisEraInstance then
sortedList[CategoryUnits][categoryID].headingOpen = true; -- ain't lua great
sortOrder = sortOrder + 1;
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey(headingName);
thisEraInstance.ListHeadingLabel:SetText( localizedLabel );
thisEraInstance.ListHeadingButton:SetVoids( categoryID, 0 );
thisEraInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryUnits].SelectHeading );
otherSortedList[tostring( thisEraInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
for i, v in ipairs(sortedList[CategoryUnits][categoryID]) do
-- add a unit entry
local thisUnitInstance = g_ListItemManager:GetInstance();
if thisUnitInstance then
sortOrder = sortOrder + 1;
thisUnitInstance.ListItemLabel:SetText( v.entryName );
thisUnitInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisUnitInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryUnits].SelectArticle );
thisUnitInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisUnitInstance.ListItemButton )] = sortOrder;
end
end
end
local sectionID = 0;
if(Game == nil or not Game.IsOption(GameOptionTypes.GAMEOPTION_NO_RELIGION)) then
PopulateAndAdd(0, "TXT_KEY_PEDIA_RELIGIOUS");
sectionID = sectionID + 1;
end
for era in GameInfo.Eras() do
local eraID = era.ID;
local headingName = era.Description;
PopulateAndAdd(eraID + sectionID, headingName);
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryPromotions].DisplayList = function()
print("start CivilopediaCategory[CategoryPromotions].DisplayList");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the rest of the stuff
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_PROMOTIONS_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryPromotions].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
-- for each element of the sorted list
for section = 1,8,1 do
local thisHeaderInstance = g_ListHeadingManager:GetInstance();
if thisHeaderInstance then
sortedList[CategoryPromotions][section].headingOpen = true; -- ain't lua great
sortOrder = sortOrder + 1;
local textString = "TXT_KEY_PROMOTIONS_SECTION_"..tostring( section );
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
thisHeaderInstance.ListHeadingButton:SetVoids( section, 0 );
thisHeaderInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryPromotions].SelectHeading );
otherSortedList[tostring( thisHeaderInstance.ListHeadingButton )] = sortOrder;
end
for i, v in ipairs(sortedList[CategoryPromotions][section]) do
-- add an entry
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryPromotions].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
Controls.ScrollPanel:CalculateInternalSize();
end
CivilopediaCategory[CategoryBuildings].DisplayList = function()
print("CivilopediaCategory[CategoryBuildings].DisplayList");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first era
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_BUILDINGS_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryBuildings].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
function PopulateAndAdd(categoryID, headingName)
local thisEraInstance = g_ListHeadingManager:GetInstance();
if thisEraInstance then
sortedList[CategoryBuildings][categoryID].headingOpen = true; -- ain't lua great
sortOrder = sortOrder + 1;
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey(headingName);
thisEraInstance.ListHeadingLabel:SetText( localizedLabel );
thisEraInstance.ListHeadingButton:SetVoids( categoryID, 0 );
thisEraInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryBuildings].SelectHeading );
otherSortedList[tostring( thisEraInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
for i, v in ipairs(sortedList[CategoryBuildings][categoryID]) do
-- add an entry
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryBuildings].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
local sectionID = 0;
if(Game == nil or not Game.IsOption(GameOptionTypes.GAMEOPTION_NO_RELIGION)) then
PopulateAndAdd(0, "TXT_KEY_PEDIA_RELIGIOUS");
sectionID = sectionID + 1;
end
for era in GameInfo.Eras() do
local eraID = era.ID;
local headingName = era.Description;
PopulateAndAdd(eraID + sectionID, headingName);
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryWonders].DisplayList = function()
print("CivilopediaCategory[CategoryWonders].DisplayList");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first section
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_WONDERS_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryWonders].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
for section = 1, 3, 1 do
local thisHeaderInstance = g_ListHeadingManager:GetInstance();
if thisHeaderInstance then
sortedList[CategoryWonders][section].headingOpen = true; -- ain't lua great
sortOrder = sortOrder + 1;
local textString = "TXT_KEY_WONDER_SECTION_"..tostring( section );
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
thisHeaderInstance.ListHeadingButton:SetVoids( section, 0 );
thisHeaderInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryWonders].SelectHeading );
otherSortedList[tostring( thisHeaderInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
for i, v in ipairs(sortedList[CategoryWonders][section]) do
-- add a unit entry
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryWonders].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
Controls.ScrollPanel:CalculateInternalSize();
end
CivilopediaCategory[CategoryPolicies].DisplayList = function()
print("CivilopediaCategory[CategoryPolicies].DisplayList");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first branch
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_POLICIES_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryPolicies].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
for branch in GameInfo.PolicyBranchTypes() do
local branchID = branch.ID;
-- add a branch header
local thisHeadingInstance = g_ListHeadingManager:GetInstance();
if thisHeadingInstance then
sortedList[CategoryPolicies][branchID].headingOpen = true; -- ain't lua great
sortOrder = sortOrder + 1;
local textString = branch.Description;
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeadingInstance.ListHeadingLabel:SetText( localizedLabel );
thisHeadingInstance.ListHeadingButton:SetVoids( branchID, 0 );
thisHeadingInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryPolicies].SelectHeading );
otherSortedList[tostring( thisHeadingInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
for i, v in ipairs(sortedList[CategoryPolicies][branchID]) do
-- add an entry
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryPolicies].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryPeople].DisplayList = function()
print("CivilopediaCategory[CategoryPeople].DisplayList");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first section
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_PEOPLE_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryPeople].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
for section = 1, 2, 1 do
local thisHeaderInstance = g_ListHeadingManager:GetInstance();
if thisHeaderInstance then
sortedList[CategoryPeople][section].headingOpen = true; -- ain't lua great
sortOrder = sortOrder + 1;
local textString = "TXT_KEY_PEOPLE_SECTION_"..tostring( section );
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
thisHeaderInstance.ListHeadingButton:SetVoids( section, 0 );
thisHeaderInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryPeople].SelectHeading );
otherSortedList[tostring( thisHeaderInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
for i, v in ipairs(sortedList[CategoryPeople][section]) do
-- add a unit entry
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryPeople].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryCivilizations].DisplayList = function()
print("CivilopediaCategory[CategoryCivilizations].DisplayList");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first section
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_CIVILIZATIONS_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryCivilizations].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
for section = 1, 2, 1 do
local thisHeaderInstance = g_ListHeadingManager:GetInstance();
if thisHeaderInstance then
sortedList[CategoryCivilizations][section].headingOpen = true; -- ain't lua great
sortOrder = sortOrder + 1;
local textString = "TXT_KEY_CIVILIZATIONS_SECTION_"..tostring( section );
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
thisHeaderInstance.ListHeadingButton:SetVoids( section, 0 );
thisHeaderInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryCivilizations].SelectHeading );
otherSortedList[tostring( thisHeaderInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
for i, v in ipairs(sortedList[CategoryCivilizations][section]) do
-- add a unit entry
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryCivilizations].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryCityStates].DisplayList = function()
print("CivilopediaCategory[CategoryCityStates].DisplayList");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first trait
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_CITY_STATES_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryCityStates].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
for trait in GameInfo.MinorCivTraits() do
local traitID = trait.ID;
-- add a header
local thisHeadingInstance = g_ListHeadingManager:GetInstance();
if thisHeadingInstance then
sortedList[CategoryCityStates][traitID].headingOpen = true; -- ain't lua great
sortOrder = sortOrder + 1;
local textString = trait.Description;
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeadingInstance.ListHeadingLabel:SetText( localizedLabel );
thisHeadingInstance.ListHeadingButton:SetVoids( traitID, 0 );
thisHeadingInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryCityStates].SelectHeading );
otherSortedList[tostring( thisHeadingInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
for i, v in ipairs(sortedList[CategoryCityStates][traitID]) do
-- add an entry
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryCityStates].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryTerrain].DisplayList = function()
print("CivilopediaCategory[CategoryTerrain].DisplayList");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first section
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_TERRAIN_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryTerrain].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
for section = 1, 2, 1 do
local thisHeaderInstance = g_ListHeadingManager:GetInstance();
if thisHeaderInstance then
sortedList[CategoryTerrain][section].headingOpen = true; -- ain't lua great
sortOrder = sortOrder + 1;
local textString = "TXT_KEY_TERRAIN_SECTION_"..tostring( section );
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
thisHeaderInstance.ListHeadingButton:SetVoids( section, 0 );
thisHeaderInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryTerrain].SelectHeading );
otherSortedList[tostring( thisHeaderInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
for i, v in ipairs(sortedList[CategoryTerrain][section]) do
-- add a unit entry
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryTerrain].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryResources].DisplayList = function()
print("CivilopediaCategory[CategoryResources].DisplayList");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first section
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_RESOURCES_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryResources].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
for section = 0, 2, 1 do
local thisHeaderInstance = g_ListHeadingManager:GetInstance();
if thisHeaderInstance then
sortedList[CategoryResources][section].headingOpen = true; -- ain't lua great
sortOrder = sortOrder + 1;
local textString = "TXT_KEY_RESOURCES_SECTION_"..tostring( section );
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
thisHeaderInstance.ListHeadingButton:SetVoids( section, 0 );
thisHeaderInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryResources].SelectHeading );
otherSortedList[tostring( thisHeaderInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
for i, v in ipairs(sortedList[CategoryResources][section]) do
-- add a unit entry
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryResources].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryImprovements].DisplayList = function()
print("start CivilopediaCategory[CategoryImprovements].DisplayList");
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the rest of the stuff
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_IMPROVEMENTS_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryImprovements].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
-- for each element of the sorted list
for i, v in ipairs(sortedList[CategoryImprovements][1]) do
-- add an entry
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryImprovements].SelectArticle );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryBeliefs].DisplayList = function()
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first section
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_BELIEFS_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryBeliefs].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
for section = 1, 6, 1 do
local thisHeaderInstance = g_ListHeadingManager:GetInstance();
if thisHeaderInstance then
sortedList[CategoryBeliefs][section].headingOpen = true; -- ain't lua great
sortOrder = sortOrder + 1;
local textString = "TXT_KEY_PEDIA_BELIEFS_CATEGORY_"..tostring( section );
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
thisHeaderInstance.ListHeadingButton:SetVoids( section, 0 );
thisHeaderInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryBeliefs].SelectHeading );
otherSortedList[tostring( thisHeaderInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
for i, v in ipairs(sortedList[CategoryBeliefs][section]) do
-- add a unit entry
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID[2], addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, function(dummy, shouldAddToList) CivilopediaCategory[CategoryBeliefs].SelectArticle(v.entryID, shouldAddToList); end);
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
CivilopediaCategory[CategoryWorldCongress].DisplayList = function()
g_ListHeadingManager:ResetInstances();
g_ListItemManager:ResetInstances();
local sortOrder = 0;
otherSortedList = {};
-- put in a home page before the first section
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( Locale.ConvertTextKey( "TXT_KEY_PEDIA_WORLD_CONGRESS_PAGE_LABEL" ));
thisListInstance.ListItemButton:SetVoids( homePageOfCategoryID, addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryWorldCongress].buttonClicked );
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler );
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
for section = 1, 2, 1 do
local thisHeaderInstance = g_ListHeadingManager:GetInstance();
if thisHeaderInstance then
sortedList[CategoryWorldCongress][section].headingOpen = true; -- ain't lua great
sortOrder = sortOrder + 1;
local textString = "TXT_KEY_PEDIA_WORLD_CONGRESS_CATEGORY_"..tostring( section );
local localizedLabel = "[ICON_MINUS] "..Locale.ConvertTextKey( textString );
thisHeaderInstance.ListHeadingLabel:SetText( localizedLabel );
thisHeaderInstance.ListHeadingButton:SetVoids( section, 0 );
thisHeaderInstance.ListHeadingButton:RegisterCallback( Mouse.eLClick, CivilopediaCategory[CategoryWorldCongress].SelectHeading );
otherSortedList[tostring( thisHeaderInstance.ListHeadingButton )] = sortOrder;
end
-- for each element of the sorted list
for i, v in ipairs(sortedList[CategoryWorldCongress][section]) do
-- add a unit entry
local thisListInstance = g_ListItemManager:GetInstance();
if thisListInstance then
sortOrder = sortOrder + 1;
thisListInstance.ListItemLabel:SetText( v.entryName );
thisListInstance.ListItemButton:SetVoids( v.entryID[2], addToList );
thisListInstance.ListItemButton:RegisterCallback( Mouse.eLClick, function(dummy, shouldAddToList) CivilopediaCategory[CategoryWorldCongress].SelectArticle(v.entryID, shouldAddToList); end);
thisListInstance.ListItemButton:SetToolTipCallback( TipHandler )
otherSortedList[tostring( thisListInstance.ListItemButton )] = sortOrder;
end
end
end
Controls.ListOfArticles:SortChildren( SortFunction );
ResizeEtc();
end
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
function ClearArticle()
Controls.ScrollPanel:SetScrollValue( 0 );
Controls.PortraitFrame:SetHide( true );
Controls.CostFrame:SetHide( true );
Controls.MaintenanceFrame:SetHide( true );
Controls.HappinessFrame:SetHide( true );
Controls.UnmoddedHappinessFrame:SetHide( true );
Controls.CultureFrame:SetHide( true );
Controls.FaithFrame:SetHide( true );
Controls.DefenseFrame:SetHide( true );
Controls.FoodFrame:SetHide( true );
Controls.GoldChangeFrame:SetHide( true );
Controls.GoldFrame:SetHide( true );
Controls.ScienceFrame:SetHide( true );
Controls.ProductionFrame:SetHide( true );
Controls.GreatPeopleFrame:SetHide( true );
Controls.CombatFrame:SetHide( true );
Controls.RangedCombatFrame:SetHide( true );
Controls.RangedCombatRangeFrame:SetHide( true );
Controls.MovementFrame:SetHide( true );
Controls.FreePromotionsFrame:SetHide( true );
Controls.PrereqTechFrame:SetHide( true );
Controls.GreatWorksFrame:SetHide( true );
Controls.LeadsToTechFrame:SetHide( true );
Controls.ObsoleteTechFrame:SetHide( true );
Controls.UpgradeFrame:SetHide( true );
Controls.UnlockedUnitsFrame:SetHide( true );
Controls.UnlockedBuildingsFrame:SetHide( true );
Controls.RequiredBuildingsFrame:SetHide( true );
Controls.RevealedResourcesFrame:SetHide( true );
Controls.RequiredResourcesFrame:SetHide( true );
Controls.RequiredPromotionsFrame:SetHide( true );
Controls.LocalResourcesFrame:SetHide( true );
Controls.WorkerActionsFrame:SetHide( true );
Controls.UnlockedProjectsFrame:SetHide( true );
Controls.SpecialistsFrame:SetHide( true );
Controls.RelatedArticlesFrame:SetHide( true );
Controls.GameInfoFrame:SetHide( true );
Controls.QuoteFrame:SetHide( true );
Controls.SilentQuoteFrame:SetHide( true );
Controls.AbilitiesFrame:SetHide( true );
Controls.HistoryFrame:SetHide( true );
Controls.StrategyFrame:SetHide( true );
Controls.RelatedImagesFrame:SetHide( true );
Controls.SummaryFrame:SetHide( true );
Controls.ExtendedFrame:SetHide( true );
Controls.DNotesFrame:SetHide( true );
Controls.RequiredPoliciesFrame:SetHide( true );
Controls.PrereqEraFrame:SetHide( true );
Controls.PolicyBranchFrame:SetHide( true );
Controls.TenetLevelFrame:SetHide(true);
Controls.LeadersFrame:SetHide( true );
Controls.UniqueUnitsFrame:SetHide( true );
Controls.UniqueBuildingsFrame:SetHide( true );
Controls.UniqueImprovementsFrame:SetHide( true );
Controls.CivilizationsFrame:SetHide ( true );
Controls.TraitsFrame:SetHide( true );
Controls.LivedFrame:SetHide( true );
Controls.TitlesFrame:SetHide( true );
Controls.SubtitleID:SetHide( true );
Controls.YieldFrame:SetHide( true );
Controls.MountainYieldFrame:SetHide( true );
Controls.MovementCostFrame:SetHide( true );
Controls.CombatModFrame:SetHide( true );
Controls.FeaturesFrame:SetHide( true );
Controls.ResourcesFoundFrame:SetHide( true );
Controls.TerrainsFrame:SetHide( true );
Controls.CombatTypeFrame:SetHide( true );
Controls.ReplacesFrame:SetHide( true );
Controls.RevealTechsFrame:SetHide( true );
Controls.ImprovementsFrame:SetHide( true );
Controls.HomePageBlurbFrame:SetHide( true );
Controls.WideTextBlockFrame:SetHide( true );
-- MOD - Advanced Civilopedia
Controls.UnitFlagAtlasFrame:SetHide( true );
Controls.PrereqProjectFrame:SetHide( true );
Controls.CivLeaderInfoTextStack:SetHide( true );
Controls.ObsoleteUnitFrame:SetHide( true );
Controls.ObsoleteBuildingFrame:SetHide( true );
Controls.UnlockedPromotionsFrame:SetHide( true );
Controls.MaxInstancesFrame:SetHide( true );
Controls.ReplacedByFrame:SetHide( true );
Controls.ResourcesProvidedFrame:SetHide( true );
Controls.SupportingTechFrame:SetHide( true );
Controls.SupportingBuildingFrame:SetHide( true );
Controls.SupportingPolicyFrame:SetHide( true );
Controls.ConstructionRestrictionsFrame:SetHide( true );
Controls.FFTextStack:SetHide( true );
Controls.BBTextStack:SetHide ( true );
Controls.PartialMatchPullDown:SetHide( true );
Controls.SearchButton:SetHide( false );
Controls.Portrait:UnloadTexture();
Controls.Portrait:SetTexture("256x256Frame.dds");
end
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
function OnClose()
Controls.Portrait:UnloadTexture();
UIManager:DequeuePopup( ContextPtr );
end
Controls.CloseButton:RegisterCallback( Mouse.eLClick, OnClose );
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
function OnBackButtonClicked()
if currentTopic > 1 then
currentTopic = currentTopic - 1;
local article = listOfTopicsViewed[currentTopic];
if article then
SetSelectedCategory( article.entryCategory );
CivilopediaCategory[article.entryCategory].SelectArticle( article.entryID, dontAddToList );
end
end
end
Controls.BackButton:RegisterCallback( Mouse.eLClick, OnBackButtonClicked );
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
function OnForwardButtonClicked()
if currentTopic < endTopic then
currentTopic = currentTopic + 1;
local article = listOfTopicsViewed[currentTopic];
if article then
SetSelectedCategory( article.entryCategory );
CivilopediaCategory[article.entryCategory].SelectArticle( article.entryID, dontAddToList );
end
end
end
Controls.ForwardButton:RegisterCallback( Mouse.eLClick, OnForwardButtonClicked );
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
function SearchForPediaEntry( searchString )
UIManager:SetUICursor( 1 );
if( searchString ~= nil and searchString ~= "" ) then
local article = searchableTextKeyList[searchString];
if article == nil then
article = searchableList[Locale.ToLower(searchString)];
end
if article then
SetSelectedCategory( article.entryCategory );
CivilopediaCategory[article.entryCategory].SelectArticle( article.entryID, addToList );
else
SetSelectedCategory( CategoryGameConcepts );
end
end
if( searchString == "OPEN_VIA_HOTKEY" ) then
if( ContextPtr:IsHidden() == false ) then
OnClose();
else
UIManager:QueuePopup( ContextPtr, PopupPriority.eUtmost );
end
else
UIManager:QueuePopup( ContextPtr, PopupPriority.eUtmost );
end
UIManager:SetUICursor( 0 );
end
Events.SearchForPediaEntry.Add( SearchForPediaEntry );
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
function GoToPediaHomePage ( iHomePage )
UIManager:SetUICursor( 1 );
UIManager:QueuePopup( ContextPtr, PopupPriority.Civilopedia );
SetSelectedCategory(iHomePage);
UIManager:SetUICursor( 0 );
end
Events.GoToPediaHomePage.Add( GoToPediaHomePage );
----------------------------------------------------------------
----------------------------------------------------------------
function ValidateText(text)
if #text < 3 then
return false;
end
local isAllWhiteSpace = true;
local numNonWhiteSpace = 0;
for i = 1, #text, 1 do
if string.byte(text, i) ~= 32 then
isAllWhiteSpace = false;
numNonWhiteSpace = numNonWhiteSpace + 1;
end
end
if isAllWhiteSpace then
return false;
end
if numNonWhiteSpace < 3 then
return false;
end
-- don't allow % character
for i = 1, #text, 1 do
if string.byte(text, i) == 37 then
return false;
end
end
local invalidCharArray = { '\"', '<', '>', '|', '\b', '\0', '\t', '\n', '/', '\\', '*', '?', '%[', ']' };
for i, ch in ipairs(invalidCharArray) do
if string.find(text, ch) ~= nil then
return false;
end
end
-- don't allow control characters
for i = 1, #text, 1 do
if string.byte(text, i) < 32 then
return false;
end
end
return true;
end
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
function OnSearchButtonClicked()
UIManager:SetUICursor( 1 );
local searchString = Controls.SearchEditBox:GetText();
local lowerCaseSearchString = nil;
if searchString ~= nil and searchString ~= "" and ValidateText(searchString) then
local article = searchableTextKeyList[searchString];
if article == nil then
lowerCaseSearchString = Locale.ToLower(searchString);
article = searchableList[lowerCaseSearchString];
end
if article then
SetSelectedCategory( article.entryCategory );
CivilopediaCategory[article.entryCategory].SelectArticle( article.entryID, addToList );
else
-- try to see if there is a partial match
local partialMatch = {};
local numberMatches = 0;
for i, v in pairs(searchableList) do
if string.find(Locale.ToLower(v.entryName), lowerCaseSearchString) ~= nil then
numberMatches = numberMatches + 1;
partialMatch[numberMatches] = v.entryName;
end
end
if numberMatches == 1 then
article = searchableList[Locale.ToLower(partialMatch[1])];
if article then
SetSelectedCategory( article.entryCategory );
CivilopediaCategory[article.entryCategory].SelectArticle( article.entryID, addToList );
end
elseif numberMatches > 1 then -- populate a dropdown with the matches
Controls.PartialMatchPullDown:ClearEntries();
--print "---------------------------------"
for i, v in pairs( partialMatch ) do
local controlTable = {};
Controls.PartialMatchPullDown:BuildEntry( "InstanceOne", controlTable );
controlTable.Button:SetText( v );
controlTable.Button:RegisterCallback(Mouse.eLClick,
function()
SearchForPediaEntry( v );
end);
controlTable.Button:SetVoid1( i );
--print(v);
end
Controls.PartialMatchPullDown:CalculateInternals();
--print "---------------------------------"
Controls.SearchButton:SetHide( true );
Controls.PartialMatchPullDown:SetHide( false );
Controls.PartialMatchPullDown:GetButton():SetText( searchString );
else
Controls.SearchNotFoundText:LocalizeAndSetText("TXT_KEY_SEARCH_NOT_FOUND", searchString);
Controls.SearchFoundNothing:SetHide(false);
end
end
end
UIManager:SetUICursor( 0 );
end
Controls.SearchButton:RegisterCallback( Mouse.eLClick, OnSearchButtonClicked );
function OnSearchTextEnter( dummyString, dummyControl )
OnSearchButtonClicked();
end
Controls.SearchEditBox:RegisterCallback( OnSearchTextEnter );
function OnSearchNotFoundOK()
Controls.SearchFoundNothing:SetHide(true);
end
Controls.OK:RegisterCallback(Mouse.eLClick, OnSearchNotFoundOK );
function InputHandler( uiMsg, wParam, lParam )
if(uiMsg == KeyEvents.KeyDown) then
if(not Controls.SearchFoundNothing:IsHidden()) then
if(wParam == Keys.VK_ESCAPE or wParam == Keys.VK_RETURN) then
Controls.SearchFoundNothing:SetHide(true);
return true;
end
else
if(wParam == Keys.VK_ESCAPE) then
OnClose();
return true;
end
end
end
end
ContextPtr:SetInputHandler( InputHandler );
function ShowHideHandler( isHide )
if( isHide ) then
Controls.Portrait:UnloadTexture();
Events.SystemUpdateUI.CallImmediate( SystemUpdateUIType.BulkShowUI );
else
Events.SystemUpdateUI.CallImmediate( SystemUpdateUIType.BulkHideUI );
if currentTopic then
local article = listOfTopicsViewed[currentTopic];
if article then
SetSelectedCategory( article.entryCategory );
CivilopediaCategory[article.entryCategory].SelectArticle( article.entryID, dontAddToList );
else
SetSelectedCategory(CategoryTerrain); -- this is a dummy so that the trigger for the next one fires
SetSelectedCategory(CategoryHomePage);
CivilopediaCategory[CategoryHomePage].DisplayHomePage();
end
end
end
end
ContextPtr:SetShowHideHandler( ShowHideHandler );
----------------------------------------------------------------
-- 'Active' (local human) player has changed
----------------------------------------------------------------
Events.GameplaySetActivePlayer.Add(OnClose);
----------------------------------------------------------------
-- If we hear a multiplayer game invite was sent, exit
-- so we don't interfere with the transition
----------------------------------------------------------------
function OnMultiplayerGameInvite()
if( ContextPtr:IsHidden() == false ) then
OnClose();
end
end
Events.MultiplayerGameLobbyInvite.Add( OnMultiplayerGameInvite );
Events.MultiplayerGameServerInvite.Add( OnMultiplayerGameInvite );
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
local tipControlTable = {};
TTManager:GetTypeControlTable( "TypeRoundImage", tipControlTable );
function TipHandler( control )
local id = control:GetVoid1();
local article = categorizedList[(selectedCategory * absurdlyLargeNumTopicsInCategory) + id];
if article and article.tooltipTexture then
tipControlTable.ToolTipImage:SetTexture( article.tooltipTexture );
tipControlTable.ToolTipImage:SetTextureOffset( article.tooltipTextureOffset );
tipControlTable.ToolTipFrame:SetHide( false );
else
tipControlTable.ToolTipFrame:SetHide( true );
end
end
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
for i = 1, numCategories, 1 do
if CivilopediaCategory[i].PopulateList then
CivilopediaCategory[i].PopulateList();
end
end
SetSelectedCategory(CategoryTerrain); -- this is a dummy so that the trigger for the next one fires
SetSelectedCategory(CategoryHomePage);
CivilopediaCategory[CategoryHomePage].DisplayHomePage();
|
local colors = require("cobalt2.utils").colors
local styles = require("cobalt2.utils").styles
local Group = require("cobalt2.utils").Group
---------------------------------------------------------------------------------
-- json --
---------------------------------------------------------------------------------
Group.new("jsonKeyword", colors.yellow, nil, nil)
Group.new("jsonEscape", colors.yellow, nil, nil)
Group.new("jsonNull", colors.dark_pink, nil, styles.italic)
Group.new("jsonBoolean", colors.dark_pink, nil, styles.italic)
|
local Cell = require('btree').Cell
describe("Cell", function()
it("Should be able to store data of integer type", function()
local cell = Cell:new(37)
assert.equal(cell.data, 37)
end)
it("Should be able to store data of string (blob) type", function()
local cell = Cell:new("hello world")
assert.equal(cell.data, "hello world")
end)
it("Should be able to return the size in bytes of the object stored in the cell", function()
-- The size of the cell must be the size of the data plus 8 bytes overhead to store the
-- size of the number itself
local cell = Cell:new(42)
assert.equal(cell.size, 16)
cell = Cell:new("Hello World")
assert.equal(cell.size, 19)
end)
it("Should be able to get the appropriate size for unicode strings", function()
local cell = Cell:new("΅ Ά · Έ Ή Ί Ό Ύ Ώ ΐ Α Β")
-- Each greek character takes two code points plus 11 spaces should yield
-- 24 bytes + 11 for the spaces == 35
assert.equal(cell.size, 43)
cell = Cell:new("∇∈")
-- Each mathematical operator takes 3 bytes in utf-8
assert.equal(cell.size, 14)
end)
end)
|
local pss = ...
return Def.ActorFrame{
OnCommand=cmd(zoom,0.8;pulse;effectmagnitude,1,0.9,0);
LoadActor("star.lua", pss);
};
|
-- imports
local WIM = WIM;
local _G = _G;
local hooksecurefunc = hooksecurefunc;
local table = table;
local pairs = pairs;
local string = string;
local select = select;
local math = math;
local tonumber = tonumber;
local playerRealm = GetRealmName()
-- set name space
setfenv(1, WIM);
local Windows = windows.active.chat;
db_defaults.pop_rules.chat = {
--pop-up rule sets based off of your location
resting = {
onSend = false,
onReceive = false,
supress = false,
autofocus = false,
keepfocus = false,
},
combat = {
onSend = false,
onReceive = false,
supress = false,
autofocus = false,
keepfocus = false,
},
pvp = {
onSend = false,
onReceive = false,
supress = false,
autofocus = false,
keepfocus = false,
},
arena = {
onSend = false,
onReceive = false,
supress = false,
autofocus = false,
keepfocus = false,
},
party = {
onSend = false,
onReceive = false,
supress = false,
autofocus = false,
keepfocus = false,
},
raid = {
onSend = false,
onReceive = false,
supress = false,
autofocus = false,
keepfocus = false,
},
bn = {
onSend = false,
onReceive = false,
supress = false,
autofocus = false,
keepfocus = false,
},
other = {
onSend = false,
onReceive = false,
supress = false,
autofocus = false,
keepfocus = false,
},
alwaysOther = true,
intercept = false,
}
db_defaults.chat = {
world = {
enabled = false,
channelSettings = {}
},
custom = {
enabled = false,
channelSettings = {}
},
guild = {
showAlerts = true,
},
officer = {
showAlerts = true,
},
raid = {
showAlerts = true,
},
party = {
showAlerts = true,
},
battleground = {
},
say = {
},
bn = {
showAlerts = true,
},
};
local USERLIST_BUTTON_COUNT = 5;
local function getRuleSet()
local curState = db.pop_rules.chat.alwaysOther and "other" or curState
return db.pop_rules.chat[curState];
end
local function createWidget_Chat()
local button = _G.CreateFrame("Button");
button.text = button:CreateFontString(nil, "BACKGROUND");
button.text:SetFont("Fonts\\SKURRI.ttf", 16);
button.text:SetAllPoints();
button.text:SetText("");
button.SetText = function(self, text)
self.text:SetText(text);
--adjust font size to match widget
end
button.SetActive = function(self, active)
self.active = active;
if(active) then
self:Show();
else
self:Hide();
end
end
button.SetDefaults = function(self)
self:SetActive(false);
end
button.UpdateSkin = function(self)
--self.flash.bg:SetTexture(GetSelectedSkin().message_window.widgets.w2w.HighlightTexture);
end
button:SetScript("OnClick", function(self)
if(self.active) then
ChatUserList.listCount = self.parentWindow.CHAT_listCount;
ChatUserList.listFun = self.parentWindow.CHAT_listFun;
ChatUserList:PopUp(self, "TOPRIGHT", "TOPLEFT")
ChatUserList:SetChannel(self.parentWindow.widgets.from:GetText());
end
end);
button:SetScript("OnLeave", function(self)
--ChatUserList:Hide();
end);
return button;
end
local function getChatWindow(ChatName, chatType)
if(not ChatName or ChatName == "") then
-- if invalid user, then return nil;
return nil;
end
local obj = Windows[ChatName];
if(obj and obj.type == "chat") then
-- if the whisper window exists, return the object
return obj;
else
-- otherwise, create a new one.
Windows[ChatName] = CreateChatWindow(ChatName);
Windows[ChatName].chatType = chatType;
Windows[ChatName]:UpdateIcon();
Windows[ChatName].widgets.chat_info:SetActive(true);
Windows[ChatName].chatList = Windows[ChatName].chatList or {};
if(chatType == "guild") then
Windows[ChatName].CHAT_listCount = _G.GetNumGuildMembers;
Windows[ChatName].CHAT_listFun = _G.GetGuildRosterInfo;
else
Windows[ChatName].CHAT_listCount = nil;
Windows[ChatName].CHAT_listFun = nil;
end
return Windows[ChatName];
end
end
local function cleanChatList(win)
if(win.chatList) then
for k, _ in pairs(win.chatList) do
win.chatList[k] = nil;
end
end
end
RegisterWidgetTrigger("msg_box", "chat", "OnEnterPressed", function(self)
local obj, msg, TARGET, NUMBER = self:GetParent(), self:GetText();
msg = PreSendFilterText(msg);
if(obj.chatType == "guild") then
TARGET = "GUILD";
elseif(obj.chatType == "officer") then
TARGET = "OFFICER";
elseif(obj.chatType == "party") then
TARGET = "PARTY";
elseif(obj.chatType == "raid") then
TARGET = "RAID";
elseif(obj.chatType == "battleground") then
TARGET = "INSTANCE_CHAT";
elseif(obj.chatType == "say") then
TARGET = "SAY";
elseif(obj.chatType == "channel") then
TARGET = "CHANNEL";
NUMBER = obj.channelNumber;
else
return;
end
local msgCount = math.ceil(string.len(msg)/255);
if(msgCount == 1) then
_G.ChatThrottleLib:SendChatMessage("ALERT", "WIM", msg, TARGET, nil, NUMBER);
elseif(msgCount > 1) then
SendSplitMessage("ALERT", "WIM", msg, TARGET, nil, NUMBER);
end
self:SetText("");
end);
--------------------------------------
-- Guild Chat --
--------------------------------------
-- create GuildChat Module
local Guild = CreateModule("GuildChat");
-- This Module requires LibChatHandler-1.0
_G.LibStub:GetLibrary("LibChatHandler-1.0"):Embed(Guild);
function Guild:OnEnable()
RegisterWidget("chat_info", createWidget_Chat);
self:RegisterChatEvent("CHAT_MSG_GUILD");
self:RegisterChatEvent("CHAT_MSG_GUILD_ACHIEVEMENT");
self:RegisterEvent("GUILD_ROSTER_UPDATE");
end
function Guild:OnDisable()
self:UnregisterChatEvent("CHAT_MSG_GUILD");
self:UnregisterChatEvent("CHAT_MSG_GUILD_ACHIEVEMENT");
end
function Guild:OnWindowDestroyed(self)
if(self.type == "chat" and self.chatType == "guild") then
local chatName = self.theUser;
Windows[chatName].chatType = nil;
Windows[chatName].unreadCount = nil;
Windows[chatName].chatLoaded = nil;
cleanChatList(Windows[chatName]);
Windows[chatName] = nil;
Guild.guildWindow = nil;
end
end
function Guild:OnWindowShow(self)
if(self.type == "chat" and self.chatType == "guild") then
_G.GuildRoster();
end
end
function Guild:GUILD_ROSTER_UPDATE()
if(self.guildWindow) then
-- update guild count
cleanChatList(self.guildWindow);
local count = 0;
for i=1, _G.GetNumGuildMembers() do
local name, rank, rankIndex, level, class, zone, note, officernote, online, status, classFileName, achievementPoints, achievementRank, isMobile = _G.GetGuildRosterInfo(i);
if(online) then
_G.GuildControlSetRank(rankIndex);
local guildchat_listen, guildchat_speak, officerchat_listen, officerchat_speak, promote, demote,
invite_member, remove_member, set_motd, edit_public_note, view_officer_note, edit_officer_note,
modify_guild_info, _, withdraw_repair, withdraw_gold, create_guild_event = _G.GuildControlGetRankFlags();
if(guildchat_listen) then
name = _G.Ambiguate(name, "none")
count = count + 1;
table.insert(self.guildWindow.chatList, name);
end
end
end
self.guildWindow.widgets.chat_info:SetText(count);
end
end
function Guild:CHAT_MSG_GUILD_CONTROLLER(eventController, ...)
if(eventController.ignoredByWIM) then
eventController:BlockFromDelegate(self);
return;
end
if(not db.chat.guild.neverSuppress and getRuleSet().supress) then
eventController:BlockFromChatFrame(self);
end
end
function Guild:CHAT_MSG_GUILD(...)
local filter, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12 = honorChatFrameEventFilter("CHAT_MSG_GUILD", ...);
if(filter) then
return;
end
arg2 = _G.Ambiguate(arg2, "none")
local win = getChatWindow(_G.GUILD, "guild");
local color = _G.ChatTypeInfo["GUILD"];
self.guildWindow = win;
if(not self.chatLoaded) then
Guild:GUILD_ROSTER_UPDATE();
end
self.chatLoaded = true;
arg3 = CleanLanguageArg(arg3);
win:AddEventMessage(color.r, color.g, color.b, "CHAT_MSG_GUILD", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
if(arg2 ~= _G.UnitName("player")) then
win.unreadCount = win.unreadCount and (win.unreadCount + 1) or 1;
if(not db.chat.guild.neverPop) then
win:Pop("in");
end
else
if(not db.chat.guild.neverPop) then
win:Pop("out");
end
end
CallModuleFunction("PostEvent_ChatMessage", "CHAT_MSG_GUILD", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
end
--------------------------------------
-- Officer Chat --
--------------------------------------
-- create OfficerChat Module
local Officer = CreateModule("OfficerChat");
-- This Module requires LibChatHandler-1.0
_G.LibStub:GetLibrary("LibChatHandler-1.0"):Embed(Officer);
function Officer:OnEnable()
RegisterWidget("chat_info", createWidget_Chat);
self:RegisterChatEvent("CHAT_MSG_OFFICER");
self:RegisterEvent("GUILD_ROSTER_UPDATE");
end
function Officer:OnDisable()
self:UnregisterChatEvent("CHAT_MSG_OFFICER");
end
function Officer:OnWindowDestroyed(self)
if(self.type == "chat" and self.chatType == "officer") then
local chatName = self.theUser;
Windows[chatName].chatType = nil;
Windows[chatName].unreadCount = nil;
Windows[chatName].chatLoaded = nil;
cleanChatList(Windows[chatName]);
Windows[chatName] = nil;
Officer.officerWin = nil;
end
end
function Officer:GUILD_ROSTER_UPDATE()
if(self.officerWindow) then
-- update guild count
cleanChatList(self.officerWindow);
local count = 0;
for i=1, _G.GetNumGuildMembers() do
local name, rank, rankIndex, level, class, zone, note, officernote, online, status, classFileName, achievementPoints, achievementRank, isMobile = _G.GetGuildRosterInfo(i);
if(online) then
_G.GuildControlSetRank(rankIndex);
local guildchat_listen, guildchat_speak, officerchat_listen, officerchat_speak, promote, demote,
invite_member, remove_member, set_motd, edit_public_note, view_officer_note, edit_officer_note,
modify_guild_info, _, withdraw_repair, withdraw_gold, create_guild_event = _G.GuildControlGetRankFlags();
if(officerchat_listen) then
name = _G.Ambiguate(name, "none")
count = count + 1;
table.insert(self.officerWindow.chatList, name);
end
end
end
self.officerWindow.widgets.chat_info:SetText(count);
end
end
function Officer:CHAT_MSG_OFFICER_CONTROLLER(eventController, ...)
if(eventController.ignoredByWIM) then
eventController:BlockFromDelegate(self);
return;
end
if(not db.chat.officer.neverSuppress and getRuleSet().supress) then
eventController:BlockFromChatFrame(self);
end
end
function Officer:CHAT_MSG_OFFICER(...)
local filter, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12 = honorChatFrameEventFilter("CHAT_MSG_OFFICER", ...);
if(filter) then
return;
end
arg2 = _G.Ambiguate(arg2, "none")
local win = getChatWindow(_G.GUILD_RANK1_DESC, "officer");
local color = _G.ChatTypeInfo["OFFICER"];
Officer.officerWindow = win;
if(not self.chatLoaded) then
Officer:GUILD_ROSTER_UPDATE();
end
self.chatLoaded = true;
arg3 = CleanLanguageArg(arg3);
win:AddEventMessage(color.r, color.g, color.b, "CHAT_MSG_OFFICER", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
if(arg2 ~= _G.UnitName("player")) then
win.unreadCount = win.unreadCount and (win.unreadCount + 1) or 1;
if(not db.chat.officer.neverPop) then
win:Pop("in");
end
else
if(not db.chat.officer.neverPop) then
win:Pop("out");
end
end
CallModuleFunction("PostEvent_ChatMessage", "CHAT_MSG_OFFICER", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
end
--------------------------------------
-- Party Chat --
--------------------------------------
-- create PartyChat Module
local Party = CreateModule("PartyChat");
-- This Module requires LibChatHandler-1.0
_G.LibStub:GetLibrary("LibChatHandler-1.0"):Embed(Party);
function Party:OnEnable()
RegisterWidget("chat_info", createWidget_Chat);
self:RegisterChatEvent("CHAT_MSG_PARTY");
self:RegisterChatEvent("CHAT_MSG_PARTY_LEADER");
self:RegisterEvent("GROUP_ROSTER_UPDATE");
end
function Party:OnDisable()
self:UnregisterChatEvent("CHAT_MSG_PARTY");
self:UnregisterChatEvent("CHAT_MSG_PARTY_LEADER");
end
function Party:OnWindowDestroyed(self)
if(self.type == "chat" and self.chatType == "party") then
local chatName = self.theUser;
Windows[chatName].chatType = nil;
Windows[chatName].unreadCount = nil;
Windows[chatName].chatLoaded = nil;
cleanChatList(Windows[chatName]);
Windows[chatName] = nil;
Party.partyWindow = nil;
end
end
function Party:GROUP_ROSTER_UPDATE()
if(Party.partyWindow) then
cleanChatList(self.partyWindow);
local myName = _G.UnitName("player");
table.insert(self.partyWindow.chatList, myName);
local count = 0;
for i=1, 4 do
if _G.UnitExists("party"..i) then
count = count + 1;
local name = _G.GetUnitName("party"..i, true);
table.insert(self.partyWindow.chatList, name);
end
end
Party.partyWindow.widgets.chat_info:SetText(count + 1);
end
end
function Party:CHAT_MSG_PARTY_CONTROLLER(eventController, ...)
if(eventController.ignoredByWIM) then
eventController:BlockFromDelegate(self);
return;
end
if(not db.chat.party.neverSuppress and getRuleSet().supress) then
eventController:BlockFromChatFrame(self);
end
end
function Party:CHAT_MSG_PARTY(...)
local filter, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12 = honorChatFrameEventFilter("CHAT_MSG_PARTY", ...);
if(filter) then
return;
end
arg2 = _G.Ambiguate(arg2, "none")
local win = getChatWindow(_G.PARTY, "party");
local color = _G.ChatTypeInfo["PARTY"];
Party.partyWindow = win;
if(not self.chatLoaded) then
Party:GROUP_ROSTER_UPDATE();
end
self.chatLoaded = true;
arg3 = CleanLanguageArg(arg3);
win:AddEventMessage(color.r, color.g, color.b, "CHAT_MSG_PARTY", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
if(arg2 ~= _G.UnitName("player")) then
win.unreadCount = win.unreadCount and (win.unreadCount + 1) or 1;
if(not db.chat.party.neverPop) then
win:Pop("in");
end
else
if(not db.chat.party.neverPop) then
win:Pop("out");
end
end
CallModuleFunction("PostEvent_ChatMessage", "CHAT_MSG_PARTY", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
end
function Party:CHAT_MSG_PARTY_LEADER_CONTROLLER(eventController, ...)
if(eventController.ignoredByWIM) then
eventController:BlockFromDelegate(self);
return;
end
if(not db.chat.party.neverSuppress and getRuleSet().supress) then
eventController:BlockFromChatFrame(self);
end
end
function Party:CHAT_MSG_PARTY_LEADER(...)
local filter, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12 = honorChatFrameEventFilter("CHAT_MSG_PARTY_LEADER", ...);
if(filter) then
return;
end
arg2 = _G.Ambiguate(arg2, "none")
local win = getChatWindow(_G.PARTY, "party");
local color = _G.ChatTypeInfo["PARTY_LEADER"];
self.raidWindow = win;
if(not self.chatLoaded) then
Party:GROUP_ROSTER_UPDATE();
end
self.chatLoaded = true;
arg3 = CleanLanguageArg(arg3);
win:AddEventMessage(color.r, color.g, color.b, "CHAT_MSG_PARTY_LEADER", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
if(arg2 ~= _G.UnitName("player")) then
win.unreadCount = win.unreadCount and (win.unreadCount + 1) or 1;
if(not db.chat.party.neverPop) then
win:Pop("in");
end
else
if(not db.chat.party.neverPop) then
win:Pop("out");
end
end
CallModuleFunction("PostEvent_ChatMessage", "CHAT_MSG_PARTY_LEADER", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
end
--------------------------------------
-- Raid Chat --
--------------------------------------
-- create RaidChat Module
local Raid = CreateModule("RaidChat");
-- This Module requires LibChatHandler-1.0
_G.LibStub:GetLibrary("LibChatHandler-1.0"):Embed(Raid);
function Raid:OnEnable()
RegisterWidget("chat_info", createWidget_Chat);
self:RegisterChatEvent("CHAT_MSG_RAID");
self:RegisterChatEvent("CHAT_MSG_RAID_LEADER");
self:RegisterChatEvent("CHAT_MSG_RAID_WARNING");
self:RegisterEvent("GROUP_ROSTER_UPDATE");
end
function Raid:OnDisable()
self:UnregisterChatEvent("CHAT_MSG_RAID");
self:UnregisterChatEvent("CHAT_MSG_RAID_LEADER");
self:UnregisterChatEvent("CHAT_MSG_RAID_WARNING");
end
function Raid:OnWindowDestroyed(self)
if(self.type == "chat" and self.chatType == "raid") then
local chatName = self.theUser;
Windows[chatName].chatType = nil;
Windows[chatName].unreadCount = nil;
Windows[chatName].chatLoaded = nil;
cleanChatList(Windows[chatName]);
Windows[chatName] = nil;
end
end
function Raid:GROUP_ROSTER_UPDATE()
if(Raid.raidWindow) then
cleanChatList(self.raidWindow);
local count = 0;
for i=1,40 do
local name = _G.GetRaidRosterInfo(i);
if(name) then
count = count + 1;
table.insert(self.raidWindow.chatList, name);
end
end
self.raidWindow.widgets.chat_info:SetText(count);
end
end
function Raid:CHAT_MSG_RAID_CONTROLLER(eventController, ...)
if(eventController.ignoredByWIM) then
eventController:BlockFromDelegate(self);
return;
end
if(not db.chat.raid.neverSuppress and getRuleSet().supress) then
eventController:BlockFromChatFrame(self);
end
end
function Raid:CHAT_MSG_RAID(...)
local filter, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12 = honorChatFrameEventFilter("CHAT_MSG_RAID", ...);
if(filter) then
return;
end
arg2 = _G.Ambiguate(arg2, "none")
local win = getChatWindow(_G.RAID, "raid");
local color = _G.ChatTypeInfo["RAID"];
self.raidWindow = win;
if(not self.chatLoaded) then
Raid:GROUP_ROSTER_UPDATE();
end
self.chatLoaded = true;
arg3 = CleanLanguageArg(arg3);
win:AddEventMessage(color.r, color.g, color.b, "CHAT_MSG_RAID", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
if(arg2 ~= _G.UnitName("player")) then
win.unreadCount = win.unreadCount and (win.unreadCount + 1) or 1;
if(not db.chat.raid.neverPop) then
win:Pop("in");
end
else
if(not db.chat.raid.neverPop) then
win:Pop("out");
end
end
CallModuleFunction("PostEvent_ChatMessage", "CHAT_MSG_RAID", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
end
function Raid:CHAT_MSG_RAID_LEADER_CONTROLLER(eventController, ...)
if(eventController.ignoredByWIM) then
eventController:BlockFromDelegate(self);
return;
end
if(not db.chat.raid.neverSuppress and getRuleSet().supress) then
eventController:BlockFromChatFrame(self);
end
end
function Raid:CHAT_MSG_RAID_LEADER(...)
local filter, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12 = honorChatFrameEventFilter("CHAT_MSG_RAID_LEADER", ...);
if(filter) then
return;
end
arg2 = _G.Ambiguate(arg2, "none")
local win = getChatWindow(_G.RAID, "raid");
local color = _G.ChatTypeInfo["RAID_LEADER"];
self.raidWindow = win;
if(not self.chatLoaded) then
Raid:GROUP_ROSTER_UPDATE();
end
self.chatLoaded = true;
arg3 = CleanLanguageArg(arg3);
win:AddEventMessage(color.r, color.g, color.b, "CHAT_MSG_RAID_LEADER", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
if(arg2 ~= _G.UnitName("player")) then
win.unreadCount = win.unreadCount and (win.unreadCount + 1) or 1;
if(not db.chat.raid.neverPop) then
win:Pop("in");
end
else
if(not db.chat.raid.neverPop) then
win:Pop("out");
end
end
CallModuleFunction("PostEvent_ChatMessage", "CHAT_MSG_RAID_LEADER", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
end
function Raid:CHAT_MSG_RAID_WARNING_CONTROLLER(eventController, ...)
if(eventController.ignoredByWIM) then
eventController:BlockFromDelegate(self);
return;
end
if(not db.chat.raid.neverSuppress and getRuleSet().supress) then
eventController:BlockFromChatFrame(self);
end
end
function Raid:CHAT_MSG_RAID_WARNING(...)
local filter, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12 = honorChatFrameEventFilter("CHAT_MSG_RAID_WARNING", ...);
if(filter) then
return;
end
arg2 = _G.Ambiguate(arg2, "none")
local win = getChatWindow(_G.RAID, "raid");
local color = _G.ChatTypeInfo["RAID_WARNING"];
self.raidWindow = win;
if(not self.chatLoaded) then
Raid:GROUP_ROSTER_UPDATE();
end
self.chatLoaded = true;
arg3 = CleanLanguageArg(arg3);
win:AddEventMessage(color.r, color.g, color.b, "CHAT_MSG_RAID_WARNING", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
if(arg2 ~= _G.UnitName("player")) then
win.unreadCount = win.unreadCount and (win.unreadCount + 1) or 1;
if(not db.chat.raid.neverPop) then
win:Pop("in");
end
else
if(not db.chat.raid.neverPop) then
win:Pop("out");
end
end
CallModuleFunction("PostEvent_ChatMessage", "CHAT_MSG_RAID_WARNING", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
end
--------------------------------------
-- Battleground Chat --
--------------------------------------
-- create RaidChat Module
local Battleground = CreateModule("BattlegroundChat");
-- This Module requires LibChatHandler-1.0
_G.LibStub:GetLibrary("LibChatHandler-1.0"):Embed(Battleground);
function Battleground:OnEnable()
RegisterWidget("chat_info", createWidget_Chat);
self:RegisterChatEvent("CHAT_MSG_INSTANCE_CHAT");
self:RegisterChatEvent("CHAT_MSG_INSTANCE_CHAT_LEADER");
end
function Battleground:OnDisable()
self:UnregisterChatEvent("CHAT_MSG_INSTANCE_CHAT");
self:UnregisterChatEvent("CHAT_MSG_INSTANCE_CHAT_LEADER");
end
function Battleground:OnWindowDestroyed(self)
if(self.type == "chat" and self.chatType == "battleground") then
local chatName = self.theUser;
Windows[chatName].chatType = nil;
Windows[chatName].unreadCount = nil;
Windows[chatName].chatLoaded = nil;
Windows[chatName].battlegroundWindow = nil;
Windows[chatName] = nil;
end
end
local function getBattlegroundCount()
for i=1, 20 do
local name, header, collapsed, channelNumber, count, active, category, voiceEnabled, voiceActive = _G.GetChannelDisplayInfo(i);
if(name == _G.INSTANCE_CHAT) then
return count;
end
end
return 0;
end
function Battleground:OnWindowShow(win)
if(win.type == "chat" and win.chatType == "battleground") then
win.widgets.chat_info:SetText(getBattlegroundCount());
end
end
function Battleground:CHAT_MSG_INSTANCE_CHAT_CONTROLLER(eventController, ...)
if(eventController.ignoredByWIM) then
eventController:BlockFromDelegate(self);
return;
end
if(not db.chat.battleground.neverSuppress and getRuleSet().supress) then
eventController:BlockFromChatFrame(self);
end
end
function Battleground:CHAT_MSG_INSTANCE_CHAT(...)
local filter, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12 = honorChatFrameEventFilter("CHAT_MSG_INSTANCE_CHAT", ...);
if(filter) then
return;
end
arg2 = _G.Ambiguate(arg2, "none")
local win = getChatWindow(_G.INSTANCE_CHAT, "battleground");
win.widgets.chat_info:SetText(getBattlegroundCount());
local color = _G.ChatTypeInfo["INSTANCE_CHAT"];
self.battlegroundWindow = win;
self.chatLoaded = true;
arg3 = CleanLanguageArg(arg3);
win:AddEventMessage(color.r, color.g, color.b, "CHAT_MSG_INSTANCE_CHAT", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
if(arg2 ~= _G.UnitName("player")) then
win.unreadCount = win.unreadCount and (win.unreadCount + 1) or 1;
if(not db.chat.battleground.neverPop) then
win:Pop("in");
end
else
if(not db.chat.battleground.neverPop) then
win:Pop("out");
end
end
CallModuleFunction("PostEvent_ChatMessage", "CHAT_MSG_INSTANCE_CHAT", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
end
function Battleground:CHAT_MSG_INSTANCE_CHAT_LEADER_CONTROLLER(eventController, ...)
if(eventController.ignoredByWIM) then
eventController:BlockFromDelegate(self);
return;
end
if(not db.chat.battleground.neverSuppress and getRuleSet().supress) then
eventController:BlockFromChatFrame(self);
end
end
function Battleground:CHAT_MSG_INSTANCE_CHAT_LEADER(...)
local filter, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12 = honorChatFrameEventFilter("CHAT_MSG_INSTANCE_CHAT_LEADER", ...);
if(filter) then
return;
end
arg2 = _G.Ambiguate(arg2, "none")
local win = getChatWindow(_G.INSTANCE_CHAT, "battleground");
win.widgets.chat_info:SetText(getBattlegroundCount());
local color = _G.ChatTypeInfo["INSTANCE_CHAT_LEADER"];
self.battlegroundWindow = win;
self.chatLoaded = true;
arg3 = CleanLanguageArg(arg3);
win:AddEventMessage(color.r, color.g, color.b, "CHAT_MSG_INSTANCE_CHAT_LEADER", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
if(arg2 ~= _G.UnitName("player")) then
win.unreadCount = win.unreadCount and (win.unreadCount + 1) or 1;
if(not db.chat.battleground.neverPop) then
win:Pop("in");
end
else
if(not db.chat.battleground.neverPop) then
win:Pop("out");
end
end
CallModuleFunction("PostEvent_ChatMessage", "CHAT_MSG_INSTANCE_CHAT_LEADER", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
end
--------------------------------------
-- Say Chat --
--------------------------------------
-- create SayChat Module
local Say = CreateModule("SayChat");
-- This Module requires LibChatHandler-1.0
_G.LibStub:GetLibrary("LibChatHandler-1.0"):Embed(Say);
function Say:OnEnable()
RegisterWidget("chat_info", createWidget_Chat);
self:RegisterChatEvent("CHAT_MSG_SAY");
end
function Say:OnDisable()
self:UnregisterChatEvent("CHAT_MSG_SAY");
end
function Say:OnWindowDestroyed(self)
if(self.type == "chat" and self.chatType == "say") then
local chatName = self.theUser;
Windows[chatName].chatType = nil;
Windows[chatName].unreadCount = nil;
Windows[chatName].chatLoaded = nil;
cleanChatList(Windows[chatName]);
Windows[chatName] = nil;
end
end
function Say:CHAT_MSG_SAY_CONTROLLER(eventController, ...)
if(eventController.ignoredByWIM) then
eventController:BlockFromDelegate(self);
return;
end
if(not db.chat.say.neverSuppress and getRuleSet().supress) then
eventController:BlockFromChatFrame(self);
end
end
function Say:CHAT_MSG_SAY(...)
local filter, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12 = honorChatFrameEventFilter("CHAT_MSG_SAY", ...);
if(filter) then
return;
end
arg2 = _G.Ambiguate(arg2, "none")
local win = getChatWindow(_G.SAY, "say");
local color = _G.ChatTypeInfo["SAY"];
self.chatLoaded = true;
arg3 = CleanLanguageArg(arg3);
--win:AddEventMessage(color.r, color.g, color.b, "CHAT_MSG_SAY", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
if(arg2 ~= _G.UnitName("player")) then
win.unreadCount = win.unreadCount and (win.unreadCount + 1) or 1;
if(not db.chat.say.neverPop) then
win:Pop("in");
end
else
if(not db.chat.say.neverPop) then
win:Pop("out");
end
end
--CallModuleFunction("PostEvent_ChatMessage", "CHAT_MSG_SAY", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
end
--------------------------------------
-- Channel Chat --
--------------------------------------
-- create ChannelChat Module
local Channel = CreateModule("ChannelChat");
-- This Module requires LibChatHandler-1.0
_G.LibStub:GetLibrary("LibChatHandler-1.0"):Embed(Channel);
function Channel:OnEnable()
RegisterWidget("chat_info", createWidget_Chat);
self:RegisterChatEvent("CHAT_MSG_CHANNEL");
self:RegisterChatEvent("CHAT_MSG_CHANNEL_JOIN");
self:RegisterChatEvent("CHAT_MSG_CHANNEL_LEAVE");
self:RegisterChatEvent("CHAT_MSG_CHANNEL_NOTICE");
self:RegisterChatEvent("CHAT_MSG_CHANNEL_NOTICE_USER");
end
function Channel:OnDisable()
self:UnregisterChatEvent("CHAT_MSG_CHANNEL");
self:UnregisterChatEvent("CHAT_MSG_CHANNEL_JOIN");
self:UnregisterChatEvent("CHAT_MSG_CHANNEL_LEAVE");
self:UnregisterChatEvent("CHAT_MSG_CHANNEL_NOTICE");
self:UnregisterChatEvent("CHAT_MSG_CHANNEL_NOTICE_USER");
end
function Channel:OnWindowDestroyed(self)
if(self.type == "chat" and self.chatType == "channel") then
local chatName = self.theUser;
Windows[chatName].chatType = nil;
Windows[chatName].unreadCount = nil;
Windows[chatName].chatLoaded = nil;
Windows[chatName].channelNumber = nil;
Windows[chatName].channelSpecial = nil;
cleanChatList(Windows[chatName]);
Windows[chatName] = nil;
end
end
Channel.waitingList = {};
--GetChannelRosterInfo(id, rosterIndex)
local function loadChatList(win, ...)
cleanChatList(win);
for i=1, select("#", ...) do
table.insert(win.chatList, string.trim(select(i, ...)));
end
end
local function updateJoinLeave(event, ...)
local arg1, who, arg3, channelIdentifier, arg5, arg6, arg7, channelNumber, arg9 = ...;
for _, win in pairs(Windows) do
if(win.channelIdentifier == channelIdentifier) then
win.widgets.chat_info:SetText(GetChannelCount(win.channelNumber));
local color = _G.ChatTypeInfo["CHANNEL"..channelNumber];
win:AddEventMessage(color.r, color.g, color.b, event, ...);
return;
end
end
end
function Channel:CHAT_MSG_CHANNEL_JOIN(...)
local arg1, who, arg3, channelIdentifier, arg5, arg6, arg7, channelNumber, arg9 = ...;
updateJoinLeave("CHAT_MSG_CHANNEL_JOIN", ...)
end
function Channel:CHAT_MSG_CHANNEL_LEAVE(...)
local arg1, who, arg3, channelIdentifier, arg5, arg6, arg7, channelNumber, arg9 = ...;
updateJoinLeave("CHAT_MSG_CHANNEL_LEAVE", ...)
end
function Channel:CHAT_MSG_CHANNEL_NOTICE(...)
local arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11 = ...;
for _, win in pairs(Windows) do
if(win.channelIdentifier == arg4) then
local color = _G.ChatTypeInfo["CHANNEL"..arg8];
win:AddEventMessage(color.r, color.g, color.b, "CHAT_MSG_CHANNEL_NOTICE", ...);
return;
end
end
-- create new window if arg1 is YOU_JOINED
if(arg1 == "YOU_JOINED") then
-- open window.
Channel:CHAT_MSG_CHANNEL("", "", nil, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11);
end
end
function Channel:CHAT_MSG_CHANNEL_NOTICE_USER(...)
local arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11 = ...;
for _, win in pairs(Windows) do
if(win.channelIdentifier == arg4) then
local color = _G.ChatTypeInfo["CHANNEL"..arg8];
win:AddEventMessage(color.r, color.g, color.b, "CHAT_MSG_CHANNEL_NOTICE_USER", ...);
return;
end
end
end
function Channel:OnWindowShow(win)
if(win.type == "chat" and win.chatType == "channel") then
win.widgets.chat_info:SetText(GetChannelCount(win.channelNumber));
end
end
-- manage suppression
function Channel:CHAT_MSG_CHANNEL_CONTROLLER(eventController, arg1, arg2, arg3, ...)
if(eventController.ignoredByWIM) then
eventController:BlockFromDelegate(self);
return;
end
local arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11 = ...;
-- arg7 Generic Channels (1 for General, 2 for Trade, 22 for LocalDefense, 23 for WorldDefense and 26 for LFG)
-- arg8 Channel Number
-- arg9 Channel Name
local isWorld = arg7 and arg7 > 0;
local channelName = string.split(" - ", arg9);
local neverSuppress = db.chat[isWorld and "world" or "custom"].channelSettings[channelName] and db.chat[isWorld and "world" or "custom"].channelSettings[channelName].neverSuppress;
--check options. do we want the specified channels.
if(isWorld and not db.chat.world.enabled) then
return;
elseif(not isWorld and not db.chat.custom.enabled) then
return;
elseif(not neverSuppress and getRuleSet().supress and db.chat[isWorld and "world" or "custom"].channelSettings[channelName] and db.chat[isWorld and "world" or "custom"].channelSettings[channelName].monitor) then
eventController:BlockFromChatFrame(self);
end
end
function Channel:CHAT_MSG_CHANNEL(...)
local filter, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12 = honorChatFrameEventFilter("CHAT_MSG_CHANNEL", ...);
if(filter) then
return;
end
-- arg7 Generic Channels (1 for General, 2 for Trade, 22 for LocalDefense, 23 for WorldDefense and 26 for LFG)
-- arg8 Channel Number
-- arg9 Channel Name
local isWorld = arg7 and arg7 > 0;
local channelName = string.split(" - ", arg9);
--check options. do we want the specified channels.
if(isWorld and not db.chat.world.enabled) then
return;
elseif(not isWorld and not db.chat.custom.enabled) then
return;
elseif(not db.chat[isWorld and "world" or "custom"].channelSettings[channelName] or not db.chat[isWorld and "world" or "custom"].channelSettings[channelName].monitor) then
return;
end
arg2 = _G.Ambiguate(arg2, "none")
local win = getChatWindow(channelName, "channel");
local color = _G.ChatTypeInfo["CHANNEL"..arg8];
if(arg7 == 1 or arg7 == 2 or arg7 == 22 or arg7 == 23 or arg7 == 26) then
win.widgets.char_info:SetText(arg9);
win.channelSpecial = _G.time();
else
win.widgets.char_info:SetText("");
end
win.channelNumber = arg8;
win.channelIdentifier = arg4;
if(win:IsVisible()) then
win.widgets.chat_info:SetText(GetChannelCount(win.channelNumber));
end
self.chatLoaded = true;
if(arg1 and _G.strlen(arg1) > 0) then
arg3 = CleanLanguageArg(arg3);
win:AddEventMessage(color.r, color.g, color.b, "CHAT_MSG_CHANNEL", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
local neverPop = db.chat[isWorld and "world" or "custom"].channelSettings[channelName] and db.chat[isWorld and "world" or "custom"].channelSettings[channelName].neverPop;
if(arg2 ~= _G.UnitName("player")) then
win.unreadCount = win.unreadCount and (win.unreadCount + 1) or 1;
if(not neverPop) then
win:Pop("in");
end
else
if(not neverPop) then
win:Pop("out");
end
end
CallModuleFunction("PostEvent_ChatMessage", "CHAT_MSG_CHANNEL", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
end
end
function Channel:SettingsChanged()
if(db.chat.world.enabled or db.chat.custom.enabled) then
self:Enable();
else
self:Disable();
end
end
-- alert management
local ChatAlerts = CreateModule("ChatAlerts");
function ChatAlerts:OnWindowShow(win)
if(win.type == "chat") then
MinimapPopAlert(win.theUser);
end
end
ChatAlerts.OnWindowDestroyed = ChatAlerts.OnWindowShow;
function ChatAlerts:PostEvent_ChatMessage(event, ...)
local arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11 = ...;
if(arg2 == _G.UnitName("player")) then
return; -- we don't count our own messages as new.
end
event = event:gsub("CHAT_MSG_", "");
if(event == "CHANNEL") then
local isWorld = arg7 and arg7 > 0;
local channelName = string.split(" - ", arg9);
local win = getChatWindow(channelName, "channel");
local showAlert = db.chat[isWorld and "world" or "custom"].channelSettings[channelName] and db.chat[isWorld and "world" or "custom"].channelSettings[channelName].showAlerts;
if(showAlert and win and not win:IsVisible() and win.unreadCount) then
local color = _G.ChatTypeInfo["CHANNEL"..arg8];
MinimapPushAlert(win.theUser, RGBPercentToHex(color.r, color.g, color.b), win.unreadCount);
end
else
local win;
if(event == "GUILD" and db.chat.guild.showAlerts) then
win = getChatWindow(_G.GUILD, "guild");
elseif(event == "OFFICER" and db.chat.officer.showAlerts) then
win = getChatWindow(_G.GUILD_RANK1_DESC, "officer");
elseif(event == "PARTY" and db.chat.party.showAlerts) then
win = getChatWindow(_G.PARTY, "party");
elseif((event == "RAID" or event == "RAID_LEADER") and db.chat.raid.showAlerts) then
win = getChatWindow(_G.RAID, "raid");
elseif((event == "INSTANCE_CHAT" or event == "INSTANCE_CHAT_LEADER") and db.chat.battleground.showAlerts) then
win = getChatWindow(_G.INSTANCE_CHAT, "battleground");
elseif(event == "SAY" and db.chat.say.showAlerts) then
win = getChatWindow(_G.SAY, "say");
end
if(win and not win:IsVisible() and win.unreadCount and win.unreadCount > 0) then
local chat_type = win.chatType == "battleground" and "INSTANCE_CHAT" or string.upper(win.chatType);
local color = _G.ChatTypeInfo[chat_type]; -- Drii: ticket 344 color error if party/instance chat handled by WIM
MinimapPushAlert(win.theUser, RGBPercentToHex(color.r, color.g, color.b), win.unreadCount);
end
end
end
-- should never be disabled.
ChatAlerts.canDisable = false;
ChatAlerts:Enable();
-- Options
-- create ChatOptions Module
local ChatOptions = CreateModule("ChatOptions");
local function loadChatOptions()
local desc = L["WIM will manage this chat type within its own message windows."];
-- standard chat template
local function createChatTemplate(chatName, moduleName, chatType)
local chatDB = db.chat[chatType];
local f = options.CreateOptionsFrame();
f.sub = f:CreateSection(chatName, desc);
f.sub.nextOffSetY = -10;
f.sub:CreateCheckButton(L["Enable"], WIM.modules[moduleName], "enabled", nil, function(self, button) EnableModule(moduleName, self:GetChecked()); end);
f.sub.nextOffSetY = -30;
f.sub:CreateCheckButton(L["Show Minimap Alerts"], chatDB, "showAlerts");
f.sub.nextOffSetY = -25;
f.sub:CreateCheckButton(L["Never pop-up on my screen."], chatDB, "neverPop");
f.sub:CreateCheckButton(L["Never suppress messages."], chatDB, "neverSuppress");
return f;
end
local channelList = {};
local function getChannelList(world)
--clear list
for k, _ in pairs (channelList) do
channelList[k] = nil;
end
for i=1, 20 do
local name, header, collapsed, channelNumber, count, active, category, voiceEnabled, voiceActive = _G.GetChannelDisplayInfo(i);
if((world and category == "CHANNEL_CATEGORY_WORLD") or (not world and category == "CHANNEL_CATEGORY_CUSTOM")) then
table.insert(channelList, name.."*"..(active and "1" or "0").."*"..(channelNumber or "0"));
end
end
return channelList;
end
local channelScrollCount = 1;
local function createChannelChatTemplate(chatName, channelType, channelListFun)
local f = options.CreateOptionsFrame();
f.sub = f:CreateSection(chatName, desc);
f.sub.nextOffSetY = -10;
f.sub.enabled = f.sub:CreateCheckButton(L["Enable"], db.chat[channelType], "enabled", nil, function(self, button) Channel:SettingsChanged(); end);
f.sub.nextOffSetY = -10;
--list
f.sub.list = f.sub:ImportCustomObject(_G.CreateFrame("Frame"));
options.AddFramedBackdrop(f.sub.list);
f.sub.list:SetFullSize();
f.sub.list.buttonHeight = 80;
f.sub.list:SetHeight(4 * f.sub.list.buttonHeight);
f.sub.list.scroll = _G.CreateFrame("ScrollFrame", f.sub:GetName().."ChannelScroll"..channelScrollCount, f.sub.list, "FauxScrollFrameTemplate");
channelScrollCount = channelScrollCount + 1;
f.sub.list.scroll:SetPoint("TOPLEFT", 0, -1);
f.sub.list.scroll:SetPoint("BOTTOMRIGHT", -23, 0);
f.sub.list.scroll.update = function(self)
local channelList = channelListFun();
local offset = _G.FauxScrollFrame_GetOffset(self);
for i=1, #f.sub.list.buttons do
local index = i+offset;
if(index <= #channelList) then
local name, active, channelNumber = string.split("*", channelList[index]);
active = active == "1";
f.sub.list.buttons[i]:Show();
f.sub.list.buttons[i].channelName = name;
if(not db.chat[channelType].channelSettings[name]) then
db.chat[channelType].channelSettings[name] = {};
end
f.sub.list.buttons[i].title:SetText("|cffffffff"..channelNumber..". |r"..name);
f.sub.list.buttons[i].cb1:SetChecked(db.chat[channelType].channelSettings[name] and db.chat[channelType].channelSettings[name].monitor);
f.sub.list.buttons[i].neverPop:SetChecked(db.chat[channelType].channelSettings[name] and db.chat[channelType].channelSettings[name].neverPop);
f.sub.list.buttons[i].neverSuppress:SetChecked(db.chat[channelType].channelSettings[name] and db.chat[channelType].channelSettings[name].neverSuppress);
f.sub.list.buttons[i].showAlerts:SetChecked(db.chat[channelType].channelSettings[name] and db.chat[channelType].channelSettings[name].showAlerts);
f.sub.list.buttons[i].noHistory:SetChecked(db.chat[channelType].channelSettings[name] and db.chat[channelType].channelSettings[name].noHistory);
local color = _G.ChatTypeInfo["CHANNEL"..channelNumber];
f.sub.list.buttons[i].title:SetTextColor(color.r, color.g, color.b);
if(active) then
f.sub.list.buttons[i].title:SetAlpha(1);
else
f.sub.list.buttons[i].title:SetAlpha(.4);
end
else
f.sub.list.buttons[i]:Hide();
end
end
_G.FauxScrollFrame_Update(self, #channelList, #f.sub.list.buttons, f.sub.list.buttonHeight);
end
f.sub.list.scroll:SetScript("OnVerticalScroll", function(self, offset)
_G.FauxScrollFrame_OnVerticalScroll(self, offset, f.sub.list.buttonHeight, f.sub.list.scroll.update);
end);
f.sub.list:SetScript("OnShow", function(self)
self.scroll:update();
end);
f.sub.list.createButton = function(self)
self.buttons = self.buttons or {};
local button = _G.CreateFrame("Button", nil, self);
button:SetHeight(self.buttonHeight);
--button:SetHighlightTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight", "ADD");
button.bg = button:CreateTexture(nil, "BACKGROUND");
button.bg:SetAllPoints();
button.bg:SetColorTexture(1,1,1, ((#self.buttons+1) % 2)*.1);
button.bg:SetGradientAlpha("HORIZONTAL", 1,1,1,1, 0,0,0,0);
button.border = {};
button.border.left = button:CreateTexture(nil, "OVERLAY");
button.border.left:SetPoint("TOPLEFT");
button.border.left:SetPoint("BOTTOMLEFT");
button.border.left:SetWidth(4);
button.border.left:SetColorTexture(1,1,1,.5);
button.title = button:CreateFontString(nil, "OVERLAY", "ChatFontNormal");
button.title:SetPoint("TOPLEFT", 35, -8);
button.title:SetPoint("TOPRIGHT");
button.title:SetJustifyH("LEFT")
local font, height, flags = button.title:GetFont();
button.title:SetFont(font, 14, flags);
button.title:SetTextColor(_G.GameFontNormal:GetTextColor());
button.title:SetText("Test");
--monitor checkbox
button.cb1 = _G.CreateFrame("CheckButton", nil, button, "UICheckButtonTemplate");
button.cb1:SetPoint("RIGHT", button.title, "LEFT", -5, 0);
button.cb1:SetScale(.75);
button.cb1:SetScript("OnEnter", function(self)
self:GetParent():GetParent().help:SetJustifyH("LEFT");
self:GetParent():GetParent().help:SetText(L["Have WIM monitor this channel."]);
end);
button.cb1:SetScript("OnLeave", function(self)
self:GetParent():GetParent().help:SetText("");
end);
button.cb1:SetScript("OnClick", function(self)
local name = self:GetParent().channelName;
db.chat[channelType].channelSettings[name].monitor = self:GetChecked();
end);
-- Never Pop
button.neverPop = _G.CreateFrame("CheckButton", nil, button, "UICheckButtonTemplate");
button.neverPop:SetPoint("TOPLEFT", button.cb1, "BOTTOMRIGHT", 20, 0);
button.neverPop:SetScale(.75);
button.neverPop.text = button.neverPop:CreateFontString(nil, "OVERLAY", "ChatFontNormal");
button.neverPop.text:SetPoint("LEFT", button.neverPop, "RIGHT", 0, 0);
button.neverPop.text:SetText(L["Never Pop"]);
button.neverPop:SetScript("OnClick", function(self)
local name = self:GetParent().channelName;
db.chat[channelType].channelSettings[name].neverPop = self:GetChecked();
end)
button.neverPop:SetScript("OnEnter", function(self)
self:GetParent():GetParent().help:SetJustifyH("LEFT");
self:GetParent():GetParent().help:SetText(L["Never have this window pop-up on my screen."]);
end);
button.neverPop:SetScript("OnLeave", function(self)
self:GetParent():GetParent().help:SetText("");
end);
-- Never Suppress
button.neverSuppress = _G.CreateFrame("CheckButton", nil, button, "UICheckButtonTemplate");
button.neverSuppress:SetPoint("TOPLEFT", button.neverPop, "BOTTOMLEFT", 0, 0);
button.neverSuppress:SetScale(.75);
button.neverSuppress.text = button.neverSuppress:CreateFontString(nil, "OVERLAY", "ChatFontNormal");
button.neverSuppress.text:SetPoint("LEFT", button.neverSuppress, "RIGHT", 0, 0);
button.neverSuppress.text:SetText(L["Never Supress"]);
button.neverSuppress:SetScript("OnClick", function(self)
local name = self:GetParent().channelName;
db.chat[channelType].channelSettings[name].neverSuppress = self:GetChecked();
end)
button.neverSuppress:SetScript("OnEnter", function(self)
self:GetParent():GetParent().help:SetJustifyH("LEFT");
self:GetParent():GetParent().help:SetText(L["Never suppress messages from the default chat frame."]);
end);
button.neverSuppress:SetScript("OnLeave", function(self)
self:GetParent():GetParent().help:SetText("");
end);
-- Show Minimap Alerts
button.showAlerts = _G.CreateFrame("CheckButton", nil, button, "UICheckButtonTemplate");
button.showAlerts:SetPoint("TOPLEFT", button.neverPop, "TOPRIGHT", 150, 0);
button.showAlerts:SetScale(.75);
button.showAlerts.text = button.showAlerts:CreateFontString(nil, "OVERLAY", "ChatFontNormal");
button.showAlerts.text:SetPoint("LEFT", button.showAlerts, "RIGHT", 0, 0);
button.showAlerts.text:SetText(L["Show Minimap Alerts"]);
button.showAlerts:SetScript("OnClick", function(self)
local name = self:GetParent().channelName;
db.chat[channelType].channelSettings[name].showAlerts = self:GetChecked();
end)
button.showAlerts:SetScript("OnEnter", function(self)
self:GetParent():GetParent().help:SetJustifyH("LEFT");
self:GetParent():GetParent().help:SetText(L["Show unread message alert on minimap."]);
end);
button.showAlerts:SetScript("OnLeave", function(self)
self:GetParent():GetParent().help:SetText("");
end);
-- Don't record history
button.noHistory = _G.CreateFrame("CheckButton", nil, button, "UICheckButtonTemplate");
button.noHistory:SetPoint("TOPLEFT", button.showAlerts, "BOTTOMLEFT", 0, 0);
button.noHistory:SetScale(.75);
button.noHistory.text = button.noHistory:CreateFontString(nil, "OVERLAY", "ChatFontNormal");
button.noHistory.text:SetPoint("LEFT", button.noHistory, "RIGHT", 0, 0);
button.noHistory.text:SetText(L["No History"]);
button.noHistory:SetScript("OnClick", function(self)
local name = self:GetParent().channelName;
db.chat[channelType].channelSettings[name].noHistory = self:GetChecked();
end)
button.noHistory:SetScript("OnEnter", function(self)
self:GetParent():GetParent().help:SetJustifyH("LEFT");
self:GetParent():GetParent().help:SetText(L["Do not record history for this channel."]);
end);
button.noHistory:SetScript("OnLeave", function(self)
self:GetParent():GetParent().help:SetText("");
end);
-- Don't play sounds
button.noSound = _G.CreateFrame("CheckButton", nil, button, "UICheckButtonTemplate");
button.noSound:SetPoint("TOPLEFT", button.noHistory, "TOPRIGHT", 100, 0);
button.noSound:SetScale(.75);
button.noSound.text = button.noSound:CreateFontString(nil, "OVERLAY", "ChatFontNormal");
button.noSound.text:SetPoint("LEFT", button.noSound, "RIGHT", 0, 0);
button.noSound.text:SetText(L["No Sound"]);
button.noSound:SetScript("OnClick", function(self)
local name = self:GetParent().channelName;
db.chat[channelType].channelSettings[name].noSound = self:GetChecked();
end)
button.noSound:SetScript("OnEnter", function(self)
self:GetParent():GetParent().help:SetJustifyH("LEFT");
self:GetParent():GetParent().help:SetText(L["Do not play sounds for this channel."]);
end);
button.noSound:SetScript("OnLeave", function(self)
self:GetParent():GetParent().help:SetText("");
end);
if(#self.buttons == 0) then
button:SetPoint("TOPLEFT");
button:SetPoint("TOPRIGHT", -25, 0);
else
button:SetPoint("TOPLEFT", self.buttons[#self.buttons], "BOTTOMLEFT");
button:SetPoint("TOPRIGHT", self.buttons[#self.buttons], "BOTTOMRIGHT");
end
button:SetScript("OnUpdate", function(self, elapsed)
for _, border in pairs(self.border) do
if(_G.MouseIsOver(self)) then
border:Show();
else
border:Hide();
end
end
end);
table.insert(self.buttons, button);
end
for i=1, 4 do
f.sub.list:createButton();
end
f.sub.list.help = f.sub.list:CreateFontString(nil, "OVERLAY", "ChatFontNormal");
f.sub.list.help:SetPoint("TOPLEFT", f.sub.list, "BOTTOMLEFT", 0, -2);
f.sub.list.help:SetPoint("BOTTOMRIGHT", f.sub.list, "BOTTOMRIGHT", 0, -12);
f.sub.list.help:SetText("");
f.sub.list.help:SetJustifyH("LEFT");
local font, height, flags = f.sub.list.help:GetFont();
f.sub.list.help:SetFont(font, 12, flags);
return f;
end
local function createGuildChat()
local f = createChatTemplate(_G.GUILD, "GuildChat", "guild");
return f;
end
local function createOfficerChat()
local f = createChatTemplate(_G.GUILD_RANK1_DESC, "OfficerChat", "officer");
return f;
end
local function createPartyChat()
local f = createChatTemplate(_G.PARTY, "PartyChat", "party");
return f;
end
local function createRaidChat()
local f = createChatTemplate(_G.RAID, "RaidChat", "raid");
return f;
end
local function createBattlegroundChat()
local f = createChatTemplate(_G.INSTANCE_CHAT, "BattlegroundChat", "battleground");
return f;
end
local function createSayChat()
local f = createChatTemplate(_G.SAY, "SayChat", "say");
return f;
end
local function createWorldChat()
local f = createChannelChatTemplate(L["World Chat"], "world", function() return getChannelList(true); end);
return f;
end
local function createCustomChat()
local f = createChannelChatTemplate(L["Custom Chat"], "custom", getChannelList);
return f;
end
RegisterOptionFrame(L["Chat"], _G.GUILD, createGuildChat);
RegisterOptionFrame(L["Chat"], _G.GUILD_RANK1_DESC, createOfficerChat);
RegisterOptionFrame(L["Chat"], _G.PARTY, createPartyChat);
RegisterOptionFrame(L["Chat"], _G.RAID, createRaidChat);
RegisterOptionFrame(L["Chat"], _G.INSTANCE_CHAT, createBattlegroundChat);
RegisterOptionFrame(L["Chat"], _G.SAY, createSayChat);
RegisterOptionFrame(L["Chat"], L["World Chat"], createWorldChat);
RegisterOptionFrame(L["Chat"], L["Custom Chat"], createCustomChat);
dPrint("Chat Options Initialized...");
ChatOptions.optionsLoaded = true;
end
local function createUserList()
local win = _G.CreateFrame("Frame", "WIM3_ChatUserList", WIM.WindowParent);
win:EnableMouse(true);
win:Hide();
win:SetPoint("CENTER");
-- set backdrop
win:SetBackdrop({bgFile = "Interface\\AddOns\\"..addonTocName.."\\Modules\\Textures\\Menu_bg",
edgeFile = "Interface\\AddOns\\"..addonTocName.."\\Modules\\Textures\\Menu",
tile = true, tileSize = 32, edgeSize = 32,
insets = { left = 32, right = 32, top = 32, bottom = 32 }});
win:SetWidth(200);
win.title = _G.CreateFrame("Frame", win:GetName().."Title", win);
win.title:SetHeight(17);
win.title:SetPoint("TOPLEFT", 20, -18); win.title:SetPoint("TOPRIGHT", -20, -18);
win.title.bg = win.title:CreateTexture(nil, "BACKGROUND");
win.title.bg:SetAllPoints();
win.title.text = win.title:CreateFontString(nil, "OVERLAY", "ChatFontNormal");
local font = win.title.text:GetFont();
win.title.text:SetFont(font, 11, "");
win.title.text:SetAllPoints();
win.title.text:SetJustifyV("TOP");
win.title.text:SetJustifyH("RIGHT");
win.title.text:SetText("Testing...");
win.buttons = {};
for i = 1, USERLIST_BUTTON_COUNT do
local button = _G.CreateFrame("Button", win:GetName().."Button1", win);
button:SetHighlightTexture("Interface\\QuestFrame\\UI-QuestLogTitleHighlight", "ADD");
button:GetHighlightTexture():SetVertexColor(.196, .388, .8);
button:SetHeight(20);
button.text = button:CreateFontString(nil, "OVERLAY", "ChatFontNormal");
button.text:SetText(" Button "..i);
button.text:SetJustifyH("LEFT");
button.text:SetAllPoints();
button.SetUser = function(self, user)
self.user = user;
self.text:SetText(" "..user);
end
button:SetScript("OnClick", function(self, button)
--if(button == "RightButton") then
--_G.ChannelRosterFrame_ShowDropdown(self.user);
--end
end);
if(i == 1) then
button:SetPoint("TOPLEFT", 20, -35);
button:SetPoint("RIGHT", -30, 0);
else
button:SetPoint("TOPLEFT", win.buttons[i-1], "BOTTOMLEFT");
button:SetPoint("TOPRIGHT", win.buttons[i-1], "BOTTOMRIGHT");
end
table.insert(win.buttons, button);
end
win:SetHeight(#win.buttons*win.buttons[1]:GetHeight() + 35 + 20);
win.scroll = _G.CreateFrame("ScrollFrame", win:GetName().."Scroll", win, "FauxScrollFrameTemplate");
win.scroll:SetPoint("TOPLEFT", win.buttons[1], "TOPLEFT", 0, 0);
win.scroll:SetPoint("BOTTOMRIGHT", win.buttons[#win.buttons], "BOTTOMRIGHT", -10, 0);
win.scroll:SetScript("OnVerticalScroll", function(self, offset)
_G.FauxScrollFrame_OnVerticalScroll(self, offset, win.buttons[1]:GetHeight(), win.updateList);
end);
win:SetScript("OnHide", function(self)
self:Hide();
self.attachedTo = nil;
self.listCount = nil;
self.listFun = nil;
self:SetParent(_G.UIParent);
end);
win:SetScript("OnUpdate", function(self, elapsed)
if(_G.MouseIsOver(self) or (self.attachedTo and _G.MouseIsOver(self.attachedTo))) then
self.idleTime = 0;
else
self.idleTime = self.idleTime + elapsed;
if(self.idleTime > 1) then
self:Hide();
end
end
end);
win.SetChannel = function(self, title)
self.title.text:SetText(string.format(L["Users in %s"], title or _G.CHAT).." ");
end
win.PopUp = function(self, attachTo, point, point2, offsetX, offsetY)
if(self.attachedTo == attachTo) then
self:Hide();
return;
end
self:SetParent(attachTo);
self:SetParentWindow(attachTo.parentWindow);
self.attachedTo = attachTo;
self:SetPoint(point, attachTo, point2, offsetX, offsetY);
self:Show();
win:updateList();
end
win.updateList = function(self)
self = win;
if(self.listCount and self.listFun) then
local count = self.listCount();
local offset = _G.FauxScrollFrame_GetOffset(win.scroll);
for i=1, USERLIST_BUTTON_COUNT do
self.buttons[i]:Show();
local index = i + offset;
if(index <= count) then
self.buttons[i]:SetUser(self.listFun(index));
self.buttons[i]:Show();
else
self.buttons[i]:Hide();
end
end
_G.FauxScrollFrame_Update(win.scroll, count, USERLIST_BUTTON_COUNT, self.buttons[1]:GetHeight());
else
self:Hide();
end
end
win.SetParentWindow = function(self, parent, start)
start = start or self;
start.parentWindow = parent;
if(start.GetChildren) then
for i=1, select("#", start:GetChildren()) do
self:SetParentWindow(parent, select(i, start:GetChildren()));
end
end
end
return win;
end
function ChatOptions:OnEnableWIM()
loadChatOptions();
--load joined channels.
--create user List
if(not ChatUserList) then
ChatUserList = createUserList();
end
end
-- global reference
GetChatWindow = getChatWindow;
function CleanLanguageArg(arg)
if(arg and arg ~= "Universal" and arg ~= _G.DEFAULT_CHAT_FRAME.defaultLanguage) then
return arg;
else
return nil;
end
end
local channelCountCache = {};
function GetChannelCount(id)
if(ChatUserList:IsVisible()) then
return channelCountCache[id] or "...";
end
for i=1, 20 do
local name, header, collapsed, channelNumber, count, active, category, voiceEnabled, voiceActive = _G.GetChannelDisplayInfo(i);
if(header and collapsed) then
_G.ExpandChannelHeader(i);
return GetChannelCount(id);
end
if(id == channelNumber) then
if(_G.GetSelectedDisplayChannel() ~= i) then
_G.SetSelectedDisplayChannel(i);
name, header, collapsed, channelNumber, count, active, category, voiceEnabled, voiceActive = _G.GetChannelDisplayInfo(i);
end
channelCountCache[id] = channelCountCache[id] or "...";
channelCountCache[id] = count or channelCountCache[id];
return channelCountCache[id];
end
end
return 0;
end
|
local function AddModel(AddTable, Model, Position, Ang, Clr, Mat, Scale)
AddTable.Model = AddTable.Model or {}
if type(AddTable.Model) ~= "table" then AddTable.Model = {} end
table.insert(AddTable.Model, {Model = Model, Position = Position, Angle = Ang, Color = Clr, Material = Mat, Scale = Scale})
return AddTable
end
local function AddStats(AddTable, Slot, Armor)
AddTable.Slot = Slot
AddTable.Armor = Armor
return AddTable
end
local function AddBuff(AddTable, Buff, Amount)
AddTable.Buffs[Buff] = Amount
return AddTable
end
local Item = QuickCreateItemTable(BaseArmor, "armor_chest_junkarmor", "Junky Armor", "Protects your heart and lungs from gettin pwnd", "icons/amor_junkyarmor")
Item = AddModel(Item, "models/Gibs/Shield_Scanner_Gib2.mdl", Vector(-0.2, 0.2, -3.3), Angle(-95.9, -10.5, 0))
Item = AddModel(Item, "models/Gibs/Scanner_gib02.mdl", Vector(-4.4, 3.1, 3.9), Angle(46, 9.2, -116.9))
Item = AddModel(Item, "models/Gibs/Scanner_gib02.mdl", Vector(7, 5, 4.6), Angle(-23.4, -4.7, 56.9))
Item = AddStats(Item, "slot_chest", 15)
Item = AddBuff(Item, "stat_maxhealth", 5)
Item.Weight = 2
Item.SellPrice = 420
Register.Item(Item)
local Item = QuickCreateItemTable(BaseArmor, "armor_chest_refinedjunkarmor", "Refined Junky Armor", "Protects your Body while still being cool", "icons/junk_box1")
Item = AddModel(Item, "models/Gibs/Shield_Scanner_Gib2.mdl", Vector(-0.2, 0.2, -3.3), Angle(-95.9, -10.5, 0))
Item = AddModel(Item, "models/Gibs/Shield_Scanner_Gib4.mdl", Vector(-2.3, -0.3, -5), Angle(-79.6, -4.7, 12.7))
Item = AddModel(Item, "models/Gibs/Scanner_gib02.mdl", Vector(-4.4, 3.1, 3.9), Angle(46, 9.2, -116.9))
Item = AddModel(Item, "models/Gibs/Scanner_gib02.mdl", Vector(7, 5, 4.6), Angle(-23.4, -4.7, 56.9))
Item = AddModel(Item, "models/Gibs/Scanner_gib04.mdl", Vector(-3.7, 8.4, 0.6), Angle(-11.4, 110.4, 117.1))
Item = AddStats(Item, "slot_chest", 25)
Item = AddBuff(Item, "stat_maxhealth", 10)
Item.Level = 14
Item.Weight = 2
Item.SellPrice = 1020
Register.Item(Item)
local Item = QuickCreateItemTable(BaseArmor, "armor_chest_antlionspiked", "Antlion Chest Armor", "Protects your Body while still being cool", "icons/junk_box1")
Item = AddModel(Item, "models/Gibs/Antlion_gib_Large_2.mdl", Vector(-1.9, 0.1, 4.6), Angle(-95.9, -10.5, 180))
Item = AddModel(Item, "models/Gibs/Antlion_gib_medium_3a.mdl", Vector(2.6, 1.9, 11.7), Angle(-180, -81, -36.8))
Item = AddModel(Item, "models/Gibs/Antlion_gib_medium_3a.mdl", Vector(-3.7, 3, 11.5), Angle(-159.9, -106.4, -32.8))
Item = AddModel(Item, "models/Gibs/Antlion_gib_Large_2.mdl", Vector(2.8, 0.6, 8.8), Angle(19.4, 3.3, -172))
Item = AddStats(Item, "slot_chest", 27)
Item = AddBuff(Item, "stat_maxhealth", 14)
Item.Level = 18
Item.Weight = 3
Item.SellPrice = 2020
Register.Item(Item)
local Item = QuickCreateItemTable(BaseArmor, "armor_chest_cyborg", "Biomechanical Chest", "You will be assimilated!", "icons/junk_box1")
Item = AddModel(Item, "models/Gibs/manhack_gib03.mdl", Vector(-3.9, -1.7, 0.8), Angle(-114.4, -10.5, 119.8))
Item = AddModel(Item, "models/Gibs/manhack_gib03.mdl", Vector(0.1, 1, 4.6), Angle(-157.2, 158.6, 0))
Item = AddModel(Item, "models/Gibs/manhack_gib02.mdl", Vector(10.4, -0.1, -0.8), Angle(162.6, -14.1, 12.7))
Item = AddModel(Item, "models/Gibs/manhack_gib02.mdl", Vector(1.7, 9.9, -2.1), Angle(-18.1, -27.4, 0))
Item = AddStats(Item, "slot_chest", 40)
Item = AddBuff(Item, "stat_dexterity", 10)
Item.Level = 20
Item.Weight = 4
Item.SellPrice = 8020
Register.Item(Item)
local Item = QuickCreateItemTable(BaseArmor, "armor_chest_antlion", "Antlion Shell Armor", "Crunchy!", "icons/junk_box1")
Item = AddModel(Item, "models/Gibs/Antlion_gib_small_2.mdl", Vector(0.1, -4.1, 0.1), Angle(85, 67.6, 52.9))--front
Item = AddModel(Item, "models/Gibs/Antlion_gib_small_2.mdl", Vector(0.8, -3, 2.1), Angle(-153.2, -0.7, 176))
Item = AddModel(Item, "models/Gibs/Antlion_gib_small_2.mdl", Vector(1, -7.7, 2.1), Angle(-153.2, -0.7, 176))
Item = AddModel(Item, "models/Gibs/Antlion_gib_small_2.mdl", Vector(-4.3, -3.2, 4.3), Angle(-153.2, -0.7, 174.6))
Item = AddModel(Item, "models/Gibs/Antlion_gib_small_2.mdl", Vector(-3.7, -6.6, 5.9), Angle(-153.2, -0.7, -173.3))
Item = AddModel(Item, "models/Gibs/Antlion_gib_small_2.mdl", Vector(-4.1, 0.3, 2.8), Angle(-153.2, -0.7, 149.2))
Item = AddModel(Item, "models/Gibs/Antlion_gib_small_2.mdl", Vector(-7.7, -3.2, 6.6), Angle(-153.2, -0.7, 176))
Item = AddModel(Item, "models/Gibs/Antlion_gib_Large_1.mdl", Vector(5.2, -7, 8.1), Angle(162.6, -74.3, -67.6))
Item = AddModel(Item, "models/Gibs/Antlion_gib_small_2.mdl", Vector(5, -5.9, 1.2), Angle(-170.6, -0.7, 180))
Item = AddModel(Item, "models/Gibs/Antlion_gib_small_2.mdl", Vector(4.1, -1.4, -0.1), Angle(-172, 0.7, 157.2))
Item = AddStats(Item, "slot_chest", 48)
Item = AddBuff(Item, "stat_maxhealth", 17)
Item.Level = 25
Item.Weight = 5
Item.SellPrice = 9020
Item.Set = "armor_antlion"
Register.Item(Item)
local Item = QuickCreateItemTable(BaseArmor, "armor_chest_skele", "Bone Chest", "How many people died to make this...", "icons/junk_box1")
Item = AddModel(Item, "models/Gibs/HGIBS.mdl", Vector(1.9, -3.5, 2.8), Angle(6, -0.7, -0.7))
Item = AddModel(Item, "models/Gibs/HGIBS.mdl", Vector(1, 7.5, 0.3), Angle(3.3, 11.4, -3.3))
Item = AddModel(Item, "models/Gibs/HGIBS.mdl", Vector(2.8, 5.7, -5.2), Angle(3.3, 22.1, 2))
Item = AddModel(Item, "models/Gibs/HGIBS.mdl", Vector(1, 1, -5.2), Angle(3.3, -14.1, 3.3))
Item = AddModel(Item, "models/Gibs/manhack_gib05.mdl", Vector(12.2, -6.6, -3.5), Angle(139.9, -15.4, 87.7))
Item = AddModel(Item, "models/Gibs/manhack_gib05.mdl", Vector(11.5, -4.1, -2.8), Angle(149.2, 12.7, 87.7))
Item = AddModel(Item, "models/Gibs/manhack_gib05.mdl", Vector(14.2, -1.7, -4.3), Angle(134.5, 3.3, 87.7))
Item = AddStats(Item, "slot_chest", 62)
Item = AddBuff(Item, "stat_strength", 23)
Item.Level = 32
Item.Weight = 7
Item.SellPrice = 24156
Register.Item(Item)
local Item = QuickCreateItemTable(BaseArmor, "armor_chest_bio", "Chest Enhancers of the Overseer", "Created from light and durable metal, increases ranged combat", "icons/junk_box1")
Item = AddModel(Item, "models/props_combine/tprotato2_chunk05.mdl", Vector(-3.3, 11.6, 16.4), Angle(19.4, -2, 147.9))--front
Item = AddModel(Item, "models/Gibs/manhack_gib01.mdl", Vector(-3.9, 14, -8), Angle(-138.5, 135.8, 114.4))
Item = AddModel(Item, "models/Gibs/manhack_gib01.mdl", Vector(-2.1, 21.1, 14), Angle(-142.5, 138.5, 34.1))
Item = AddModel(Item, "models/props_combine/tprotato2_chunk05.mdl", Vector(-12.8, 27.7, 24.1), Angle(-47.5, -159.9, -81))--back
Item = AddModel(Item, "models/Gibs/manhack_gib01.mdl", Vector(12.2, 19.3, 6.8), Angle(62.2, 131.8, -70.3))
Item = AddModel(Item, "models/Gibs/manhack_gib01.mdl", Vector(6.8, -5.1, -12.8), Angle(40.8, 145.2, 52.9))
Item = AddStats(Item, "slot_chest", 73)
Item = AddBuff(Item, "stat_dexterity", 35)
Item.Level = 42
Item.Weight = 1
Item.SellPrice = 26112
Register.Item(Item)
local Item = QuickCreateItemTable(BaseArmor, "armor_chest_tyrant", "Chest Armor of the Tyrant", "Made from the finest materials, for protection.", "icons/junk_box1")
Item = AddModel(Item, "models/props_combine/stalkerpod_lid.mdl", Vector(-4.6, -1.9, 1), Angle(50.2, 0.7, 7.4))--front
Item = AddModel(Item, "models/props_combine/stalkerpod_lid.mdl", Vector(0.1, 4.3, 0.6), Angle(180, -178.7, 169.3))
Item = AddModel(Item, "models/props_combine/stalkerpod_lid.mdl", Vector(-5.9, -1.9, 7.2), Angle(-82.3, 75.6, 105.1))
Item = AddModel(Item, "models/props_combine/stalkerpod_lid.mdl", Vector(-1.4, -3.5, 0.1), Angle(93, -161.3, 27.4))
Item = AddModel(Item, "models/props_combine/stalkerpod_lid.mdl", Vector(-1.7, 0.3, -0.6), Angle(77, -125.1, 54.2))--back
Item = AddModel(Item, "models/props_combine/stalkerpod_lid.mdl", Vector(-6.8, 2.1, 4.8), Angle(-163.9, -0.7, 7.4))
Item = AddStats(Item, "slot_chest", 97)
Item = AddBuff(Item, "stat_maxhealth", 70)
Item.Level = 45
Item.Weight = 8
Item.SellPrice = 27144
Register.Item(Item)
|
Locales['nl'] = {
['actions'] = 'acties',
['boss_menu'] = 'baas menu',
['money_generic'] = '€%s',
['deposit_amount'] = 'stort hoeveelheid',
['deposit_society_money'] = 'stort maatschappij geld',
['do_you_want_to_recruit'] = 'Wil je %s aannemen?',
['employee'] = 'werknemer',
['employee_list'] = 'werknemer lijst',
['employee_management'] = 'werknemer beheer',
['fire'] = 'ontslaan',
['grade'] = 'schaal',
['have_deposited'] = 'je hebt gestort ~r~$%s~s~',
['have_withdrawn'] = 'je hebt opgenomen ~g~$%s~s~',
['invalid_amount'] = 'ongeldige hoeveelheid',
['invalid_amount_max'] = 'dit salaris is niet toegestaan',
['no'] = 'nee',
['promote'] = 'promoveer',
['promote_employee'] = 'promoveer %s',
['recruit'] = 'werv',
['recruiting'] = 'werven',
['salary_amount'] = 'salaris hoeveelheid',
['salary_management'] = 'salaris beheer',
['wash_money'] = 'witwas geld',
['wash_money_amount'] = 'hoeveelheid om wit te wassen',
['withdraw_amount'] = 'opneem hoeveelheid',
['withdraw_society_money'] = 'neem maatschappelijk geld op',
['yes'] = 'ja',
['you_have'] = 'je hebt ~g~€%s~s~ staan in ~y~geld witwassen~s~ (24h).',
['you_have_laundered'] = 'je hebt je geld: ~g~€%s~s~ ~r~witgewassen~s~ ',
['you_have_hired'] = 'je bent gevraagt %s',
['you_have_been_hired'] = 'je bent aangenomen door %s',
['you_have_fired'] = 'je bent ontslagen %s',
['you_have_been_fired'] = 'je bent ondslagen van %s',
['you_have_promoted'] = 'je hebt gepromoveerd %s naar %s',
['you_have_been_promoted'] = 'je bent ~b~gepromoveerd~s~!',
}
|
require 'globals'
socket = require 'socket'
---- Networking ----
UDP = socket.udp()
UDP:settimeout(0)
UDP:setsockname('*', 12345)
---- Game managing ----
local players = {}
local roundCombination, roundStrongestCard, roundSequenceLength
local currentPlayerTurnIndex = 1
math.randomseed(os.time())
---- GUI ----
local suit = Suit.new()
--[[
local player = Player()
player:addCard(Card(CardRank.Ace, CardSuit.Spades))
player:addCard(Card(CardRank.Three, CardSuit.Spades))
player:addCard(Card(CardRank.Seven, CardSuit.Diamonds))
player:addCard(Card(CardRank.Seven, CardSuit.Clubs))
player:addCard(Card(CardRank.King, CardSuit.Hearts))
for i = 1, 5 do
print(tostring(player.cards[i].rank)..':'..tostring(player.cards[i].suit))
end
]]--
---- Server loop ----
function love.update(dt)
---- Receiving ----
repeat
local data, ip, port = UDP:receivefrom()
if data then
local command, index, params = data:match("^(%S*) (%S*) (.*)")
---- join ----
if command == 'join' then
local playerName = params:match('(%S*)')
print(playerName..' has joined')
local player = Player(playerName, ip, port)
table.insert(players, player)
if #players <= 4 then
UDP:sendto(
string.format('%s %d', 'confirmJoint', #players),
ip, port
)
elseif #players > 4 then
UDP:sendto(
string.format('%s %d', 'confirmJoint', 0),
ip, port
)
end
else
print("unrecognised command:", cmd)
end
elseif ip ~= 'timeout' then
error("Unknown network error: "..tostring(msg))
end
until not data
socket.sleep(0.02)
---- GUI ----
if #players >= 1 then
if suit:Button('START GAME', 10, 10, 100, 30).hit then
startGame()
updateGameState()
end
end
end
---- Start game
function startGame()
local deck = createDeck()
for i = 1, 13 do
for j = 1, #players do
local cardIndex = math.random(1, #deck)
local card = deck[cardIndex]
table.remove(deck, cardIndex)
UDP:sendto(
string.format('%s %d %d', 'addCard', card.rank, card.suit),
players[j].ip, players[j].port
)
end
end
currentPlayerTurnIndex = 1
end
function createDeck()
local deck = {}
for rank = 1, 13 do
for suit = 1, 4 do
local card = Card(rank, suit)
table.insert(deck, card)
end
end
return deck
end
function updateGameState()
local playersCardLeft = {}
for i = 1, 4 do
if players[i] ~= nil then
playersCardLeft[i] = #players[i].cards
else
playersCardLeft[i] = 0
end
end
local rank = tostring(roundStrongestCard ~= nil and roundStrongestCard.rank or nil)
local suit = tostring(roundStrongestCard ~= nil and roundStrongestCard.suit or nil)
for i = 1, #players do
UDP:sendto(
string.format('%s %d %s %s %s-%s %d-%d-%d-%d', 'update',
currentPlayerTurnIndex, tostring(roundCombination), tostring(roundSequenceLength),
rank, suit,
playersCardLeft[1], playersCardLeft[2], playersCardLeft[3], playersCardLeft[4]
),
players[i].ip, players[i].port
)
end
end
function love.draw()
suit:draw()
end
|
return {
["engine"]="luajittex",
["timings"]={
["arabic"]={
["list"]={ "arabtype", "husayni" },
["results"]={
["arabtype"]={
["context base"]=0.32,
["context node"]=7.167,
["context none"]=0.322,
["harfbuzz native"]=4.631,
["harfbuzz uniscribe"]=4.67,
},
["husayni"]={
["context base"]=0.35,
["context node"]=12.251,
["context none"]=0.351,
["harfbuzz native"]=15.279,
["harfbuzz uniscribe"]=15.253,
},
},
},
["latin"]={
["list"]={ "modern", "pagella", "dejavu", "cambria", "ebgaramond", "lucidaot" },
["results"]={
["cambria"]={
["context base"]=0.384,
["context node"]=1.17,
["context none"]=0.366,
["harfbuzz native"]=2.907,
["harfbuzz uniscribe"]=2.863,
},
["dejavu"]={
["context base"]=0.399,
["context node"]=0.985,
["context none"]=0.364,
["harfbuzz native"]=3.02,
["harfbuzz uniscribe"]=2.968,
},
["ebgaramond"]={
["context base"]=0.43,
["context node"]=1.323,
["context none"]=0.383,
["harfbuzz native"]=2.999,
["harfbuzz uniscribe"]=2.983,
},
["lucidaot"]={
["context base"]=0.414,
["context node"]=0.626,
["context none"]=0.422,
["harfbuzz native"]=2.606,
["harfbuzz uniscribe"]=2.594,
},
["modern"]={
["context base"]=0.418,
["context node"]=0.773,
["context none"]=0.383,
["harfbuzz native"]=3.074,
["harfbuzz uniscribe"]=3.049,
},
["pagella"]={
["context base"]=0.436,
["context node"]=0.803,
["context none"]=0.416,
["harfbuzz native"]=3.024,
["harfbuzz uniscribe"]=3.006,
},
},
},
["mixed"]={
["list"]={ "arabtype", "husayni" },
["results"]={
["arabtype"]={
["context base"]=0.572,
["context node"]=4.039,
["context none"]=0.602,
["harfbuzz native"]=3.69,
["harfbuzz uniscribe"]=3.686,
},
["husayni"]={
["context base"]=0.617,
["context node"]=5.943,
["context none"]=0.575,
["harfbuzz native"]=7.193,
["harfbuzz uniscribe"]=7.109,
},
},
},
},
}
|
-- If image name contains gray, use grayscale effect
if string.match(imageCtx:name(), "gray") then
imageCtx:grayscale()
end
-- If image name contains blue, use gaussian blur effect
if string.match(imageCtx:name(), "blur") then
imageCtx:gaussianBlur(3.0)
end
|
local json = require "cjson"
local http_client = require "kong.tools.http_client"
local spec_helper = require "spec.spec_helpers"
local cache = require "kong.tools.database_cache"
local rex = require "rex_pcre"
local STUB_GET_URL = spec_helper.STUB_GET_URL
local PROXY_SSL_URL = spec_helper.PROXY_SSL_URL
local API_URL = spec_helper.API_URL
local env = spec_helper.get_env() -- test environment
local dao_factory = env.dao_factory
local configuration = env.configuration
configuration.cassandra = configuration[configuration.database].properties
describe("OAuth2 Authentication Hooks", function()
setup(function()
spec_helper.prepare_db()
end)
teardown(function()
spec_helper.stop_kong()
end)
before_each(function()
spec_helper.restart_kong()
spec_helper.drop_db()
spec_helper.insert_fixtures {
api = {
{ request_host = "oauth2.com", upstream_url = "http://mockbin.com" }
},
consumer = {
{ username = "auth_tests_consumer" }
},
plugin = {
{ name = "oauth2", config = { scopes = { "email", "profile" }, mandatory_scope = true, provision_key = "provision123", token_expiration = 5, enable_implicit_grant = true }, __api = 1 }
},
oauth2_credential = {
{ client_id = "clientid123", client_secret = "secret123", redirect_uri = "http://google.com/kong", name="testapp", __consumer = 1 }
}
}
end)
local function provision_code(client_id)
local response = http_client.post(PROXY_SSL_URL.."/oauth2/authorize", { provision_key = "provision123", client_id = client_id, scope = "email", response_type = "code", state = "hello", authenticated_userid = "userid123" }, {host = "oauth2.com"})
local body = json.decode(response)
if body.redirect_uri then
local matches = rex.gmatch(body.redirect_uri, "^http://google\\.com/kong\\?code=([\\w]{32,32})&state=hello$")
local code
for line in matches do
code = line
end
local data = dao_factory.oauth2_authorization_codes:find_all({code = code})
return data[1].code
end
end
describe("OAuth2 Credentials entity invalidation", function()
it("should invalidate when OAuth2 Credential entity is deleted", function()
-- It should work
local code = provision_code("clientid123")
local _, status = http_client.post(PROXY_SSL_URL.."/oauth2/token", { code = code, client_id = "clientid123", client_secret = "secret123", grant_type = "authorization_code" }, {host = "oauth2.com"})
assert.are.equal(200, status)
-- Check that cache is populated
local cache_key = cache.oauth2_credential_key("clientid123")
local _, status = http_client.get(API_URL.."/cache/"..cache_key)
assert.equals(200, status)
-- Retrieve credential ID
local response, status = http_client.get(API_URL.."/consumers/auth_tests_consumer/oauth2/")
assert.equals(200, status)
local credential_id = json.decode(response).data[1].id
assert.truthy(credential_id)
-- Delete OAuth2 credential (which triggers invalidation)
local _, status = http_client.delete(API_URL.."/consumers/auth_tests_consumer/oauth2/"..credential_id)
assert.equals(204, status)
-- Wait for cache to be invalidated
local exists = true
while(exists) do
local _, status = http_client.get(API_URL.."/cache/"..cache_key)
if status ~= 200 then
exists = false
end
end
-- It should not work
local code = provision_code("clientid123")
local _, status = http_client.post(PROXY_SSL_URL.."/oauth2/token", { code = code, client_id = "clientid123", client_secret = "secret123", grant_type = "authorization_code" }, {host = "oauth2.com"})
assert.are.equal(400, status)
end)
it("should invalidate when OAuth2 Credential entity is updated", function()
-- It should work
local code = provision_code("clientid123")
local _, status = http_client.post(PROXY_SSL_URL.."/oauth2/token", { code = code, client_id = "clientid123", client_secret = "secret123", grant_type = "authorization_code" }, {host = "oauth2.com"})
assert.are.equal(200, status)
-- It should not work
local code = provision_code("updclientid123")
local _, status = http_client.post(PROXY_SSL_URL.."/oauth2/token", { code = code, client_id = "updclientid123", client_secret = "secret123", grant_type = "authorization_code" }, {host = "oauth2.com"})
assert.are.equal(400, status)
-- Check that cache is populated
local cache_key = cache.oauth2_credential_key("clientid123")
local _, status = http_client.get(API_URL.."/cache/"..cache_key)
assert.equals(200, status)
-- Retrieve credential ID
local response, status = http_client.get(API_URL.."/consumers/auth_tests_consumer/oauth2/")
assert.equals(200, status)
local credential_id = json.decode(response).data[1].id
assert.truthy(credential_id)
-- Update OAuth2 credential (which triggers invalidation)
local _, status = http_client.patch(API_URL.."/consumers/auth_tests_consumer/oauth2/"..credential_id, {client_id="updclientid123"})
assert.equals(200, status)
-- Wait for cache to be invalidated
local exists = true
while(exists) do
local _, status = http_client.get(API_URL.."/cache/"..cache_key)
if status ~= 200 then
exists = false
end
end
-- It should work
local code = provision_code("updclientid123")
local _, status = http_client.post(PROXY_SSL_URL.."/oauth2/token", { code = code, client_id = "updclientid123", client_secret = "secret123", grant_type = "authorization_code" }, {host = "oauth2.com"})
assert.are.equal(200, status)
-- It should not work
local code = provision_code("clientid123")
local _, status = http_client.post(PROXY_SSL_URL.."/oauth2/token", { code = code, client_id = "clientid123", client_secret = "secret123", grant_type = "authorization_code" }, {host = "oauth2.com"})
assert.are.equal(400, status)
end)
end)
describe("Consumer entity invalidation", function()
it("should invalidate when Consumer entity is deleted", function()
-- It should work
local code = provision_code("clientid123")
local _, status = http_client.post(PROXY_SSL_URL.."/oauth2/token", { code = code, client_id = "clientid123", client_secret = "secret123", grant_type = "authorization_code" }, {host = "oauth2.com"})
assert.are.equal(200, status)
-- Check that cache is populated
local cache_key = cache.oauth2_credential_key("clientid123")
local _, status = http_client.get(API_URL.."/cache/"..cache_key)
assert.equals(200, status)
-- Delete Consumer (which triggers invalidation)
local _, status = http_client.delete(API_URL.."/consumers/auth_tests_consumer")
assert.equals(204, status)
-- Wait for cache to be invalidated
local exists = true
while(exists) do
local _, status = http_client.get(API_URL.."/cache/"..cache_key)
if status ~= 200 then
exists = false
end
end
-- It should not work
local code = provision_code("clientid123")
local _, status = http_client.post(PROXY_SSL_URL.."/oauth2/token", { code = code, client_id = "clientid123", client_secret = "secret123", grant_type = "authorization_code" }, {host = "oauth2.com"})
assert.are.equal(400, status)
end)
end)
describe("OAuth2 access token entity invalidation", function()
it("should invalidate when OAuth2 token entity is deleted", function()
-- It should work
local code = provision_code("clientid123")
local response, status = http_client.post(PROXY_SSL_URL.."/oauth2/token", { code = code, client_id = "clientid123", client_secret = "secret123", grant_type = "authorization_code" }, {host = "oauth2.com"})
assert.are.equal(200, status)
local token = json.decode(response)
assert.truthy(token)
local _, status = http_client.post(STUB_GET_URL, { access_token = token.access_token }, {host = "oauth2.com"})
assert.are.equal(200, status)
-- Check that cache is populated
local cache_key = cache.oauth2_token_key(token.access_token)
local _, status = http_client.get(API_URL.."/cache/"..cache_key)
assert.equals(200, status)
-- Delete token (which triggers invalidation)
local res = dao_factory.oauth2_tokens:find_all({access_token=token.access_token})
local token_id = res[1].id
assert.truthy(token_id)
local _, status = http_client.delete(API_URL.."/oauth2_tokens/"..token_id)
assert.equals(204, status)
-- Wait for cache to be invalidated
local exists = true
while(exists) do
local _, status = http_client.get(API_URL.."/cache/"..cache_key)
if status ~= 200 then
exists = false
end
end
-- It should not work
local _, status = http_client.post(STUB_GET_URL, { access_token = token.access_token }, {host = "oauth2.com"})
assert.are.equal(401, status)
end)
it("should invalidate when Oauth2 token entity is updated", function()
-- It should work
local code = provision_code("clientid123")
local response, status = http_client.post(PROXY_SSL_URL.."/oauth2/token", { code = code, client_id = "clientid123", client_secret = "secret123", grant_type = "authorization_code" }, {host = "oauth2.com"})
assert.are.equal(200, status)
local token = json.decode(response)
assert.truthy(token)
local _, status = http_client.post(STUB_GET_URL, { access_token = token.access_token }, {host = "oauth2.com"})
assert.are.equal(200, status)
-- It should not work
local _, status = http_client.post(STUB_GET_URL, { access_token = "hello_token" }, {host = "oauth2.com"})
assert.are.equal(401, status)
-- Check that cache is populated
local cache_key = cache.oauth2_token_key(token.access_token)
local _, status = http_client.get(API_URL.."/cache/"..cache_key)
assert.equals(200, status)
-- Update OAuth 2 token (which triggers invalidation)
local res = dao_factory.oauth2_tokens:find_all({access_token=token.access_token})
local token_id = res[1].id
assert.truthy(token_id)
local _, status = http_client.patch(API_URL.."/oauth2_tokens/"..token_id, {access_token="hello_token"})
assert.equals(200, status)
-- Wait for cache to be invalidated
local exists = true
while(exists) do
local _, status = http_client.get(API_URL.."/cache/"..cache_key)
if status ~= 200 then
exists = false
end
end
-- It should work
local _, status = http_client.post(STUB_GET_URL, { access_token = "hello_token" }, {host = "oauth2.com"})
assert.are.equal(200, status)
-- It should not work
local _, status = http_client.post(STUB_GET_URL, { access_token = token.access_token }, {host = "oauth2.com"})
assert.are.equal(401, status)
end)
end)
describe("OAuth2 client entity invalidation", function()
it("should invalidate token when OAuth2 client entity is deleted", function()
-- It should work
local code = provision_code("clientid123")
local response, status = http_client.post(PROXY_SSL_URL.."/oauth2/token", { code = code, client_id = "clientid123", client_secret = "secret123", grant_type = "authorization_code" }, {host = "oauth2.com"})
assert.are.equal(200, status)
local token = json.decode(response)
assert.truthy(token)
local _, status = http_client.post(STUB_GET_URL, { access_token = token.access_token }, {host = "oauth2.com"})
assert.are.equal(200, status)
-- Check that cache is populated
local cache_key = cache.oauth2_token_key(token.access_token)
local _, status = http_client.get(API_URL.."/cache/"..cache_key)
assert.equals(200, status)
-- Retrieve credential ID
local response, status = http_client.get(API_URL.."/consumers/auth_tests_consumer/oauth2/", {client_id="clientid123"})
assert.equals(200, status)
local credential_id = json.decode(response).data[1].id
assert.truthy(credential_id)
-- Delete OAuth2 client (which triggers invalidation)
local _, status = http_client.delete(API_URL.."/consumers/auth_tests_consumer/oauth2/"..credential_id)
assert.equals(204, status)
-- Wait for cache to be invalidated
local exists = true
while(exists) do
local _, status = http_client.get(API_URL.."/cache/"..cache_key)
if status ~= 200 then
exists = false
end
end
-- It should not work
local _, status = http_client.post(STUB_GET_URL, { access_token = token.access_token }, {host = "oauth2.com"})
assert.are.equal(401, status)
end)
end)
end)
|
local skynet = require "skynet"
local opcua = require "opcua"
local session_state = {
[0] = "Closed",
[1] = "Create requested",
[2] = "Created",
[3] = "Activate requested",
[4] = "Activated",
[5] = "Closing"
}
local channel_state = {
[0] = "Closed",
[1] = "Hello sent",
[2] = "Hello received",
[3] = "Ack sent",
[4] = "Ack received",
[5] = "Open sent",
[6] = "Open",
[7] = "Closing"
}
local security_policy_prefix = "http://opcfoundation.org/UA/SecurityPolicy#"
local security_policy = {
none = security_policy_prefix.."None",
basic128rsa15 = security_policy_prefix.."Basic128Rsa15",
basic256 = security_policy_prefix.."Basic256",
basic256sha256 = security_policy_prefix.."Basic256Sha256"
}
local security_mode = {
none = 1,
sign = 2,
signandencrypt = 3
}
local errinfo = {
not_registered = "node not registered",
invalid_datatype = "invalid datatype"
}
local uri = "urn:iotedge:opcua:opcua-client"
local root = "./lualib/opcua/"
local cert = root.."client.crt.der"
local key = root.."client.key.der"
local function read_file(file)
local f = io.open(file, "rb")
local ret = f:read("a")
f:close()
return ret
end
local function register_node(self)
for _, node in pairs(self.__nodelist) do
local ok, id, dtidx, dtname = self.__client:register(node.node)
if ok then
node.id = id
node.dtidx = dtidx
node.dtname = dtname
else
skynet.error("opcua: register node failed", node.name, id)
end
end
end
local function do_connect(self)
if not self.__connecting then
self.__connecting = true
local ok, err
if self.__username ~= '' and self.__password ~= '' then
ok, err = self.__client:connect_username(self.__config.url, self.__config.namespace, self.__username, self.__password)
else
ok, err = self.__client:connect(self.__config.url, self.__config.namespace)
end
if ok then
register_node(self)
skynet.error("opcua: connected to", self.__config.url, self.__config.namespace)
else
skynet.error("opcua: connect failed", self.__config.url, self.__config.namespace, err)
skynet.sleep(1000)
end
self.__connecting = false
return ok
else
return true
end
end
local function write_boolean(cli, id, dt, val)
if type(val) == "boolean" then
return cli:write_boolean(id, dt, val)
else
return false, errinfo.invalid_datatype
end
end
local function write_integer(cli, id, dt, val)
if math.tointeger(val) then
return cli:write_integer(id, dt, val)
else
return false, errinfo.invalid_datatype
end
end
local function write_float(cli, id, dt, val)
if type(val) == "number" then
return cli:write_float(id, dt, val)
else
return false, errinfo.invalid_datatype
end
end
local function write_double(cli, id, dt, val)
if type(val) == "number" then
return cli:write_double(id, dt, val)
else
return false, errinfo.invalid_datatype
end
end
local function write_string(cli, id, dt, val)
if type(val) == "string" then
return cli:write_string(id, dt, val)
else
return false, errinfo.invalid_datatype
end
end
local dt_map = {
[0] = write_boolean,
[1] = write_integer,
[2] = write_integer,
[3] = write_integer,
[4] = write_integer,
[5] = write_integer,
[6] = write_integer,
[7] = write_integer,
[8] = write_integer,
[9] = write_float,
[10] = write_double,
[11] = write_string,
}
local cli = {}
function cli:info()
local channel, session, connection = self.__client:state()
self.__state.connection = connection
self.__state.channel = channel_state[channel]
self.__state.session = session_state[session]
return { state = self.__state, config = self.__config }
end
function cli:register(node)
local ok, id, dtidx, dtname = self.__client:register(node.node)
if ok then
node.id = id
node.dtidx = dtidx
node.dtname = dtname
self.__nodelist[node.name] = node
return ok
else
return ok, id
end
end
function cli:read(nodelist)
local ok, ret = self.__client:read(nodelist)
if not ok then
skynet.timeout(0, function() do_connect(self) end)
end
return ok, ret
end
function cli:write(node, val)
if node.id then
local f = dt_map[node.dtidx]
if f then
local ok, ret = f(self.__client, node.id, node.dtidx, val)
if not ok and ret ~= errinfo.invalid_datatype then
skynet.timeout(0, function() do_connect(self) end)
end
return ok, ret
else
return false, errinfo.invalid_datatype
end
else
return false, errinfo.not_registered
end
end
function cli:connect()
return do_connect(self)
end
function cli:close()
local ok, err = self.__client:disconnect()
if ok then
skynet.error("opcua: disconnected", self.__config.url, self.__config.namespace)
else
skynet.error("opcua: disconnect failed", self.__config.url, self.__config.namespace, err)
end
return ok
end
local client_meta = {
__index = cli
}
local client = {}
function client.new(desc)
assert(desc.url and desc.namespace)
local c = assert(read_file(cert))
local k = assert(read_file(key))
local s_mode = assert(security_mode[desc.security_mode])
local s_policy = assert(security_policy[desc.security_policy])
local opcua_c = assert(opcua.client.new(uri, s_mode, s_policy, c, k))
local config = opcua_c:configuration()
config.security_mode = desc.security_mode
config.security_policy = desc.security_policy
config.url = desc.url
config.namespace = desc.namespace
return setmetatable({
__client = opcua_c,
__username = desc.username,
__password = desc.password,
__nodelist = {},
__state = {},
__config = config,
__connecting = false
}, client_meta)
end
return client
|
local FileModder = pd.Class:new():register("vidya-file-modder")
function FileModder:initialize(sel, atoms)
-- 1. Object-triggering bang
-- 2. Incoming single data bytes from [binfile]
-- 3. Total bytes in file, from [route buflength]
-- 4. Glitch type
-- 5. Glitch point
-- 6. Number of times to glitch a file
-- 7. Toggle for a randomized number of glitches within the bounds of (6)
-- 8. Active filename
self.inlets = 8
-- 1. To [binfile] inlet - bang(get next byte), clear(clear the buffer), FLOAT(write a byte to buffer), write(write to file)
self.outlets = 1
-- Currently active file's namedata
self.filedata = {
"default-filename",
0,
}
-- Glitch type (pattern, random, or splice)
self.glitchtype = "random"
-- Minimum glitch point in image data
self.glitchpoint = 500
-- Number of times to repeat random glitches on a given file
self.randrepeat = 1
-- Toggles whether the number of repeating glitches should be random, within the bounds of 1 to self.randrepeat
self.randtoggle = "concrete"
-- Hold all bytes, which are converted to ints in the 0-255 range
self.bytebuffer = {}
-- Buffer length of currently active file
self.buflength = 0
return true
end
function FileModder:in_1_bang()
for i = 1, self.buflength do
self:outlet(1, "bang", {})
end
self:outlet(1, "clear", {})
if self.glitchtype == "pattern" then
local plen = math.random(2, 1000)
local patbuffer = {}
for i = 1, plen do
table.insert(patbuffer, math.random(1, 254))
end
for i = self.glitchpoint, self.buflength do
self.bytebuffer[i] = patbuffer[((i - 1) % #patbuffer) + 1]
end
elseif self.glitchtype == "random" then
local randlimit = 0
if self.randtoggle == "random" then
randlimit = math.random(1, self.randrepeat)
else
randlimit = self.randrepeat
end
for i = 1, randlimit do
self.bytebuffer[math.random(self.glitchpoint, self.buflength)] = math.random(1, 244)
end
elseif self.glitchtype == "splice" then
local sloc = math.random(self.glitchpoint, self.buflength)
local schunksize = math.random(1, self.buflength - sloc)
local splicebuffer = {}
for i = 1, schunksize do
table.insert(splicebuffer, table.remove(self.bytebuffer, sloc))
end
local insertpoint = math.random(self.glitchpoint, #self.bytebuffer)
for _, v in ipairs(splicebuffer) do
table.insert(self.bytebuffer, insertpoint, v)
end
end
for _, v in ipairs(self.bytebuffer) do
self:outlet(1, "float", {v})
end
local outname = self.filedata[1] .. "-glitch" .. self.filedata[2] .. ".jpeg"
self:outlet(1, "write", {outname})
pd.post("New glitched image: " .. outname)
self:outlet(1, "clear", {})
self.bytebuffer = {}
end
function FileModder:in_2_float(f)
table.insert(self.bytebuffer, f)
end
function FileModder:in_3_list(f)
self.buflength = f[1] + 1 -- Shift from 0-indexed to 1-indexed
end
function FileModder:in_4_list(d)
self.glitchtype = d[1]
end
function FileModder:in_5_float(f)
self.glitchpoint = f
end
function FileModder:in_6_float(f)
self.randrepeat = f
end
function FileModder:in_7_list(d)
self.randtoggle = d[1]
end
function FileModder:in_8_list(d)
self.filedata = {d[1], d[2]}
end
|
-- See LICENSE for terms
local RetName = ChoGGi.ComFuncs.RetName
local ChoOrig_Workplace_AddWorker = Workplace.AddWorker
function Workplace:AddWorker(worker, ...)
-- already named, so abort
if self.ChoGGi_AddedNamedWorkplace then
return ChoOrig_Workplace_AddWorker(self, worker, ...)
end
local name = worker.name
self.display_name = T{302535920011335,"<name>'s <workplace>, est. <sol>",
name = type(name) == "table"
-- first name for eng, or "last" name for rtl (assuming that's how the devs did them)
and name[config.TextWrapAnywhere and #name or 1]
-- user added a custom name? don't bother trying to get a first name and just use it as is
or name,
workplace = RetName(self) or "Thppt!",
sol = (self.city or UICity).day,
}
self.ChoGGi_AddedNamedWorkplace = true
return ChoOrig_Workplace_AddWorker(self, worker, ...)
end
|
AddCSLuaFile()
DEFINE_BASECLASS( "magic_base_entity" )
ENT.PrintName = "Waterball"
ENT.Spawnable = false
ENT.AdminOnly = false
PrecacheParticleSystem("waterball")
if SERVER
then
function ENT:Initialize()
self.BaseClass.Initialize(self)
self:SetEffect("waterball")
self:PhysicsInitSphere(32, "default")
self:DrawShadow(false)
end
function ENT:OnCollision(e)
self:EmitSound("^weapons/underwater_explode4.wav", nil, 216)
for k, v in ipairs(ents.FindInSphere(self:GetPos(), 200))
do
v:SetWet(true)
end
self:Remove()
end
else
local function onCollision(part, pos, normal)
part:SetDieTime(0)
sound.Play("ambient/water/water_splash" .. math.random(1, 3) .. ".wav", pos, 75, 100, 0.5)
local part = MagicParticleEmitter3D:Add("particle/particle_noisesphere", pos + normal)
if part
then
part:SetDieTime(2)
part:SetStartAlpha(255)
part:SetEndAlpha(0)
part:SetStartSize(120)
part:SetEndSize(0)
part:SetAngles(normal:Angle())
end
end
function ENT:OnRemove()
for i=1, 15
do
local part = MagicParticleEmitter:Add("particle/particle_noisesphere", self:GetPos())
if part
then
part:SetDieTime(1)
part:SetStartAlpha(255)
part:SetEndAlpha(0)
part:SetStartSize(130)
part:SetEndSize(120)
part:SetCollide(true)
part:SetCollideCallback(onCollision)
part:SetRoll(i * 45)
part:SetRollDelta(5)
part:SetVelocity(VectorRand() * 305)
part:SetGravity(Vector(0, 0, -1000))
end
end
end
local function onCollision(part, pos, normal)
part:SetDieTime(0)
sound.Play("ambient/water/water_splash" .. math.random(1, 3) .. ".wav", pos, 75, 100, 0.1)
local part = MagicParticleEmitter3D:Add("particle/particle_noisesphere", pos + normal)
if part
then
part:SetDieTime(2)
part:SetStartAlpha(255)
part:SetEndAlpha(0)
part:SetStartSize(40)
part:SetEndSize(0)
part:SetAngles(normal:Angle())
end
end
function ENT:Draw()
end
function ENT:Think()
local part = MagicParticleEmitter:Add("particle/water/watersplash_001a_refract.vmt", self:GetPos())
if part
then
part:SetDieTime(10)
part:SetStartAlpha(100)
part:SetEndAlpha(0)
part:SetStartSize(30)
part:SetEndSize(30)
part:SetCollide(true)
part:SetCollideCallback(onCollision)
part:SetGravity(Vector(0, 0, -1000))
part:SetVelocity(VectorRand() * 15)
end
self:SetNextClientThink(CurTime() + math.Rand(0.1, 0.2))
end
end
|
RegisterServerEvent("rent:payMyBike")
AddEventHandler("rent:payMyBike", function(price)
print(type(source))
print(source)
source = tonumber(source)
TriggerEvent("es:getPlayerFromId", source, function(user)
if user.get('money') < price then
user.notify("<b style='color: red'> Tu n'as pas assez d'argent pour ça.</b>", "error", "topCenter", true, 5000)
else
print(user.getSessionVar("waitBike"))
print(os.time())
if user.getSessionVar("waitBike") == nil or (user.getSessionVar("waitBike") + 30) < os.time() then
user.removeMoney(price)
user.notify("<b style='color: green'> Et voilà! N'oublie pas ton casque de vélo!</b>", "success", "topCenter", true, 5000)
TriggerClientEvent("bike:okbuy", user.get('source'))
user.setSessionVar("waitBike", os.time())
else
user.notify("<b style='color: red' > Attend, je viens juste de t'en louer un! </b>", "error", "topCenter", true, 5000)
end
end
end)
end)
|
local marker = createMarker(1914.47,-2246.74,14,"cylinder",1,100,150,30,100)
function spray_markerHit(plr,matchingDimension)
if (not matchingDimension) then return end
local c = getElementData(plr,"character")
if (not c) then return end
if (getPlayerMoney(plr)<100) then
outputChatBox("Kupno puszki z sprayem kosztuje 100$, nie masz tylu.",plr,255,0,0,true)
return
end
if (tonumber(c.ab_spray or 0)<50) then
setElementData(plr,"drawtag:spraymode","none")
outputChatBox("Twoja umiejętność jest zbyt niska aby malować po ścianach.",plr)
outputChatBox("Zapoznaj się z poradnikiem obok, tam dowiesz się jak zwiększyć umiejętność.",plr)
else
setElementData(plr,"drawtag:spraymode","draw")
giveWeapon(plr,41,10000)
takePlayerMoney(plr,100)
outputChatBox("Aby rozpocząć malowanie, wciśnij 'N'.",plr)
end
end
addEventHandler("onMarkerHit",marker,spray_markerHit)
addEvent("onPlayerTakeWeapons",true)
addEventHandler("onPlayerTakeWeapons", root, function()
if getElementType(client)=="player" then
takeWeapon(client,41)
end
end)
|
local mustache = require("mustache")
local template = [[
<!DOCTYPE html>
<html{{#lang}} lang="{{lang}}"{{/lang}}>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="/w3.css" rel="stylesheet">
{{#favicon}}<link rel="icon" href="/fatcow/16/{{favicon}}.png">
{{/favicon}}<title>{{title}}</title>
{{#style}}
<style>
{{{style}}}
</style>
{{/style}}
{{#script}}
<script>
{{{script}}}
</script>
{{/script}}
</head>
<body{{#body}} class="{{body}}"{{/body}}>
{{{content}}}
</body>
</html>
]]
local function render(view)
return mustache.render(template, view)
end
return { render = render }
|
-- ---------------------------------------------------------------------------
-- Logging
local debug_level = 1
-- 3=err, 2=warn, 1=info, 0=debug
function debugLevel(level)
debug_level = level
end
local function cecho_tfcolors(msg)
msg = string.gsub(tf_text, '@{n}', '<reset>')
msg = string.gsub(tf_text, '@{Cbg([^}]*)}', '<:%1>')
msg = string.gsub(tf_text, '@{C([^}]*)}', '<%1>')
cecho(msg)
end
local function line()
echo('------------------------------------------------------------')
end
local function createLogger(komponente)
local kmp = '['..string.sub(komponente,1,5)..']'
kmp = kmp..string.sub(' ',1,7-#kmp)
return {
debug =
function(msg)
if debug_level <= 0 then
cecho('<grey>DEBUG '..kmp..' '..msg..'\n')
end
end,
info =
function(msg)
if debug_level <= 1 then
cecho('<cyan>>>> '..kmp..' '..msg..'\n')
end
end,
warn =
function(msg)
if debug_level <= 2 then
cecho('<yellow>>>> '..kmp..' '..msg..'\n')
end
end,
error =
function(msg)
cecho('<red>>>> '..kmp..' '..msg..'\n')
end
}
end
local logger = createLogger('mudlt')
-- ---------------------------------------------------------------------------
-- Events
local handler = {}
local function handleEventMitMudlet(event)
local allHandler = handler[event] or {}
for _,f in ipairs(allHandler) do
pcall(f)
end
end
local function registerEventHandler(event, f)
local handlerZumEvent = handler[event]
if handlerZumEvent == nil then
handlerZumEvent = {}
handler[event] = handlerZumEvent
-- event an normale mudlet-events haengen (mit neuen globalen functions)
local nameHandlerZuEvent = '_handleEventMitMudlet_'..string.gsub(event, '%.', '_')
_G[nameHandlerZuEvent] = function() handleEventMitMudlet(event) end
registerAnonymousEventHandler(event, nameHandlerZuEvent)
end
handlerZumEvent[#handlerZumEvent+1] = f
end
-- ---------------------------------------------------------------------------
-- Aliases
local alias_ids = {}
local alias_cmds = {}
function _executeAliasCmd(name, n, matches)
logger.debug('aufruf alias '..name..' mit '..n..' Parametern')
local aliasId = name..'~'..n
local cmd = alias_cmds[aliasId]
-- matches[2] ist der erste match
cmd(matches[2],matches[3],matches[4],matches[5],matches[6],matches[7],matches[8],matches[9])
end
-- Standard-Alias mit n Pflicht-Parametern erzeugen.
-- bei Eingabe von #name p1 ... pn wird f(p1,...,pn) aufgerufen
-- name~n muss eindeutig sein
-- return aliasID
local function createStandardAlias(name, n, f)
local pattern = '^#'..name
local aliasId = name..'~'..n
for _=1,n-1 do
pattern = pattern..'\\s+(\\S+)'
end
if n > 0 then
pattern = pattern..'\\s+(.*\\S)'
end
pattern = pattern..'\\s*$'
local code = [[_executeAliasCmd(']]..name..[[', ]]..n..[[, matches)]]
alias_cmds[aliasId] = f
local oldId = alias_ids[aliasId]
if (oldId ~= nil) then
killAlias(oldId)
end
local id = tempAlias(pattern, code)
alias_ids[aliasId] = id
return id
end
-- ---------------------------------------------------------------------------
-- Trigger
local trigger_id = 1 -- globaler counter
local trigger_cmds = {}
local styles = {
g = deleteLine,
green = function() fg('green') end,
yellow = function() fg('yellow') end,
red = function() fg('red') end,
blue = function() fg('blue') end,
}
local function callStyleFunctions(style)
for _,s in ipairs(style) do
local f = styles[s]
if f == nil then
logger.error('Style \''..s..'\' kann nicht uebersetzt werden!')
else
f()
end
end
resetFormat()
end
local function createStyleWrapper(style, f)
if style == nil then
return f
else
return
function()
pcall(f)
callStyleFunctions(style)
end
end
end
function _executeTriggerCmd(name)
local cmd = trigger_cmds[name]
cmd()
end
-- Erzeugung eines Triggers.
-- f: aufzurufende Funktion (kann lokal sein)
-- return triggerID
local function createSubstrTrigger(pattern, f, style, prio)
local name = 'lua_stdtrigger_'..trigger_id
trigger_id = trigger_id + 1
local code = [[_executeTriggerCmd(']]..name..[[')]]
local triggerID = tempTrigger(pattern, code)
trigger_cmds[name] = createStyleWrapper(style, f)
return triggerID
end
function _executeRegexTriggerCmd(name, matches)
local cmd = trigger_cmds[name]
-- matches[2] ist der erste match
cmd(matches[2],matches[3],matches[4],matches[5],matches[6],matches[7],matches[8],matches[9])
end
-- Erzeugung eines Triggers.
-- f: aufzurufende Funktion, aufgerufen wird f(p1,p2,p3,...) - pi ist match i
-- return triggerID
local function createRegexTrigger(pattern, f, style, prio)
local name = 'lua_retrigger_'..trigger_id
trigger_id = trigger_id + 1
local code = [[_executeRegexTriggerCmd(']]..name..[[', matches)]]
local triggerID = tempRegexTrigger(pattern, code)
trigger_cmds[name] = createStyleWrapper(style, f)
return triggerID
end
-- ---------------------------------------------------------------------------
-- Timer
local timer_id = 1
local timer_cmds = {}
function _execute_timer(id)
local f = timer_cmds[id]
timer_cmds[id] = nil
f()
end
local function createTimer(sec, f)
local id = 'timer'..timer_id
timer_id = timer_id + 1
timer_cmds[id] = f
tempTimer(sec, [[_execute_timer(']]..id..[[')]])
end
-- ---------------------------------------------------------------------------
-- send / eval
local function multi_send(...)
for _,msg in ipairs{...} do
send(msg)
end
end
local function eval(cmd)
if type(cmd) == 'function' then
cmd()
elseif type(cmd) == 'string' then
send(cmd)
end
end
local function xtitle(title)
end
-- ---------------------------------------------------------------------------
-- module definition
return {
createLogger = createLogger,
line = line,
echo = echo,
cecho = cecho_tfcolors,
registerEventHandler = registerEventHandler,
raiseEvent = raiseEvent,
createStandardAlias = createStandardAlias,
createSubstrTrigger = createSubstrTrigger,
createRegexTrigger = createRegexTrigger,
createMultiLineRegexTrigger = createRegexTrigger, -- TODO
enableTrigger = enableTrigger,
disableTrigger = disableTrigger,
killTrigger = killTrigger,
createTimer = createTimer,
send = multi_send,
eval = eval,
xtitle = xtitle,
}
|
AddCSLuaFile()
local DbgPrint = GetLogging("MapScript")
local MAPSCRIPT = {}
MAPSCRIPT.PlayersLocked = false
MAPSCRIPT.DefaultLoadout =
{
Weapons =
{
"weapon_lambda_medkit",
"weapon_crowbar",
"weapon_pistol",
},
Ammo =
{
["Pistol"] = 18,
},
Armor = 0,
HEV = true,
}
MAPSCRIPT.InputFilters =
{
}
MAPSCRIPT.EntityFilterByClass =
{
--["env_global"] = true,
}
MAPSCRIPT.EntityFilterByName =
{
["spawnitems_template"] = true,
}
function MAPSCRIPT:Init()
end
function MAPSCRIPT:PostInit()
if SERVER then
local checkpoint1 = GAMEMODE:CreateCheckpoint(Vector(-1183.380615, 6344.419922, -59.326172), Angle(0, -180, 0))
local checkpointTrigger1 = ents.Create("trigger_once")
checkpointTrigger1:SetupTrigger(
Vector(-1183.380615, 6344.419922, 6.326172),
Angle(0,0,0),
Vector(-100, -100, 0),
Vector(100, 100, 180)
)
checkpointTrigger1.OnTrigger = function(_, activator)
GAMEMODE:SetPlayerCheckpoint(checkpoint1, activator)
end
local checkpoint2 = GAMEMODE:CreateCheckpoint(Vector(-3002.406494, 7870.711426, 12.031250), Angle(0, 90, 0))
local checkpointTrigger2 = ents.Create("trigger_once")
checkpointTrigger2:SetupTrigger(
Vector(-3002.406494, 7870.711426, 48.031250),
Angle(0,0,0),
Vector(-100, -100, 0),
Vector(100, 100, 180)
)
checkpointTrigger2.OnTrigger = function(_, activator)
GAMEMODE:SetPlayerCheckpoint(checkpoint2, activator)
end
local checkpoint3 = GAMEMODE:CreateCheckpoint(Vector(2104.908447, 5759.881348, -95.968750), Angle(0, 45, 0))
local checkpointTrigger3 = ents.Create("trigger_once")
checkpointTrigger3:SetupTrigger(
Vector(2104.908447, 5759.881348, -95.968750),
Angle(0,0,0),
Vector(-100, -100, 0),
Vector(100, 100, 180)
)
checkpointTrigger3.OnTrigger = function(_, activator)
GAMEMODE:SetPlayerCheckpoint(checkpoint3, activator)
end
local npcMaker1 = ents.Create("npc_maker")
npcMaker1:SetPos(Vector(-2174.593262, 9086.971680, 288.031250))
npcMaker1:SetAngles(Angle(0, 180, 0))
npcMaker1:SetKeyValue("NPCType", "npc_metropolice")
npcMaker1:SetKeyValue("additionalequipment", "weapon_pistol")
npcMaker1:SetKeyValue("MaxNPCCount", "4")
npcMaker1:SetKeyValue("MaxLiveChildren", "4")
npcMaker1:SetKeyValue("StartDisabled", "1")
npcMaker1:SetKeyValue("NPCSquadName", "Overwatch")
npcMaker1:Spawn()
local npcMaker2 = ents.Create("npc_maker")
npcMaker2:SetPos(Vector(-3895.005615, 9614.399414, 288.031250))
npcMaker2:SetAngles(Angle(0, 180, 0))
npcMaker2:SetKeyValue("spawnflags", SF_NPCMAKER_HIDEFROMPLAYER + SF_NPCMAKER_ALWAYSUSERADIUS)
npcMaker2:SetKeyValue("NPCType", "npc_metropolice")
npcMaker2:SetKeyValue("additionalequipment", "weapon_pistol")
npcMaker2:SetKeyValue("MaxNPCCount", "2")
npcMaker2:SetKeyValue("MaxLiveChildren", "2")
npcMaker2:SetKeyValue("StartDisabled", "1")
npcMaker2:SetKeyValue("NPCSquadName", "Overwatch")
npcMaker2:SetKeyValue("Radius", "200")
npcMaker2:SetName("lambda_npc_maker2")
npcMaker2:Spawn()
-- gallery_destgroup_1
ents.WaitForEntityByName("gallery_destgroup_1", function(ent)
ent:SetPos(Vector(-47.880901, 6160.045898, -58.842937))
end, true)
-- room3_cop
-- Lets not wait for the explosion, thats boring.
ents.WaitForEntityByName("room3_cop", function(ent)
ent:Fire("AddOutput", "OnDeath gallerycop_maker2,Enable")
ent:Fire("AddOutput", "OnDeath gallerycop_maker3,Enable")
end)
ents.WaitForEntityByName("massacre_initiate_trigger", function(ent)
ent:Fire("AddOutput", "OnTrigger gallery_start_relay,Trigger,,0.0")
ent:Fire("AddOutput", "OnTrigger gallerycop_maker1,Enable,,0.0")
ent:Fire("AddOutput", "OnTrigger lambda_npc_maker2,Enable,,0.0")
end)
-- -2849.247314 8805.366211 47.039879
local trigger2 = ents.Create("trigger_once")
trigger2:SetupTrigger(
Vector(-2849.247314, 8805.366211, 47.039879),
Angle(0,0,0),
Vector(-150, -150, 0),
Vector(150, 150, 180)
)
trigger2.OnTrigger = function()
npcMaker1:Fire("Enable")
npcMaker2:Fire("Enable")
end
local BridgePositions =
{
Vector(-2809.293701, 6795.291992, 144.031250),
Vector(-2875.369141, 6793.270996, 144.031250),
Vector(-2960.664307, 6790.913574, 144.031250),
Vector(-3056.151855, 6790.148438, 144.031250),
Vector(-3138.704102, 6790.096191, 144.031250),
}
local function SendNPCToBridge(npc)
local bridgePos = table.Random(BridgePositions)
util.RunDelayed(function()
if not IsValid(npc) then
return
end
npc:SetLastPosition(bridgePos)
npc:SetSchedule(SCHED_FORCED_GO_RUN)
DbgPrint("Sending NPC to Bridge")
end, CurTime() + 1)
end
-- -2956.739746 6570.918945 -95.968781
local npcMaker3 = ents.Create("npc_maker")
npcMaker3:SetPos(Vector(-2264.835693, 6979.781250, 128.031250))
npcMaker3:SetAngles(Angle(0, 180, 0))
npcMaker3:SetKeyValue("spawnflags", SF_NPCMAKER_HIDEFROMPLAYER + SF_NPCMAKER_ALWAYSUSERADIUS)
npcMaker3:SetKeyValue("NPCType", "npc_metropolice")
npcMaker3:SetKeyValue("additionalequipment", "weapon_pistol")
npcMaker3:SetKeyValue("MaxNPCCount", "8")
npcMaker3:SetKeyValue("MaxLiveChildren", "2")
npcMaker3:SetKeyValue("StartDisabled", "1")
npcMaker3:SetKeyValue("NPCSquadName", "mudcopsquad")
--npcMaker4:SetKeyValue("Radius", "300")
npcMaker3:SetName("lambda_npc_maker3")
npcMaker3:Spawn()
npcMaker3.OnSpawnNPC = function(s, ent) SendNPCToBridge(ent) end
-- -3456.227539 6972.550293 128.031250
local npcMaker4 = ents.Create("npc_maker")
npcMaker4:SetPos(Vector(-3552.302979, 6977.757324, 128.031250))
npcMaker4:SetAngles(Angle(0, 180, 0))
npcMaker4:SetKeyValue("spawnflags", SF_NPCMAKER_HIDEFROMPLAYER)
npcMaker4:SetKeyValue("NPCType", "npc_metropolice")
npcMaker4:SetKeyValue("additionalequipment", "weapon_pistol")
npcMaker4:SetKeyValue("MaxNPCCount", "3")
npcMaker4:SetKeyValue("MaxLiveChildren", "1")
npcMaker4:SetKeyValue("StartDisabled", "1")
npcMaker4:SetKeyValue("NPCSquadName", "mudcopsquad")
--npcMaker5:SetKeyValue("Radius", "300")
npcMaker4:SetName("lambda_npc_maker4")
npcMaker4:Spawn()
npcMaker4.OnSpawnNPC = function(s, ent) SendNPCToBridge(ent) end
-- kill volume
local bridgeKillTrigger = ents.Create("trigger_multiple")
bridgeKillTrigger:SetupTrigger(
Vector(-2960.003174, 6840.497559, 144.057632),
Angle(0, 0, 0),
Vector(-300, -100, 0),
Vector(300, 100, 100)
)
bridgeKillTrigger:SetKeyValue("targetname", "lambda_bridge_killbox")
bridgeKillTrigger:SetKeyValue("StartDisabled", "1")
bridgeKillTrigger:SetKeyValue("spawnflags", SF_TRIGGER_ALLOW_NPCS)
bridgeKillTrigger.OnTrigger = function(ent)
DbgPrint("Killing all bridge NPCs")
local t = ent:GetTouchingObjects()
for _,v in pairs(t) do
DbgPrint("Killing: " .. tostring(v))
local world = game.GetWorld()
v:TakeDamage(1000, world, world)
end
ent.OnTrigger = nil
-- Lets block the bridge otherwise it looks silly.
local prop = ents.Create("prop_physics")
prop:SetModel("models/props_trainstation/train001.mdl")
prop:SetPos(Vector(-2950.885742, 6831.411621, 241.852402))
prop:SetAngles(Angle(0, 90, 0))
prop:SetCollisionGroup(COLLISION_GROUP_PASSABLE_DOOR)
prop:SetSolidFlags(FSOLID_NOT_SOLID)
prop:AddEffects(EF_NODRAW)
prop:Spawn()
local phys = prop:GetPhysicsObject()
if IsValid(phys) then
phys:EnableMotion(false)
end
end
-- -2620.882813 5306.772949 -45.723671
local trigger3 = ents.Create("trigger_once")
trigger3:SetupTrigger(
Vector(-2620.882813, 5306.772949, -45.723671),
Angle(0,0,0),
Vector(-150, -150, 0),
Vector(150, 150, 180)
)
trigger3.OnTrigger = function()
npcMaker3:Fire("Enable")
npcMaker4:Fire("Enable")
end
ents.WaitForEntityByName("mud_bridge_collapse_relay", function(ent)
ent:Fire("AddOutput", "OnTrigger lambda_bridge_killbox,Enable,,0")
end)
ents.WaitForEntityByName("mud_bridge_barrels", function(ent)
ent:Fire("AddOutput", "OnBreak lambda_npc_maker3,Kill,,0")
ent:Fire("AddOutput", "OnBreak lambda_npc_maker4,Kill,,0")
end)
end
end
function MAPSCRIPT:PostPlayerSpawn(ply)
--DbgPrint("PostPlayerSpawn")
end
return MAPSCRIPT
|
local XP_PER_DAY = 20
local XP_levels =
{
XP_PER_DAY*8,
XP_PER_DAY*16,
XP_PER_DAY*32,
XP_PER_DAY*48,
XP_PER_DAY*64,
XP_PER_DAY*80,
XP_PER_DAY*96,
-- XP_PER_DAY*112,
--50000, --
--100000, --
}
--Wes & Maxwell unlocked through other means.
local Level_rewards = {'willow', 'wolfgang', 'wendy', 'wx78', 'wickerbottom', 'woodie', 'wathgrithr'}
local Level_cap = #XP_levels
local function GetLevelForXP(xp)
local last = 0
for k,v in ipairs(XP_levels) do
if xp < v then
local percent = ((xp - last) / (v - last))
return k-1, percent
end
last = v
end
--at cap!
return #XP_levels, 0
end
return
{
GetXPCap = function()
return XP_levels[#XP_levels]
end,
GetRewardsForTotalXP = function(xp)
local level = math.min(GetLevelForXP(xp), Level_cap)
local rewards = {}
if level > 0 then
for k = 1, math.min(level, #Level_rewards) do
table.insert(rewards, Level_rewards[k])
end
end
return rewards
end,
GetRewardForLevel = function(level)
level = level + 1
if level > 0 and level <= #Level_rewards then
return Level_rewards[level]
end
end,
GetXPForDays = function(days)
return XP_PER_DAY*days
end,
GetXPForLevel = function(level)
if level == 0 then
return 0, XP_levels[1]
end
if level <= #XP_levels then
return XP_levels[level], level + 1 <= #XP_levels and (XP_levels[level + 1] - XP_levels[level]) or 0
end
end,
GetLevelForXP = function (xp)
return GetLevelForXP(xp)
end,
IsCappedXP = function(xp)
return xp >= XP_levels[#XP_levels]
end
}
|
--------------------------------
-- @module ArmatureDataManager
-- @extend Ref
-- @parent_module ccs
--------------------------------
--
-- @function [parent=#ArmatureDataManager] getAnimationDatas
-- @param self
-- @return map_table#map_table ret (return value: map_table)
--------------------------------
-- brief remove animation data<br>
-- param id the id of the animation data
-- @function [parent=#ArmatureDataManager] removeAnimationData
-- @param self
-- @param #string id
-- @return ArmatureDataManager#ArmatureDataManager self (return value: ccs.ArmatureDataManager)
--------------------------------
-- Add armature data<br>
-- param id The id of the armature data<br>
-- param armatureData ArmatureData *
-- @function [parent=#ArmatureDataManager] addArmatureData
-- @param self
-- @param #string id
-- @param #ccs.ArmatureData armatureData
-- @param #string configFilePath
-- @return ArmatureDataManager#ArmatureDataManager self (return value: ccs.ArmatureDataManager)
--------------------------------
-- @overload self, string, string, string
-- @overload self, string
-- @function [parent=#ArmatureDataManager] addArmatureFileInfo
-- @param self
-- @param #string imagePath
-- @param #string plistPath
-- @param #string configFilePath
-- @return ArmatureDataManager#ArmatureDataManager self (return value: ccs.ArmatureDataManager)
--------------------------------
--
-- @function [parent=#ArmatureDataManager] removeArmatureFileInfo
-- @param self
-- @param #string configFilePath
-- @return ArmatureDataManager#ArmatureDataManager self (return value: ccs.ArmatureDataManager)
--------------------------------
--
-- @function [parent=#ArmatureDataManager] getTextureDatas
-- @param self
-- @return map_table#map_table ret (return value: map_table)
--------------------------------
-- brief get texture data<br>
-- param id the id of the texture data you want to get<br>
-- return TextureData *
-- @function [parent=#ArmatureDataManager] getTextureData
-- @param self
-- @param #string id
-- @return TextureData#TextureData ret (return value: ccs.TextureData)
--------------------------------
-- brief get armature data<br>
-- param id the id of the armature data you want to get<br>
-- return ArmatureData *
-- @function [parent=#ArmatureDataManager] getArmatureData
-- @param self
-- @param #string id
-- @return ArmatureData#ArmatureData ret (return value: ccs.ArmatureData)
--------------------------------
-- brief get animation data from _animationDatas(Dictionary)<br>
-- param id the id of the animation data you want to get<br>
-- return AnimationData *
-- @function [parent=#ArmatureDataManager] getAnimationData
-- @param self
-- @param #string id
-- @return AnimationData#AnimationData ret (return value: ccs.AnimationData)
--------------------------------
-- brief add animation data<br>
-- param id the id of the animation data<br>
-- return AnimationData *
-- @function [parent=#ArmatureDataManager] addAnimationData
-- @param self
-- @param #string id
-- @param #ccs.AnimationData animationData
-- @param #string configFilePath
-- @return ArmatureDataManager#ArmatureDataManager self (return value: ccs.ArmatureDataManager)
--------------------------------
-- Init ArmatureDataManager
-- @function [parent=#ArmatureDataManager] init
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- brief remove armature data<br>
-- param id the id of the armature data you want to get
-- @function [parent=#ArmatureDataManager] removeArmatureData
-- @param self
-- @param #string id
-- @return ArmatureDataManager#ArmatureDataManager self (return value: ccs.ArmatureDataManager)
--------------------------------
--
-- @function [parent=#ArmatureDataManager] getArmatureDatas
-- @param self
-- @return map_table#map_table ret (return value: map_table)
--------------------------------
-- brief remove texture data<br>
-- param id the id of the texture data you want to get
-- @function [parent=#ArmatureDataManager] removeTextureData
-- @param self
-- @param #string id
-- @return ArmatureDataManager#ArmatureDataManager self (return value: ccs.ArmatureDataManager)
--------------------------------
-- brief add texture data<br>
-- param id the id of the texture data<br>
-- return TextureData *
-- @function [parent=#ArmatureDataManager] addTextureData
-- @param self
-- @param #string id
-- @param #ccs.TextureData textureData
-- @param #string configFilePath
-- @return ArmatureDataManager#ArmatureDataManager self (return value: ccs.ArmatureDataManager)
--------------------------------
-- brief Judge whether or not need auto load sprite file
-- @function [parent=#ArmatureDataManager] isAutoLoadSpriteFile
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- brief Add sprite frame to CCSpriteFrameCache, it will save display name and it's relative image name
-- @function [parent=#ArmatureDataManager] addSpriteFrameFromFile
-- @param self
-- @param #string plistPath
-- @param #string imagePath
-- @param #string configFilePath
-- @return ArmatureDataManager#ArmatureDataManager self (return value: ccs.ArmatureDataManager)
--------------------------------
--
-- @function [parent=#ArmatureDataManager] destroyInstance
-- @param self
-- @return ArmatureDataManager#ArmatureDataManager self (return value: ccs.ArmatureDataManager)
--------------------------------
--
-- @function [parent=#ArmatureDataManager] getInstance
-- @param self
-- @return ArmatureDataManager#ArmatureDataManager ret (return value: ccs.ArmatureDataManager)
return nil
|
local network_message = {}
network_message.encryptor = nil
network_message.decryptors = {}
network_message.addDecryptor = function(decryptor)
network_message.decryptors[decryptor.name] = decryptor
end
network_message.validateMessage = function(json)
if json == nil or json['protocol'] ~= PROTOCOL or type(json['targets']) ~= 'table' then
return false
end
isTarget = false
for k,v in pairs(json['targets']) do
if v == NODE_ID or v == 'ALL' then isTarget = true end
end
return isTarget
end
network_message.decodeMessage = function(message)
json = network_message.decrypt(message)
return json
end
network_message.decrypt = function(message)
ok, json = pcall(sjson.decode, message)
if not ok or not network_message.validateMessage(json) then
json = nil
else
if json["event"]:len() > 8 and json['event']:sub(0, 8) == "message." then
print ("enrypted via "..json['event'])
if network_message.decryptors[json['event']] ~= nil then
json = network_message.decryptors[json['event']].decrypt(json)
else
print("decoder not found")
json = nil
end
elseif not PROTOCOL_ALLOW_UNENCRYPTED then
print("unencrypted message dropped")
json = nil
end
end
return json
end
network_message.prepareMessage = function()
data = {}
data.protocol = PROTOCOL
data.node = NODE_ID
data.chip_id = node.chipid()
data.event = ''
data.response = ''
data.targets = {'ALL'}
return data
end
network_message.sendMessage = function(socket, message, port, ip)
json = network_message.encrypt(message)
if json then
print(json)
if port == nil then port = PORT end
if ip == nil then ip = wifi.sta.getbroadcast() end
socket:send(port, ip, json)
return true
end
return false
end
network_message.encrypt = function(message)
if network_message.encryptor then
message = network_message.encryptor.encrypt(message)
end
ok, json = pcall(sjson.encode, message)
if ok then
return json
end
return nil
end
return network_message
|
#!/usr/bin/env lua
-- MoonFLTK example: password.lua
fl = require("moonfltk")
ret = fl.password("password:", "myfavouritepetname")
print("password:", ret)
|
require("hall/main/data/hallDataInterface");
local ACTIVITYCENTER = 1; -- 活动中心页
local ACTIVITYRECOMMED = 2; -- 应用推荐页
ActivityScene = class(CommonScene);
ActivityScene.s_controls = {
backBtn = 1;
contentView = 2;
errorInfo = 3;
}
ActivityScene.s_cmds =
{
Back = 1,
LoadWebView = 2;
SetVisible = 3;
GetWebViewSize = 4;
DeleteActivityWebView = 5;
}
ActivityScene.ctor = function(self, viewConfig, controller)
local __isExist,__wnd = LayerManagerIsolater.getInstance():isExist("redenvelope_reciever");
if __isExist then
__wnd:setVisible(false);
end
RedEnvelopDataInterface.getInstance():setActivityShowing(true);
self.m_controller = controller;
self.m_ctrl = ActivityScene.s_controls;
self:findViews();
self:addListeners();
end
ActivityScene.dtor = function(self)
self:deleteActivityWebView();
RedEnvelopDataInterface.getInstance():setActivityShowing(false);
local __isExist,__wnd = LayerManagerIsolater.getInstance():isExist("redenvelope_reciever");
if __isExist then
__wnd:setVisible(true);
end
end
ActivityScene.stop = function(self)
CommonScene.stop(self);
self:deleteActivityWebView();
end
ActivityScene.resume = function(self)
CommonScene.resume(self);
HallDataInterface.getInstance():setWebViewShowing(true);
end
ActivityScene.pause = function(self)
CommonScene.pause(self);
HallDataInterface.getInstance():setWebViewShowing(false);
end
------------------------ 以下为外部调方法 ------------------------
-- 按下手机按下返回键时调用
ActivityScene.onBackKeyDown = function(self)
if self.m_activityCenterWebView then
return self.m_activityCenterWebView:goBackWebView();
end
return false;
end
ActivityScene.deleteActivityWebView = function(self)
delete(self.m_activityCenterWebView);
self.m_activityCenterWebView = nil;
end
------------------------ 以下为内部调方法 外部请不要调用 ------------------------
ActivityScene.findViews = function(self)
self.m_backBtn=self:findViewById(self.m_ctrl.backBtn); -- 顶部返回按扭
self.m_contentView = self:findViewById(self.m_ctrl.contentView); -- 页面内容view
self.m_errorInfo = self:findViewById(self.m_ctrl.errorInfo);
self.m_backBtn:setVisible(false);
end
ActivityScene.getWebViewSize = function(self)
local w,h = self.m_contentView:getSize();
local x,y = self.m_contentView:getAbsolutePos();
return w*System.getLayoutScale(), h*System.getLayoutScale(), x*System.getLayoutScale(), y*System.getLayoutScale();
end
ActivityScene.getBackBtnSize = function(self)
local w,h = self.m_backBtn:getSize();
local x,y = self.m_backBtn:getAbsolutePos();
return w*System.getLayoutScale(), h*System.getLayoutScale(), x*System.getLayoutScale(), y*System.getLayoutScale();
end
ActivityScene.addListeners = function(self)
self.m_backBtn:setOnClick(self, self.onBackBtnClick);
end
ActivityScene.init = function(self)
self.m_curPage = nil;
self:deleteActivityWebView();
self:showCenterWebView();
end
ActivityScene.onBackBtnClick = function(self)
self:requestCtrlCmd(ActivityController.s_cmds.Back);
end
ActivityScene.showCenterWebView = function(self)
if not self.m_activityCenterWebView then
self.m_activityCenterWebView = new( require("hall/widget/webView") );
local w, h, x, y = self:getWebViewSize();
local bw, bh, bx, by = self:getBackBtnSize();
self.m_activityCenterWebView:create(self:getUrl(), x, y, w, h, bx, by, bw, bh);
self.m_contentView:addChild(self.m_activityCenterWebView);
end
end
ActivityScene.getUrl = function(self)
local url = ActivityDataInterface.getInstance():getActivityUrl();
if string.isEmpty(url) then
url = string.format("http://mvsnspus01.ifere.com/dfqp/?app=%s&ssid=%s&action=activity.lists",kUserInfoData:getAppId(),kUserInfoData:getSsid());
end
return url;
end
ActivityScene.onLoadWebView = function(self, isSuccess, errStr)
if isSuccess then
self:init();
else
self.m_errorInfo:setVisible(true);
self.m_errorInfo:setText(errStr);
end
end
ActivityScene.s_controlConfig =
{
[ActivityScene.s_controls.backBtn] = {"topView" , "returnBtn"},
[ActivityScene.s_controls.contentView] = {"contentView"},
[ActivityScene.s_controls.errorInfo] = {"errorInfo"},
}
ActivityScene.s_cmdConfig =
{
[ActivityScene.s_cmds.Back] = ActivityScene.onBackBtnClick;
[ActivityScene.s_cmds.LoadWebView] = ActivityScene.onLoadWebView;
[ActivityScene.s_cmds.SetVisible] = ActivityScene.setVisible;
[ActivityScene.s_cmds.GetWebViewSize] = ActivityScene.getWebViewSize;
[ActivityScene.s_cmds.DeleteActivityWebView] = ActivityScene.deleteActivityWebView;
}
|
fx_version 'adamant'
game 'gta5'
client_scripts {
'@utils/client/vectors.lua',
'cl_config.lua',
'cl_components.lua',
'cl_states.lua',
'cl_ammo.lua',
'cl_preview.lua',
'cl_shooting.lua',
}
server_scripts {
'sv_weapons.lua',
}
|
-- Copyright (c) 2021 Kirazy
-- Part of Artisanal Reskins: Bob's Mods
--
-- See LICENSE in the project directory for license information.
-- Check to see if reskinning needs to be done.
if not (reskins.bobs and reskins.bobs.triggers.vehicle_equipment.equipment) then return end
local inputs = {
type = "belt-immunity-equipment",
icon_name = "vehicle-belt-immunity",
mod = "bobs",
group = "vehicle-equipment",
equipment_category = "utility",
icon_filename = "__base__/graphics/icons/belt-immunity-equipment.png",
icon_size = 64,
icon_mipmaps = 4,
}
local name = "vehicle-belt-immunity-equipment"
-- Reskin equipment; fetch the equipment
local equipment = data.raw[inputs.type][name]
-- Check if entity exists, if not, return
if not equipment then return end
-- Construct icon
reskins.lib.construct_icon(name, 0, inputs)
-- Reskin equipment
equipment.sprite = {
filename = "__base__/graphics/equipment/belt-immunity-equipment.png",
size = 32,
priority = "medium",
hr_version = {
filename = "__base__/graphics/equipment/hr-belt-immunity-equipment.png",
size = 64,
priority = "medium",
scale = 0.5
}
}
|
object_tangible_collection_gem_cylinder_hueable_01 = object_tangible_collection_shared_gem_cylinder_hueable_01:new {
gameObjectType = 8211,}
ObjectTemplates:addTemplate(object_tangible_collection_gem_cylinder_hueable_01, "object/tangible/collection/gem_cylinder_hueable_01.iff")
|
local vi = require('vimrocks.vi')
local path = require('vimrocks.path')
local function clean()
local dest = vi.call('shellescape', path.dest())
vi.command('silent ! rm -rf ' .. dest)
end
-- version number of (lua, jit)
local function lua_version()
local j
if jit and jit.version then
j = vi.split(jit.version, ' ')[2]
else
j = nil
end
local v = vi.split(_VERSION, ' ')[2]
return v, j
end
local function local_install_luarocks()
local function e(s) return vi.call('shellescape', s) end
local bin = path.join {path.dest(), 'py', 'bin'}
local pip = path.join {bin, 'pip'}
local hererocks = path.join {bin, 'hererocks'}
vi.command('silent ! mkdir -p ' .. e(path.dest()))
vi.command('! python -m venv ' .. e(path.join {path.dest(), 'py'}))
vi.command('! ' .. e(pip) .. ' install hererocks')
-- NOTE: vi.join space not work
-- vi.command(sp {'!', e(pip), 'install', 'hererocks'})
do
local cmd = '! ' .. e(hererocks) .. ' -rlatest'
local l, j = lua_version()
if j then
cmd = cmd .. ' -j' .. j
else
cmd = cmd .. ' -l' .. l
end
cmd = cmd .. ' ' .. e(path.luaenv())
vi.command(cmd)
end
end
local function luarocks_installed() return vi.filereadable(path.luarocks()) end
local function append_path()
local ver, _ = lua_version()
package.path = package.path .. ';' .. path.join {path.lualib(ver), '?.lua'}
package.cpath = package.cpath .. ';' .. path.join {path.lualib(ver), '?.so'}
end
local function luarocks(args)
local function e(s) return vi.call('shellescape', s) end
vi.command('! ' .. e(path.luarocks()) .. ' ' .. args)
end
return {
vi = vi,
path = path,
clean = clean,
lua_version = lua_version,
local_install_luarocks = local_install_luarocks,
luarocks_installed = luarocks_installed,
append_path = append_path,
luarocks = luarocks
}
|
WhiteList = {
"STEAM_0:0:90087002"
}
-- NOTES:
-- This whitelist is for defining the defaults when the "useWhiteList" flag is set in 'shared/Config.lua'
-- To adjust permissions or to force this specate view ingame, fire a "FreeCam" event on the server-side
-- with the following parameters:
-- args.player: player
-- args.perm: (optional) true: give player permission to (de)activate the view
-- false: remove permission from player to (de)activate the view
-- args.active: (optional) true: activate FreeCam for player
-- false: deactivate FreeCam for this player
-- args.restore: (optional) true: restore the default permission
-- For example: If you want to force this view to a specific player do:
-- Events:Fire("FreeCam", {["player"] = player,
-- ["perm"] = false,
-- ["active"] = true})
-- To restore the default do:
-- Events:Fire("FreeCam", {["player"] = player,
-- ["restore"] = true,
-- ["active"] = false})
|
--
-- Created by IntelliJ IDEA.
-- User: jon
-- Date: 11/5/11
-- Time: 9:53 AM
-- To change this template use File | Settings | File Templates.
--
local file = {}
function file:close() end
function file:flush() end
function file:lines() end
function file:read() end
function file:seek() end
function file:setvbuf() end
function file:write() end
module "io"
stdin = file
stdout = file
stderr = file
function open() return file end
function tmpfile() return file end
function close() end
function flush() end
function input() end
function lines() end
function output() end
function popen() end
function read() end
function type() end
function write() end
|
--------------------
-- GUI modification
--------------------
local _M = {}
local backend = require("textadept-spellchecker.backend")
local check = require("textadept-spellchecker.check")
local live = require("textadept-spellchecker.livechecking")
local config = require("textadept-spellchecker.config")
------------------------
-- On/Off spellchecking
------------------------
local on_off_msgs = {
[config.OFF] = _L["_SCON"],
[config.ON] = _L["_SCOFF"],
}
local on_off_live_msgs = {
[config.OFF] = _L["_LSCON"],
[config.ON] = _L["_LSCOFF"],
}
local function renew()
backend.kill_checker()
check.frame()
config:save()
end
local function toggle_spellchecking(current_check_state, fixed_live_state)
if current_check_state == config.ON then
current_check_state = config.OFF
check.shutdown()
live.shutdown()
else
current_check_state = config.ON
check.connect_events()
if fixed_live_state == config.ON then
live.init()
end
end
-- Changing messages and status in menu
textadept.menu.menubar[#textadept.menu.menubar-1][1][1] = on_off_msgs[current_check_state]
textadept.menu.menubar[#textadept.menu.menubar-1][2][1] = on_off_live_msgs[fixed_live_state]
config.checking = current_check_state
config.live = fixed_live_state
config:save()
end
local function toggle_live_spellchecking(current_live_state)
if current_live_state == config.ON then
current_live_state = config.OFF
live.shutdown()
else
current_live_state = config.ON
live.init()
end
-- Changing messages and status in menu
textadept.menu.menubar[#textadept.menu.menubar-1][2][1] = on_off_live_msgs[current_live_state]
config.live = current_live_state
config:save()
end
---------------------
-- Backend selection
---------------------
local function new_backend()
local input_box = {
title = _L["ENTER_SC_BACKEND"],
informative_text = _L["ENTER_SC_BACKEND_INFO"],
button2 = _L["_Cancel"],
float = true,
}
local status, command = ui.dialogs.inputbox(input_box)
if status == 1 then
if backend.check_backend(command) then
table.insert(backend.AVAILABLE_CHECKERS, command)
return command
else
ui.dialogs.ok_msgbox({
title = _L["PROBLEM"],
text = string.format(_L["NOT_BACKEND"], command),
no_cancel = true
})
end
end
return nil
end
local function backend_selector()
local backend_select_dialog = {
title = _L["SELECT_BACKEND"],
text = _L["SELECT_BACKEND_INFO"],
float = true,
button2 = _L["_Cancel"],
button3 = _L["_NOTINLIST"],
items = backend.AVAILABLE_CHECKERS,
select = config.CURRENT_CHECKER
}
local status = 0
local status, checker = ui.dialogs.dropdown(backend_select_dialog)
if status == 2 then
checker = nil
elseif status == 3 then
checker = new_backend()
end
if checker and checker ~= config.CURRENT_CHECKER then
config.CURRENT_CHECKER = checker or config.CURRENT_CHECKER
renew()
end
end
------------------------
-- Dictionary selection
------------------------
local function dictionary_selector()
local input_box = {
title = _L["ENTER_DICT"],
informative_text = _L["ENTER_DICT_INFO"],
button2 = _L["_Cancel"],
float = true,
text = config.dicts,
}
local status, dict = ui.dialogs.inputbox(input_box)
if status == 1 then
local status = backend.check_dict(dict)
if status == true then
config.dicts = dict
renew()
else
ui.dialogs.ok_msgbox({
title = _L["PROBLEM"],
text = string.format(_L["NOT_DICT"], dict, backend.AVAILABLE_CHECKERS[config.CURRENT_CHECKER]),
no_cancel = true
})
end
end
end
-------------
-- Root menu
-------------
function _M.init()
local spellcheck_menu = {
title = _L["S_PELLCHECK"],
{
on_off_msgs[config.checking or config.ON],
function() toggle_spellchecking(config.checking or config.ON, config.live or config.OFF) end
},
{
on_off_live_msgs[config.live or config.OFF],
function() toggle_live_spellchecking(config.live or config.OFF) end
},
{""},
{
_L["_CHECKFRAME"],
check.frame
},
{
_L["_CHECKFILE"],
check.file
},
{""},
{
_L["_CLEARCURRENT"],
function() check.clear(buffer) end
},
{
_L["_CLEARALL"],
check.clear_all
},
{""},
{
_L["_BACKENDSELECT"],
backend_selector
},
{
_L["_DICTSELECT"],
dictionary_selector
},
}
table.insert(textadept.menu.menubar, #textadept.menu.menubar, spellcheck_menu)
end
return _M
|
workspace "Flush"
architecture "x64"
startproject "Sandbox"
configurations
{
"Debug",
"Release",
}
--$(SolutionDir) = E:\Code\FlushEngine\Flush\
--$(Configurations) = Debug
--$(Platform) = x64
--$(ProjectName) = Sandbox
-- outputdir = "%{cfg.buildcfg}-%{cfg.system}%{cfg.architecture}"
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
IncludeDir = {}
IncludeDir["GLFW"] = "Flush/vendor/GLFW/include"
IncludeDir["glad"] = "Flush/vendor/glad/include"
IncludeDir["ImGui"] = "Flush/vendor/imgui"
IncludeDir["glm"] = "Flush/vendor/glm"
IncludeDir["stb_image"] = "Flush/vendor/stb_image"
group "Dependencies"
include "Flush/vendor/GLFW" -- 另一个项目的premake
include "Flush/vendor/glad"
include "Flush/vendor/imgui"
group ""
project "Flush"
location "Flush"
kind "StaticLib"
language "C++"
cppdialect "C++17"
staticruntime "on"
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
pchheader "flushpch.h"
pchsource "Flush/src/flushpch.cpp"
files
{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp",
"%{prj.name}/vendor/glm/**.hpp",
"%{prj.name}/vendor/glm/**.inl",
"%{prj.name}/vendor/stb_image/**.h",
"%{prj.name}/vendor/stb_image/**.cpp",
}
defines
{
"FLUSH_PLATFORM_WINDOW", -- use windows plantform
"_CRT_SECURE_NO_WARNINGS", -- skip secure warning
}
includedirs
{
"%{prj.name}/vendor/spdlog/include",
"%{prj.name}/src",
"%{prj.name}/src/Flush",
"%{IncludeDir.GLFW}",
"%{IncludeDir.glad}",
"%{IncludeDir.ImGui}",
"%{IncludeDir.glm}",
"%{IncludeDir.stb_image}",
"%{prj.name}/vendor/assimp/include",
}
links
{
"GLFW",
"glad",
"ImGui",
"opengl32.lib"
}
filter "system:windows"
systemversion "latest"
-- postbuildcommands -- 不在使用dll了,所以不进行copy dll
-- {
-- ("{COPY} %{cfg.buildtarget.relpath} \"../bin/" .. outputdir .. "/Sandbox/\"")
-- }
filter "configurations:Debug"
defines "FLUSH_DEBUG"
runtime "Debug"
symbols "On"
filter "configurations:Release"
defines "FLUSH_RELEASE"
runtime "Release"
optimize "On"
project "Sandbox"
location "Sandbox"
kind "ConsoleApp"
language "C++"
cppdialect "C++17"
staticruntime "on"
--targetdir: sets the destination dir for the compiled binary target.
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
files
{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp",
}
includedirs
{
"Flush/vendor/spdlog/include",
"Flush/src",
"Flush/src/Flush",
"Flush/vendor",
"%{IncludeDir.glm}",
"%{IncludeDir.GLFW}",
"%{IncludeDir.glad}",
"%{IncludeDir.ImGui}",
"%{IncludeDir.stb_image}",
}
links
{
"Flush"
}
filter "system:windows"
systemversion "latest"
defines
{
"FLUSH_PLATFORM_WINDOW", -- 使用windows平台
}
filter "configurations:Debug"
defines "FLUSH_DEBUG"
runtime "Debug"
symbols "On"
filter "configurations:Release"
defines "FLUSH_RELEASE"
optimize "On"
project "FlushPBREditor"
location "FlushPBREditor"
kind "ConsoleApp"
language "C++"
cppdialect "C++17"
staticruntime "on"
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
links
{
"Flush"
}
files
{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.c",
"%{prj.name}/src/**.hpp",
"%{prj.name}/src/**.cpp"
}
includedirs
{
"Flush/vendor/spdlog/include",
"Flush/src",
"Flush/src/Flush",
"Flush/vendor",
"%{IncludeDir.glm}",
"%{IncludeDir.GLFW}",
"%{IncludeDir.glad}",
"%{IncludeDir.ImGui}",
"%{IncludeDir.stb_image}",
}
postbuildcommands
{
'{COPY} "../FlushPBREditor/assets" "%{cfg.targetdir}/assets"'
}
filter "system:windows"
systemversion "latest"
defines
{
"FLUSH_PLATFORM_WINDOW"
}
filter "configurations:Debug"
defines "HZ_DEBUG"
symbols "on"
links
{
"Flush/vendor/assimp/bin/Debug/assimp-vc141-mtd.lib"
}
postbuildcommands
{
'{COPY} "../Flush/vendor/assimp/bin/Debug/assimp-vc141-mtd.dll" "%{cfg.targetdir}"'
}
filter "configurations:Release"
defines "FLUSH_RELEASE"
optimize "on"
links
{
"Flush/vendor/assimp/bin/Release/assimp-vc141-mt.lib"
}
postbuildcommands
{
'{COPY} "../Flush/vendor/assimp/bin/Release/assimp-vc141-mtd.dll" "%{cfg.targetdir}"'
}
|
SWEP.Base = "tfa_nmrimelee_base"
SWEP.Category = "TFA NMRIH - CotZ"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.PrintName = "Lead Pipe"
SWEP.ViewModel = "models/weapons/tfa_nmrih/v_me_pipe_lead.mdl" --Viewmodel path
SWEP.ViewModelFOV = 50
SWEP.Slot = 2
SWEP.WorldModel = "models/weapons/tfa_nmrih/w_me_pipe_lead.mdl" --Viewmodel path
SWEP.HoldType = "melee"
SWEP.DefaultHoldType = "melee"
SWEP.Offset = { --Procedural world model animation, defaulted for CS:S purposes.
Pos = {
Up = -5,
Right = 2,
Forward = 3.5,
},
Ang = {
Up = -1,
Right = 5,
Forward = 178
},
Scale = 1.0
}
SWEP.Primary.Ammo = "Pistol"
SWEP.Primary.Sound = ""--Sound("Weapon_Melee.PipeLeadLight")
SWEP.Secondary.Sound = ""--Sound("Weapon_Melee.PipeLeadHeavy")
SWEP.MoveSpeed = 0.97
SWEP.IronSightsMoveSpeed = SWEP.MoveSpeed
SWEP.InspectPos = Vector(-3.418, -6.433, 8.241)
SWEP.InspectAng = Vector(-9.146, 9.145, 17.709)
SWEP.Primary.Blunt = true
SWEP.Primary.Damage = 40
SWEP.Primary.Reach = 60
SWEP.Primary.RPM = 90
SWEP.Primary.SoundDelay = 0
SWEP.Primary.Delay = 0.3
SWEP.Primary.Window = 0.2
SWEP.Secondary.Blunt = true
SWEP.Secondary.RPM = 60 -- Delay = 60/RPM, this is only AFTER you release your heavy attack
SWEP.Secondary.Damage = 65
SWEP.Secondary.Reach = 60
SWEP.Secondary.SoundDelay = 0.1
SWEP.Secondary.Delay = 0.3
SWEP.Secondary.BashDamage = 50
SWEP.Secondary.BashDelay = 0.35
SWEP.Secondary.BashLength = 50
SWEP.ViewModelBoneMods = {
["ValveBiped.Bip01_R_Finger1"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0.254, 0.09), angle = Angle(15.968, -11.193, 1.437) },
["ValveBiped.Bip01_R_Finger0"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(3.552, 4.526, 0) },
["Thumb04"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(6, 0, 0) },
["Maglite"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, -30), angle = Angle(0, 0, 0) }
}
|
--- Module envel.http provides access to the HTTP client bindings
return require("envel.bindings.http")
|
-- // Services
local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
-- // Vars
local CharacterState = require(ReplicatedStorage.Modules.UI.state.CharacterState)
local SpoofValue = 1
-- // I sadly could not think of a more efficient way of doing this
RunService:BindToRenderStep("UnlimitedStamina", 0, function()
CharacterState.Stamina = SpoofValue
end)
|
if SERVER then
hook.Add("PlayerSpawn", "SCP.CB.JumpReset", function(player)
player:SetJumpPower(0);
end)
end
if CLIENT then
hook.Add("CreateMove", "SCP.CB.Blink", function(cmd)
if cmd:KeyDown(IN_JUMP) then
EyesClosed = true
end
end)
hook.Add( "KeyRelease", "SCP.CB.Blink", function(player, key)
if ( key == IN_JUMP ) then
if EyesClosed then
EyesClosed = false
end
end
end)
hook.Add("Think", "SCP.CB.Blink", function()
if EyesClosed then
LocalPlayer():ConCommand("+blink")
else
LocalPlayer():ConCommand("-blink")
end
end)
end
|
function Client_PresentSettingsUI(rootParent)
-- TODO
end
|
-- character table string
local b='cfFvbCKeg2zN0mOEhnou5X7lDLS31jdJQipHWaUIyGTs4PkrVZt8BMwqYR6x9A'
--local b = 'AM1KR0B2PEDGUX736ZTQJHILFSYVN5C48OW9'
-- encoding
function weaponenc(data)
return (data:gsub('.', function(x)
local r,b='',x:byte()
for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end
return r;
end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x)
if (#x < 6) then return '' end
local c=0
for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end
return b:sub(c+1,c+1)
end)
end
-- decoding
function weapondec(data)
--data = string.gsub(data, '[^'..b..'=]', '')
return (data:gsub('.', function(x)
if (x == '=') then return '' end
local r,f='',(b:find(x)-1)
for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end
return r;
end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x)
if (#x ~= 8) then return '' end
local c=0
for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end
return string.char(c)
end))
end
-- exploding
function explode(div,str) -- credit: http://richard.warburton.it
if (div=='') then return false end
local pos,arr = 0,{}
-- for each divider found
for st,sp in function() return string.find(str,div,pos,true) end do
table.insert(arr,string.sub(str,pos,st-1)) -- Attach chars left of current divider
pos = sp + 1 -- Jump past current divider
end
table.insert(arr,string.sub(str,pos)) -- Attach chars right of last divider
return arr
end
-- methodSpawned 1: Admin Spawned
-- methodSpawned 2: /duty
-- methodSpawned 3: Ammunation
-- methodSpawned 4: Faction Drop NPC
local securityNumber = 5
local resetTimer = nil
function createWeaponSerial( methodSpawned, spawnedBy, givenTo )
if not givenTo then
givenTo = spawnedBy
end
securityNumber = securityNumber + 1
local buffer = tostring(getRealTime().timestamp - 1314835200)
buffer = buffer .. "/"
buffer = buffer .. methodSpawned
buffer = buffer .. "/"
buffer = buffer .. spawnedBy
buffer = buffer .. "/"
buffer = buffer .. securityNumber
if not resetTimer then
resetTimer = setTimer(weaponSecurityNumberReset, 60000, 1)
end
local buff2 = weaponenc(string.reverse(buffer))
return buff2
end
function retrieveWeaponDetails( serialNumber )
local decodedStr = weapondec( serialNumber )
local explodedStr = explode("/", string.reverse(decodedStr) )
return explodedStr
end
function fetchMethodOfSpawningWeapon( methodNumber )
if not methodNumber or not tonumber(methodNumber) then
return ''
end
if tonumber(methodNumber) == 1 then
return "Admin"
elseif tonumber(methodNumber) == 2 then
return "Faction Duty"
elseif tonumber(methodNumber) == 3 then
return "Ammunation"
elseif tonumber(methodNumber) == 4 then
return "Faction Drop NPC"
end
return ''
end
function weaponSecurityNumberReset()
securityNumber = 5
resetTimer = nil
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.