content
stringlengths 5
1.05M
|
|---|
--[[
© CloudSixteen.com do not share, re-distribute or modify
without permission of its author (kurozael@gmail.com).
Clockwork was created by Conna Wiles (also known as kurozael.)
http://cloudsixteen.com/license/clockwork.html
--]]
cwAnimatedLegs.BoneHoldTypes = {
["none"] = {
"ValveBiped.Bip01_Head1",
"ValveBiped.Bip01_Neck1",
"ValveBiped.Bip01_Spine4",
"ValveBiped.Bip01_Spine2",
},
["fist"] = {
"ValveBiped.Bip01_Head1",
"ValveBiped.Bip01_Neck1",
"ValveBiped.Bip01_Spine4",
"ValveBiped.Bip01_Spine2",
},
["chair"] = {
"ValveBiped.Bip01_Head1",
"ValveBiped.Bip01_Neck1",
"ValveBiped.Bip01_Spine4",
"ValveBiped.Bip01_Spine2",
"ValveBiped.Bip01_R_Upperarm",
"ValveBiped.Bip01_L_Upperarm",
"ValveBiped.Bip01_R_Clavicle",
"ValveBiped.Bip01_L_Clavicle"
},
["default"] = {
"ValveBiped.Bip01_Head1",
"ValveBiped.Bip01_L_Hand",
"ValveBiped.Bip01_L_Forearm",
"ValveBiped.Bip01_L_Upperarm",
"ValveBiped.Bip01_L_Clavicle",
"ValveBiped.Bip01_R_Hand",
"ValveBiped.Bip01_R_Forearm",
"ValveBiped.Bip01_R_Upperarm",
"ValveBiped.Bip01_R_Clavicle",
"ValveBiped.Bip01_L_Finger4",
"ValveBiped.Bip01_L_Finger41",
"ValveBiped.Bip01_L_Finger42",
"ValveBiped.Bip01_L_Finger3",
"ValveBiped.Bip01_L_Finger31",
"ValveBiped.Bip01_L_Finger32",
"ValveBiped.Bip01_L_Finger2",
"ValveBiped.Bip01_L_Finger21",
"ValveBiped.Bip01_L_Finger22",
"ValveBiped.Bip01_L_Finger1",
"ValveBiped.Bip01_L_Finger11",
"ValveBiped.Bip01_L_Finger12",
"ValveBiped.Bip01_L_Finger0",
"ValveBiped.Bip01_L_Finger01",
"ValveBiped.Bip01_L_Finger02",
"ValveBiped.Bip01_R_Finger4",
"ValveBiped.Bip01_R_Finger41",
"ValveBiped.Bip01_R_Finger42",
"ValveBiped.Bip01_R_Finger3",
"ValveBiped.Bip01_R_Finger31",
"ValveBiped.Bip01_R_Finger32",
"ValveBiped.Bip01_R_Finger2",
"ValveBiped.Bip01_R_Finger21",
"ValveBiped.Bip01_R_Finger22",
"ValveBiped.Bip01_R_Finger1",
"ValveBiped.Bip01_R_Finger11",
"ValveBiped.Bip01_R_Finger12",
"ValveBiped.Bip01_R_Finger0",
"ValveBiped.Bip01_R_Finger01",
"ValveBiped.Bip01_R_Finger02"
},
["vehicle"] = {
"ValveBiped.Bip01_Head1",
"ValveBiped.Bip01_Neck1",
"ValveBiped.Bip01_Spine4",
"ValveBiped.Bip01_Spine2",
}
};
cwAnimatedLegs.PlaybackRate = 1;
cwAnimatedLegs.OldWeapon = nil;
cwAnimatedLegs.Sequence = nil;
cwAnimatedLegs.Velocity = 0;
cwAnimatedLegs.HoldType = nil;
cwAnimatedLegs.ForwardOffset = -24;
cwAnimatedLegs.BonesToRemove = {};
cwAnimatedLegs.RenderAngle = nil;
cwAnimatedLegs.RenderColor = {};
cwAnimatedLegs.BreathScale = 0.5;
cwAnimatedLegs.BoneMatrix = nil;
cwAnimatedLegs.NextBreath = 0;
cwAnimatedLegs.BiaisAngle = nil;
cwAnimatedLegs.ClipVector = vector_up * -1;
cwAnimatedLegs.RenderPos = nil;
cwAnimatedLegs.RadAngle = nil;
-- A function to get whether the legs should be drawn.
function cwAnimatedLegs:ShouldDrawLegs()
return IsValid(self.LegsEntity) and Clockwork.Client:Alive()
and self:CheckDrawVehicle() and GetViewEntity() == Clockwork.Client
and !Clockwork.Client:ShouldDrawLocalPlayer() and !IsValid(Clockwork.Client:GetObserverTarget());
end;
-- A function to check if a vehicle should be drawn.
function cwAnimatedLegs:CheckDrawVehicle()
return Clockwork.Client:InVehicle()
and (Clockwork.Client:GetVehicle() and Clockwork.Client:GetVehicle():GetThirdPersonMode())
or !Clockwork.Client:InVehicle();
end;
-- A function to create the legs.
function cwAnimatedLegs:CreateLegs()
self.LegsEntity = ClientsideModel(Clockwork.Client:GetModel(), RENDER_GROUP_OPAQUE_ENTITY);
self.LegsEntity:SetNoDraw(true);
self.LegsEntity:SetSkin(Clockwork.Client:GetSkin());
self.LegsEntity:SetMaterial(Clockwork.Client:GetMaterial());
self.LegsEntity.LastTick = 0;
end;
-- A function to get when a weapon is changed.
function cwAnimatedLegs:WeaponChanged(weapon)
if (IsValid(self.LegsEntity)) then
if (IsValid(weapon)) then
self.HoldType = weapon.HoldType;
else
self.HoldType = "none";
end;
for i = 0, self.LegsEntity:GetBoneCount() do
self.LegsEntity:ManipulateBoneScale(i, Vector(1, 1, 1));
self.LegsEntity:ManipulateBonePosition(i, vector_origin);
end;
self.BonesToRemove = {"ValveBiped.Bip01_Head1"};
if (!Clockwork.Client:InVehicle()) then
if ((self.HoldType != "fist" or !Clockwork.player:GetWeaponRaised(Clockwork.Client))
and self.BoneHoldTypes[self.HoldType]) then
self.BonesToRemove = self.BoneHoldTypes[self.HoldType];
else
self.BonesToRemove = self.BoneHoldTypes["default"];
end;
elseif (!Clockwork.entity:IsChairEntity(Clockwork.Client:GetVehicle())) then
self.BonesToRemove = self.BoneHoldTypes["vehicle"];
else
self.BonesToRemove = self.BoneHoldTypes["chair"];
end;
for k, v in pairs(self.BonesToRemove) do
local bone = self.LegsEntity:LookupBone(v);
if (bone) then
self.LegsEntity:ManipulateBoneScale(bone, vector_origin);
self.LegsEntity:ManipulateBonePosition(bone, Vector(-10,-10,0));
end;
end;
end;
end;
-- Called every frame for the legs.
function cwAnimatedLegs:LegsThink(maxSeqGroundSpeed)
local curTime = CurTime();
if (IsValid(self.LegsEntity)) then
if (Clockwork.Client:GetActiveWeapon() != self.OldWeapon) then
self.OldWeapon = Clockwork.Client:GetActiveWeapon();
self:WeaponChanged(self.OldWeapon);
end;
if (self.LegsEntity:GetModel() != Clockwork.Client:GetModel()) then
self.LegsEntity:SetModel(Clockwork.Client:GetModel());
end
self.LegsEntity:SetMaterial(Clockwork.Client:GetMaterial());
self.LegsEntity:SetSkin(Clockwork.Client:GetSkin());
self.Velocity = Clockwork.Client:GetVelocity():Length2D();
self.PlaybackRate = 1;
if (self.Velocity > 0.5) then
if (maxSeqGroundSpeed < 0.001) then
self.PlaybackRate = 0.01;
else
self.PlaybackRate = self.Velocity / maxSeqGroundSpeed;
self.PlaybackRate = math.Clamp(self.PlaybackRate, 0.01, 10);
end
end
self.LegsEntity:SetPlaybackRate(self.PlaybackRate);
self.Sequence = Clockwork.Client:GetSequence();
if (self.LegsEntity.Anim != self.Sequence) then
self.LegsEntity.Anim = self.Sequence;
self.LegsEntity:ResetSequence(self.Sequence);
end;
self.LegsEntity:FrameAdvance(curTime - self.LegsEntity.LastTick);
self.LegsEntity.LastTick = curTime;
if (self.NextBreath <= curTime) then
self.NextBreath = curTime + 1.95 / self.BreathScale;
self.LegsEntity:SetPoseParameter("breathing", self.BreathScale);
end
self.LegsEntity:SetPoseParameter("move_yaw", (Clockwork.Client:GetPoseParameter("move_yaw") * 360) - 180);
self.LegsEntity:SetPoseParameter("body_yaw", (Clockwork.Client:GetPoseParameter("body_yaw") * 180) - 90);
self.LegsEntity:SetPoseParameter("spine_yaw", (Clockwork.Client:GetPoseParameter("spine_yaw") * 180) - 90);
if (Clockwork.Client:InVehicle()) then
self.LegsEntity:SetColor(color_transparent);
self.LegsEntity:SetPoseParameter("vehicle_steer", (Clockwork.Client:GetVehicle():GetPoseParameter("vehicle_steer") * 2) - 1);
end;
for iBodygroupIndex = 0, Clockwork.Client:GetNumBodyGroups() - 1 do
self.LegsEntity:SetBodygroup(iBodygroupIndex, Clockwork.Client:GetBodygroup(iBodygroupIndex));
end;
end;
end;
|
project "glm"
kind "StaticLib" -- StaticLib for .lib
language "C++" -- C++
staticruntime "on"
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
-- Files that should be included into this project
files
{
"glm/**.hpp",
"glm/**.inl"
}
-- If the system is windows
filter "system:windows"
systemversion "latest"
staticruntime "On"
--postbuildcommands
--{
-- "{COPYDIR} %{cfg.buildtarget.bundlepath} ../bin/" .. outputdir
--}
-- Debug configuration
filter "configurations:Debug"
runtime "Debug"
symbols "on"
-- Release configuration
filter "configurations:Release"
runtime "Release"
optimize "on"
|
--------------------------------------------------------------
-- Definition of "setfallback" using tag methods
-- (for compatibility with old code)
--------------------------------------------------------------
-- default fallbacks for each event:
local defaults = {
gettable = function () error('indexed expression not a table') end,
settable = function () error('indexed expression not a table') end,
index = function () return nil end,
getglobal = function () return nil end,
arith = function () error('number expected in arithmetic operation') end,
order = function () error('incompatible types in comparison') end,
concat = function () error('string expected in concatenation') end,
gc = function () return nil end,
['function'] = function () error('called expression not a function') end,
error = function (s) write(_STDERR, s, '\n') end,
}
function setfallback (name, func)
-- set the given function as the tag method for all "standard" tags
-- (since some combinations may cause errors, use call to avoid messages)
local fillvalids = function (n, func)
call(settagmethod, {0, n, func}, 'x', nil)
call(settagmethod, {tag(0), n, func}, 'x', nil)
call(settagmethod, {tag(''), n, func}, 'x', nil)
call(settagmethod, {tag{}, n, func}, 'x', nil)
call(settagmethod, {tag(function () end), n, func}, 'x', nil)
call(settagmethod, {tag(settagmethod), n, func}, 'x', nil)
call(settagmethod, {tag(nil), n, func}, 'x', nil)
end
assert(type(func) == 'function')
local oldfunc
if name == 'error' then
oldfunc = seterrormethod(func)
elseif name == 'getglobal' then
oldfunc = settagmethod(tag(nil), 'getglobal', func)
elseif name == 'arith' then
oldfunc = gettagmethod(tag(0), 'pow')
foreach({"add", "sub", "mul", "div", "unm", "pow"},
function(_, n) %fillvalids(n, %func) end)
elseif name == 'order' then
oldfunc = gettagmethod(tag(nil), 'lt')
foreach({"lt", "gt", "le", "ge"},
function(_, n) %fillvalids(n, %func) end)
else
oldfunc = gettagmethod(tag(nil), name)
fillvalids(name, func)
end
return oldfunc or rawgettable(%defaults, name)
end
|
BigWigs:AddColors("Mechano-Lord Capacitus", {
[35158] = {"green","orange"},
[35159] = {"green","orange"},
[39096] = {"cyan","orange","red"},
})
BigWigs:AddColors("Gatewatcher Iron-Hand", {
[35311] = {"blue","orange"},
[39193] = "red",
[39194] = {"blue","yellow"},
})
BigWigs:AddColors("Gatewatcher Gyro-Kill", {
[35311] = {"blue","orange"},
[39193] = "red",
})
BigWigs:AddColors("Nethermancer Sepethrea", {
[-5488] = {"blue","cyan"},
[35250] = {"blue","orange"},
[35314] = {"blue","red"},
[41951] = {"blue","yellow"},
})
BigWigs:AddColors("Pathaleon the Calculator", {
[35280] = {"blue","red"},
[35285] = "red",
})
|
workspace "Adonis"
architecture "x64"
configurations{
"Debug",
"Release",
"Dist"
}
outputdir = "%{cfg.buildcfg}/%{cfg.system}-%{cfg.architecture}"
IncludeDir = {}
IncludeDir["GLFW"] = "Adonis/vendor/GLFW/include"
IncludeDir["GLAD"] = "Adonis/vendor/glad/include"
IncludeDir["IMGUI"] = "Adonis/vendor/imgui"
IncludeDir["GLM"] = "Adonis/vendor/glm"
group "Dependencies"
include "Adonis/vendor/GLFW"
include "Adonis/vendor/glad"
include "Adonis/vendor/imgui"
group ""
project "Adonis"
location "Adonis"
kind "SharedLib"
language "C++"
staticruntime "off"
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
pchheader "pch.h"
pchsource "Adonis/src/pch.cpp"
files{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp",
"%{prj.name}/src/**.vert",
"%{prj.name}/src/**.frag",
"%{prj.name}/resources/WindowIcon.png"
}
includedirs{
"%{prj.name}",
"%{prj.name}/src",
"%{prj.name}/vendor/spdlog/include",
"%{prj.name}/vendor/stb/include",
"%{prj.name}/vendor/glad/include",
"%{prj.name}/vendor/GLFW/include",
"%{prj.name}/vendor/glm",
"%{prj.name}/vendor/imgui",
"%{prj.name}/vendor/jsonparser/single_include",
}
links{
"GLFW",
"GLAD",
"IMGUI",
"opengl32.lib"
}
defines{
"ADONIS_USE_GLFW",
}
filter "system:windows"
cppdialect "C++17"
systemversion "latest"
defines{
"ADONIS_PLATFORM_WINDOWS",
"ADONIS_BUILD_DLL",
"ADONIS_GLLOADER_GLAD",
"_CRT_SECURE_NO_WARNINGS",
"STB_IMAGE_IMPLEMENTATION"
}
postbuildcommands{
("{COPY} %{cfg.buildtarget.relpath} ../bin/" .. outputdir .. "/Sandbox")
}
filter "configurations:Debug"
defines "ADONIS_DEBUG"
runtime "Debug"
symbols "On"
filter "configurations:Release"
defines "ADONIS_RELEASE"
runtime "Release"
optimize "On"
filter "configurations:Dist"
defines "ADONIS_DIST"
buildoptions "Release"
optimize "On"
project "Sandbox"
location "Sandbox"
kind "ConsoleApp"
language "C++"
staticruntime "off"
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
files{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp",
"Adonis/resources/WindowIcon.png"
}
includedirs{
"Adonis/src",
"Adonis/vendor/spdlog/include",
"Adonis/vendor/glm",
"Adonis/vendor/stb/include",
"Adonis/vendor/glad/include",
"Adonis/vendor/GLFW/include",
"Adonis/vendor/imgui/",
"Adonis/vendor/jsonparser/single_include",
}
links{
"Adonis",
"IMGUI",
}
filter "system:windows"
cppdialect "C++17"
systemversion "latest"
defines{
"ADONIS_PLATFORM_WINDOWS",
}
filter "configurations:Debug"
defines "ADONIS_DEBUG"
runtime "Debug"
symbols "On"
filter "configurations:Release"
defines "ADONIS_RELEASE"
runtime "Release"
optimize "On"
filter "configurations:Dist"
defines "ADONIS_DIST"
buildoptions "Release"
optimize "On"
|
--
-- slip.actions
--
-- Public functions with unified API.
--
local notes = require('slip.notes')
local slips = require('slip.slips')
local config = require('slip.config').opts
local slip_finders = require('slip.telescope.finders')
local tele_builtin = require('telescope.builtin')
local pickers = require('telescope.pickers')
local actions = require('telescope.actions')
local action_set = require('telescope.actions.set')
local action_state = require('telescope.actions.state')
local tele_conf = require('telescope.config').values
local m = {}
function m.create_note(opts)
opts = opts or {}
opts.slip = opts.slip or slips.get_default()
opts.type = opts.type or 'permanent'
if opts.type == 'bibliographical' then
local slip_spec = config.slips[opts.slip]
local bib_dir_path = slip_spec.path .. '/' .. slip_spec.bibliography_dir_name
if 0 == vim.fn.isdirectory(bib_dir_path) then
print('succ: ' .. vim.fn.mkdir(bib_dir_path))
end
end
local path = notes.get_new_note_path(opts.slip, opts.type)
local edit_cmd = opts.edit_cmd or 'edit'
vim.cmd(edit_cmd .. ' ' .. vim.fn.fnamemodify(path, ':~:.'))
end
function m.update_index(opts)
opts = opts or {}
opts.slips = opts.slips or {slips.get_default()}
local notes_to_update = {}
local add_all_notes = function (slip)
local notes_paths = vim.fn.glob(config.slips[slip].path .. '/*.md', false, true)
if #notes_paths > 0 then
notes_to_update[slip] = {}
end
for _, path in ipairs(notes_paths) do
table.insert(notes_to_update[slip], notes.parse(path))
end
end
for _, slip in ipairs(opts.slips) do
add_all_notes(slip)
end
for slip, slip_notes in pairs(notes_to_update) do
local index = slips.get_index(slip)
index:update(slip_notes)
end
end
function m.find_notes(opts)
opts = opts or {}
opts.slips = opts.slips or {slips.get_default()}
pickers.new(opts, {
prompt_title = 'Notes in ' .. table.concat(opts.slips, '/'),
finder = slip_finders.slip_notes(opts.slips),
previewer = tele_conf.file_previewer(opts),
sorter = tele_conf.generic_sorter(opts),
}):find()
end
--TODO: transform these into pickers with opts
function m.insert_link(opts)
opts = opts or {}
opts.slip = opts.slip or slips.get_default()
local curr_note = notes.parse(vim.fn.expand('%:p'))
if curr_note == nil then
error('Path ' .. vim.fn.expand('&:p') .. ' cannot be parsed as a note.')
end
local curr_mode = vim.api.nvim_get_mode().mode
if curr_note == nil then
error('Cannot insert link. Current file is not a note.')
end
pickers.new(opts, {
prompt_title = 'Link destination',
finder = slip_finders.slip_notes({opts.slip}),
previewer = tele_conf.file_previewer(opts),
sorter = tele_conf.generic_sorter(opts),
attach_mappings = function (prompt_bufnr)
action_set.select:replace(function ()
actions.close(prompt_bufnr)
local selected_note = action_state.get_selected_entry().value
curr_note:insert_link(selected_note)
if curr_mode == 'i' then
vim.api.nvim_feedkeys('a', 'n', true)
end
end)
return true
end
}):find()
end
function m.live_grep(opts)
opts = opts or {}
opts.slips = opts.slips or {slips.get_default()}
local search_dirs = {}
for _, s in ipairs(opts.slips) do
table.insert(search_dirs, config.slips[s].path)
end
tele_builtin.live_grep(vim.tbl_extend('keep', opts, {
prompt_title = 'Notes live grep in ' .. table.concat(opts.slips, '/'),
search_dirs = search_dirs,
}))
end
function m.find_close_notes(opts)
opts = opts or {}
opts.note_path = opts.note_path or vim.fn.exepath('%:p')
local central_note = notes.parse(vim.fn.expand('%:p'))
if central_note == nil then
error('Path ' .. vim.fn.expand('&:p') .. ' cannot be parsed as a note.')
end
end
return m
|
local event = require("event")
local libGUI = require("libGUI")
local reactor_ctrl = require("brgc/reactor_ctrl")
local turbine_ctrl = require("brgc/turbine_ctrl")
local reactor_info_small = require("brgc/gui/reactor_info_small")
local turbine_info_small = require("brgc/gui/turbine_info_small")
local reactor_info_big = require("brgc/gui/reactor_info_big")
local turbine_info_big = require("brgc/gui/turbine_info_big")
local controller_info_big = require("brgc/gui/controller_info_big")
local tabframe = libGUI.newFrame("tabframe")
local list_r = libGUI.newFrame("list")
local list_t = libGUI.newFrame("list")
local list_c = libGUI.newFrame("list")
local grid_view = controller_info_big()
--
local function update_list()
local reactors = {}
local turbines = {}
for _, reactor in pairs(reactor_ctrl.mReactors or {}) do
table.insert(reactors, reactor)
end
for _, turbine in pairs(turbine_ctrl.mTurbines or {}) do
table.insert(turbines, turbine)
end
table.sort(reactors, function(a,b) return a:getAddress() < b:getAddress() end)
table.sort(turbines, function(a,b) return a:getAddress() < b:getAddress() end)
-- if #list_r.mChildren ~= #reactors then
while #list_r.mChildren > 0 do
list_r:removeChild(list_r.mChildren[1])
end
for _, reactor in pairs(reactors) do
local rframe = reactor_info_small(reactor)
function rframe:onTouch() tabframe:setFrameActive(reactor_info_big(reactor)) end
list_r:addChild(rframe)
end
-- end
-- if #list_t.mChildren ~= #turbines then
while #list_t.mChildren > 0 do
list_t:removeChild(list_t.mChildren[1])
end
for _, turbine in pairs(turbines) do
local tframe = turbine_info_small(turbine)
function tframe:onTouch() tabframe:setFrameActive(turbine_info_big(turbine)) end
list_t:addChild(tframe)
end
-- end
-- if #list_c.mChildren ~= #reactors+#turbines then
while #list_c.mChildren > 0 do
list_c:removeChild(list_c.mChildren[1])
end
list_c:addChild(libGUI.newFrame("label", "Reactors", "center"))
for _, reactor in pairs(reactors) do
local rframe = reactor_info_small(reactor)
function rframe:onTouch() tabframe:setFrameActive(reactor_info_big(reactor)) end
list_c:addChild(rframe)
end
list_c:addChild(libGUI.newFrame("label", "Turbines", "center"))
for _, turbine in pairs(turbines) do
local tframe = turbine_info_small(turbine)
function tframe:onTouch() tabframe:setFrameActive(turbine_info_big(turbine)) end
list_c:addChild(tframe)
end
-- end
-- tabframe:onDraw()
end
local function update_list_callback()
xpcall(update_list, function(...)
libGUI.exit()
io.stderr:write("[BRGCGUI] " .. debug.traceback( ... ) .. "\n")
end)
tabframe:onDraw(false)
end
local function onTerminate()
event.ignore("brgc_reactor_added", update_list_callback)
event.ignore("brgc_turbine_added", update_list_callback)
event.ignore("libGUI_terminate", onTerminate)
end
--
libGUI.init()
libGUI.setRootFrame(tabframe)
libGUI.setOptimalResolutionByTier(0.5, 1)
update_list()
tabframe:addItem("Grid", nil, grid_view)
tabframe:addItem("Combined", nil, list_c)
if libGUI.getResolution() > 60 then
tabframe:addItem("Reactors", nil, list_r)
tabframe:addItem("Turbines", nil, list_t)
end
tabframe:addItem("Exit", libGUI.exit, nil)
tabframe:activateItem("Combined")
event.listen("brgc_reactor_added", update_list_callback)
event.listen("brgc_turbine_added", update_list_callback)
event.listen("libGUI_terminate", onTerminate)
libGUI.setRedrawInterval(1)
libGUI.runOrFork()
|
local class = require('opus.class')
local Sound = require('opus.sound')
local UI = require('opus.ui')
local colors = _G.colors
UI.Form = class(UI.Window)
UI.Form.defaults = {
UIElement = 'Form',
values = { },
margin = 2,
event = 'form_complete',
cancelEvent = 'form_cancel',
}
function UI.Form:postInit()
self:createForm()
end
function UI.Form:reset()
for _,child in pairs(self.children) do
if child.reset then
child:reset()
end
end
end
function UI.Form:setValues(values)
self:reset()
self.values = values
for _,child in pairs(self.children) do
if child.formKey then
if child.setValue then
child:setValue(self.values[child.formKey])
else
child.value = self.values[child.formKey] or ''
end
end
end
end
function UI.Form:createForm()
self.children = self.children or { }
if not self.labelWidth then
self.labelWidth = 1
for _, child in pairs(self) do
if type(child) == 'table' and child.UIElement then
if child.formLabel then
self.labelWidth = math.max(self.labelWidth, #child.formLabel + 2)
end
end
end
end
local y = self.margin
for _, child in pairs(self) do
if type(child) == 'table' and child.UIElement then
if child.formKey then
child.value = self.values[child.formKey] or ''
end
if child.formLabel then
child.x = self.labelWidth + self.margin - 1
child.y = child.formIndex and (child.formIndex + self.margin - 1) or y
if not child.width and not child.ex then
child.ex = -self.margin
end
table.insert(self.children, UI.Text {
x = self.margin,
y = child.y,
textColor = colors.black,
width = #child.formLabel,
value = child.formLabel,
})
end
if child.formLabel then
y = y + 1
end
end
end
if not self.manualControls then
table.insert(self.children, UI.Button {
y = -self.margin, x = -12 - self.margin,
text = 'Ok',
event = 'form_ok',
})
table.insert(self.children, UI.Button {
y = -self.margin, x = -7 - self.margin,
text = 'Cancel',
event = self.cancelEvent,
})
end
end
function UI.Form:validateField(field)
if field.required then
if not field.value or #tostring(field.value) == 0 then
return false, 'Field is required'
end
end
if field.validate == 'numeric' then
field.value = field.value or ''
if #tostring(field.value) > 0 then
if not tonumber(field.value) then
return false, 'Invalid number'
end
end
end
return true
end
function UI.Form:save()
for _,child in pairs(self.children) do
if child.formKey then
local s, m = self:validateField(child)
if not s then
self:setFocus(child)
Sound.play('entity.villager.no', .5)
self:emit({ type = 'form_invalid', message = m, field = child })
return false
end
end
end
for _,child in pairs(self.children) do
if child.formKey then
if child.validate == 'numeric' then
self.values[child.formKey] = tonumber(child.value)
else
self.values[child.formKey] = child.value
end
end
end
return true
end
function UI.Form:eventHandler(event)
if event.type == 'form_ok' then
if not self:save() then
return false
end
self:emit({ type = self.event, UIElement = self, values = self.values })
else
return UI.Window.eventHandler(self, event)
end
return true
end
|
-- protocol ops:
-- c->s prgdl <uid> <version>
-- s->c prgfile <uid> <path>
-- s->c prgdata <uid> <bin data>
-- Check protocol.txt for more info
local dlprogram = {}
local fs = require("filesystem")
local term = require("term")
local modem = require("component").modem
local event = require("event")
local programport = 3200
dlprogram.states = {
sentfirstpacket=10, -- Sent prgdl packet to server.
newfile=11, -- Got a prgfile packet, and will download that file. This is returned along with the name of the file to receive.
dlfile=12, -- Got a prgdata packet. This is returned along with the number of bytes downloaded.
error=99, -- Anything after this is an error.
iderror=100, -- Program being received isn't the one specified. This is returned along with the UID of the program being received.
fileerror=101 -- Could not create a file. Returned along the file that couldn't be created.
}
function dlprogram.download(_serveraddr, _uid, _version, _path)
local pathCreated = false
local hasStarted = false
dlprogram.downloadedbytes = 0 -- this may generate errors in the future: managing global vars here?
dlprogram.currentfile = nil
local serveraddr, uid, version, path = _serveraddr, _uid, _version, _path
-- Iterator that downloads an entire program. Yields progress.
return function()
if not hasStarted then
modem.send(serveraddr, programport, "prgdl", uid, version)
hasStarted = true
return dlprogram.states.sentfirstpacket
end
-- encase everything in a while loop, in case event.pull pulls another event that is not modem_message.
while true do
local name, _, address, _p, _d, arg1, arg2, arg3 = event.pull()
if name == "modem_message" then
if address ~= serveraddr then goto continue end
if arg1 ~= "prgfile" and arg1 ~= "prgdata" and arg1~="prgdend" then goto continue end
if arg2 ~= uid then
return dlprogram.states.iderror, arg2
end
if arg1 == "prgfile" then
dlprogram.currentfile = arg3
return dlprogram.states.newfile, arg3
elseif arg1 == "prgdata" then
local writepath = path .. dlprogram.currentfile
if not fs.exists(writepath) then
if not fs.exists(fs.path(writepath)) then
fs.makeDirectory(fs.path(writepath)) -- Create parent dirs if neccesary
end
local f = fs.open(writepath, "w")
if f == nil then
return dlprogram.states.fileerror, writepath
end
f:close()
end
dlprogram.downloadedbytes = dlprogram.downloadedbytes + #arg3
local handle = require("io").open(writepath, "ab")
handle:write(arg3)
handle:flush()
handle:close()
return dlprogram.states.dlfile, #arg3
elseif arg1 == "prgdend" then
return nil
end
end
::continue::
end
end
end
return dlprogram
|
EFFECT.Smoke = {
Material( "particle/smokesprites_0001" ),
Material( "particle/smokesprites_0002" ),
Material( "particle/smokesprites_0003" ),
Material( "particle/smokesprites_0004" ),
Material( "particle/smokesprites_0005" ),
Material( "particle/smokesprites_0006" ),
Material( "particle/smokesprites_0007" ),
Material( "particle/smokesprites_0008" ),
Material( "particle/smokesprites_0009" ),
Material( "particle/smokesprites_0010" ),
Material( "particle/smokesprites_0011" ),
Material( "particle/smokesprites_0012" ),
Material( "particle/smokesprites_0013" ),
Material( "particle/smokesprites_0014" ),
Material( "particle/smokesprites_0015" ),
Material( "particle/smokesprites_0016" ),
};
function EFFECT:Init( data )
self.StartTime = CurTime();
self.Ent = data:GetEntity();
self.Dir = data:GetNormal();
self.Offset = data:GetMagnitude();
self.Emitter = ParticleEmitter( self.Ent:GetPos(), false );
for i = 17, #self.Smoke do
self.Smoke[i] = nil;
end
end
function EFFECT:Think()
if( self.Ent and self.Ent:IsValid() ) then
if( self.Emitter and self.Ent != LocalPlayer() ) then
self.Emitter:SetPos( self.Ent:GetPos() );
local mat = table.Random( self.Smoke );
local pos = Vector();
local t = math.Rand( -math.pi, math.pi );
local p = math.Rand( 0, math.pi );
local r = 8;
pos.x = r * math.sin( t ) * math.cos( p );
pos.y = r * math.sin( t ) * math.sin( p );
pos.z = r * math.cos( p );
local p = self.Emitter:Add( mat, self.Ent:GetPos() + pos + Vector( 0, 0, self.Offset ) );
if( p ) then
p:SetAirResistance( 1 );
p:SetCollide( false );
if( math.random( 1, 2 ) == 1 ) then
p:SetColor( 255, math.random( 100, 200 ), math.random( 10, 50 ) );
else
p:SetColor( 255, 255, 255 );
end
p:SetDieTime( 1 );
p:SetEndAlpha( 0 );
p:SetEndSize( 24 );
p:SetGravity( Vector( 0, 0, -8 ) );
p:SetLifeTime( 0 );
p:SetRoll( math.Rand( -math.pi, math.pi ) );
p:SetRollDelta( math.Rand( -math.pi, math.pi ) );
p:SetStartAlpha( 100 );
p:SetStartSize( 8 );
local noise = Vector();
local t = math.Rand( -math.pi, math.pi );
local phi = math.Rand( 0, math.pi );
local r = 20;
noise.x = r * math.sin( t ) * math.cos( phi );
noise.y = r * math.sin( t ) * math.sin( phi );
noise.z = r * math.cos( phi );
local dir = self.Dir;
local thrust = math.Rand( 40, 80 );
local vel = Vector( dir.x * thrust + noise.x, dir.y * thrust + noise.y, dir.z * thrust + noise.z );
p:SetVelocity( vel );
end
end
end
if( CurTime() - self.StartTime > 0.3 ) then
self.Emitter:Finish();
end
return CurTime() - self.StartTime < 0.3;
end
function EFFECT:Render()
end
|
--
-- volume.lua
-- volume status notification
--
local naughty = require("naughty")
local beautiful = require("beautiful")
-- ========================================
-- Config
-- ========================================
local icons_path = beautiful.icons_path .. "volume/"
-- ========================================
-- Logic
-- ========================================
-- Notify volume change
local notify_volume_change = function (percentage)
return naughty.notify {
icon = icons_path .. "volume_notification.svg",
title = "Volume",
text = string.format("Volume is now at %s%%", percentage),
}
end
-- Notify volume muted
local notify_volume_muted = function ()
return naughty.notify {
icon = icons_path .. "volume_notification_muted.svg",
title = "Volume",
text = "Volume is now muted",
}
end
-- ========================================
-- Initialization
-- ========================================
local notification
awesome.connect_signal("daemon::volume::percentage", function (percentage)
-- Pavucontrol already show volume, so do nothing
if client.focus and client.focus.class == "Pavucontrol" then return end
-- Remove existing notification
if notification then naughty.destroy(notification) end
notification = notify_volume_change(percentage)
end)
awesome.connect_signal("daemon::volume::muted", function ()
-- Pavucontrol already show volume, so do nothing
if client.focus and client.focus.class == "Pavucontrol" then return end
-- Remove existing notification
if notification then naughty.destroy(notification) end
notification = notify_volume_muted()
end)
|
-- Date palms.
--
-- Date palms grow in hot and dry desert, but they require water. This makes them
-- a bit harder to find. If found in the middle of the desert, their presence
-- indicates a water source below the surface.
--
-- As an additional feature (which can be disabled), dates automatically regrow after
-- harvesting (provided a male tree is sufficiently nearby).
-- If regrowing is enabled, then ripe dates will not hang forever. Most will disappear
-- (e.g. eaten by birds, ...), and a small fraction will drop as items.
-- © 2016, Rogier <rogier777@gmail.com>
local S = moretrees.intllib
-- Some constants
local dates_drop_ichance = 4
local stems_drop_ichance = 4
local flowers_wither_ichance = 3
-- implementation
local dates_regrow_prob
if moretrees.dates_regrow_unpollinated_percent <= 0 then
dates_regrow_prob = 0
elseif moretrees.dates_regrow_unpollinated_percent >= 100 then
dates_regrow_prob = 1
else
dates_regrow_prob = 1 - math.pow(moretrees.dates_regrow_unpollinated_percent/100, 1/flowers_wither_ichance)
end
-- Make the date palm fruit trunk a real trunk (it is generated as a fruit)
local trunk = minetest.registered_nodes["moretrees:date_palm_trunk"]
local ftrunk = {}
local fftrunk = {}
local mftrunk = {}
for k,v in pairs(trunk) do
ftrunk[k] = v
end
ftrunk.tiles = {}
for k,v in pairs(trunk.tiles) do
ftrunk.tiles[k] = v
end
ftrunk.drop = "moretrees:date_palm_trunk"
ftrunk.after_destruct = function(pos, oldnode)
local dates = minetest.find_nodes_in_area({x=pos.x-2, y=pos.y, z=pos.z-2}, {x=pos.x+2, y=pos.y, z=pos.z+2}, {"group:moretrees_dates"})
for _,datespos in pairs(dates) do
-- minetest.dig_node(datespos) does not cause nearby dates to be dropped :-( ...
local items = minetest.get_node_drops(minetest.get_node(datespos).name)
minetest.swap_node(datespos, biome_lib.air)
for _, itemname in pairs(items) do
minetest.add_item(datespos, itemname)
end
end
end
for k,v in pairs(ftrunk) do
mftrunk[k] = v
fftrunk[k] = v
end
fftrunk.tiles = {}
mftrunk.tiles = {}
for k,v in pairs(trunk.tiles) do
fftrunk.tiles[k] = v
mftrunk.tiles[k] = v
end
-- Make the different types of trunk distinguishable (but not too easily)
ftrunk.tiles[1] = "moretrees_date_palm_trunk_top.png^[transformR180"
ftrunk.description = ftrunk.description.." (gen)"
fftrunk.tiles[1] = "moretrees_date_palm_trunk_top.png^[transformR90"
mftrunk.tiles[1] = "moretrees_date_palm_trunk_top.png^[transformR-90"
minetest.register_node("moretrees:date_palm_fruit_trunk", ftrunk)
minetest.register_node("moretrees:date_palm_ffruit_trunk", fftrunk)
minetest.register_node("moretrees:date_palm_mfruit_trunk", mftrunk)
-- ABM to grow new date blossoms
local date_regrow_abm_spec = {
nodenames = { "moretrees:date_palm_ffruit_trunk", "moretrees:date_palm_mfruit_trunk" },
interval = moretrees.dates_flower_interval,
chance = moretrees.dates_flower_chance,
action = function(pos, node, active_object_count, active_object_count_wider)
local dates = minetest.find_nodes_in_area({x=pos.x-2, y=pos.y, z=pos.z-2}, {x=pos.x+2, y=pos.y, z=pos.z+2}, "group:moretrees_dates")
-- New blossom interval increases exponentially with number of dates already hanging
-- In addition: if more dates are hanging, the chance of picking an empty spot decreases as well...
if math.random(2^#dates) <= 2 then
-- Grow in area of 5x5 round trunk; higher probability in 3x3 area close to trunk
local dx=math.floor((math.random(50)-18)/16)
local dz=math.floor((math.random(50)-18)/16)
local datepos = {x=pos.x+dx, y=pos.y, z=pos.z+dz}
local datenode = minetest.get_node(datepos)
if datenode.name == "air" then
if node.name == "moretrees:date_palm_ffruit_trunk" then
minetest.swap_node(datepos, {name="moretrees:dates_f0"})
else
minetest.swap_node(datepos, {name="moretrees:dates_m0"})
end
end
end
end
}
if moretrees.dates_regrow_pollinated or moretrees.dates_regrow_unpollinated_percent > 0 then
minetest.register_abm(date_regrow_abm_spec)
end
-- Choose male or female palm, and spawn initial dates
-- (Instead of dates, a dates fruit trunk is generated with the tree. This
-- ABM converts the trunk to a female or male fruit trunk, and spawns some
-- hanging dates)
minetest.register_abm({
nodenames = { "moretrees:date_palm_fruit_trunk" },
interval = 1,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
local type
if math.random(100) <= moretrees.dates_female_percent then
type = "f"
minetest.swap_node(pos, {name="moretrees:date_palm_ffruit_trunk"})
else
type = "m"
minetest.swap_node(pos, {name="moretrees:date_palm_mfruit_trunk"})
end
local dates1 = minetest.find_nodes_in_area({x=pos.x-1, y=pos.y, z=pos.z-1}, {x=pos.x+1, y=pos.y, z=pos.z+1}, "air")
local genpos
for _,genpos in pairs(dates1) do
if math.random(100) <= 20 then
if type == "m" then
minetest.swap_node(genpos, {name = "moretrees:dates_n"})
else
minetest.swap_node(genpos, {name = "moretrees:dates_f4"})
end
end
end
local dates2 = minetest.find_nodes_in_area({x=pos.x-2, y=pos.y, z=pos.z-2}, {x=pos.x+2, y=pos.y, z=pos.z+2}, "air")
for _,genpos in pairs(dates2) do
if math.random(100) <= 5 then
if type == "m" then
minetest.swap_node(genpos, {name = "moretrees:dates_n"})
else
minetest.swap_node(genpos, {name = "moretrees:dates_f4"})
end
end
end
end,
})
-- Dates growing functions.
-- This is a bit complex, as the purpose is to find male flowers at horizontal distances of over
-- 100 nodes. As searching such a large area is time consuming, this is optimized in four ways:
-- - The search result (the locations of male trees) is cached, so that it can be used again
-- - Only 1/9th of the desired area is searched at a time. A new search is only performed if no male
-- flowers are found in the previously searched parts.
-- - Search results are shared with other female palms nearby.
-- - If previous searches for male palms have consumed too much CPU time, the search is skipped
-- (This means no male palms will be found, and the pollination of the flowers affected will be
-- delayed. If this happens repeatedly, eventually, the female flowers will wither...)
-- A caching method was selected that is suited for the case where most date trees are long-lived,
-- and where the number of trees nearby is limited:
-- - Locations of male palms are stored as metadata for every female palm. This means that a player
-- visiting a remote area with some date palms will not cause extensive searches for male palms as
-- long overdue blossoming ABMs are triggered for every date palm.
-- - Even when male palms *are* cut down, a cache refill will only be performed if the cached results do not
-- contain a male palm with blossoms.
-- The method will probably perform suboptimally:
-- - If female palms are frequently chopped down and replanted.
-- Freshly grown palms will need to search for male palms again
-- (this is mitigated by the long blossoming interval, which increases the chance that search
-- results have already been shared)
-- - If an area contains a large number of male and female palms.
-- In this area, every female palm will have an almost identical list of male palm locations
-- as metadata.
-- - If all male palms within range of a number of female palms have been chopped down (with possibly
-- new ones planted). Although an attempt was made to share search results in this case as well,
-- a number of similar searches will unavoidably be performed by the different female palms.
-- - If no male palms are in range of a female palm. In that case, there will be frequent searches
-- for newly-grown male palms.
-- Search statistics - used to limit the search load.
local sect_search_stats = {} -- Search statistics - server-wide
local function reset_sect_search_stats()
sect_search_stats.count = 0 -- # of searches
sect_search_stats.skip = 0 -- # of times skipped
sect_search_stats.sum = 0 -- total time spent
sect_search_stats.min = 999999999 -- min time spent
sect_search_stats.max = 0 -- max time spent
end
reset_sect_search_stats()
sect_search_stats.last_us = 0 -- last time a search was done (microseconds, max: 2^32)
sect_search_stats.last_s = 0 -- last time a search was done (system time in seconds)
-- Find male trunks in one section (=1/9 th) of the searchable area.
-- sect is -4 to 4, where 0 is the center section
local function find_fruit_trunks_near(ftpos, sect)
local r = moretrees.dates_pollination_distance + 2 * math.sqrt(2)
local sect_hr = math.floor(r / 3 + 0.9999)
local sect_vr = math.floor(r / 2 + 0.9999)
local t0us = core.get_us_time()
local t0s = os.time()
-- Compute elapsed time since last search.
-- Unfortunately, the time value wraps after about 71 minutes (2^32 microseconds),
-- so it must be corrected to obtain the actual elapsed time.
if t0us < sect_search_stats.last_us then
-- Correct a simple wraparound.
-- This is not sufficient, as the time value may have wrapped more than once...
sect_search_stats.last_us = sect_search_stats.last_us - 2^32
end
if t0s - sect_search_stats.last_s > 2^32/1000000 then
-- One additional correction is enough for our purposes.
-- For exact results, more corrections may be needed though...
-- (and even not applying this correction at all would still only yield
-- a minimal risk of a non-serious miscalculation...)
sect_search_stats.last_us = sect_search_stats.last_us - 2^32
end
-- Skip the search if it is consuming too much CPU time
if sect_search_stats.count > 0 and moretrees.dates_blossom_search_iload > 0
and sect_search_stats.sum / sect_search_stats.count > moretrees.dates_blossom_search_time_treshold
and t0us - sect_search_stats.last_us < moretrees.dates_blossom_search_iload * (sect_search_stats.sum / sect_search_stats.count) then
sect_search_stats.skip = sect_search_stats.skip + 1
return nil
end
local basevec = { x = ftpos.x + 2 * sect.x * sect_hr,
y = ftpos.y,
z = ftpos.z + 2 * sect.z * sect_hr}
-- find_nodes_in_area is limited to 82^3, make sure to not overrun it
local sizevec = { x = sect_hr, y = sect_vr, z = sect_hr }
if sect_hr * sect_hr * sect_vr > 41^3 then
sizevec = vector.apply(sizevec, function(a) return math.min(a, 41) end)
end
local all_palms = minetest.find_nodes_in_area(
vector.subtract(basevec, sizevec),
vector.add(basevec, sizevec),
{"moretrees:date_palm_mfruit_trunk", "moretrees:date_palm_ffruit_trunk"})
-- Collect different palms in separate lists.
local female_palms = {}
local male_palms = {}
local all_male_palms = {}
for _, pos in pairs(all_palms) do
if pos.x ~= ftpos.x or pos.y ~= ftpos.y or pos.z ~= ftpos.z then
local node = minetest.get_node(pos)
if node and node.name == "moretrees:date_palm_ffruit_trunk" then
table.insert(female_palms,pos)
elseif node then
table.insert(all_male_palms,pos)
-- In sector 0, all palms are of interest.
-- In other sectors, forget about palms that are too far away.
if sect == 0 then
table.insert(male_palms,pos)
else
local ssq = 0
for _, c in pairs({"x", "z"}) do
local dc = pos[c] - ftpos[c]
ssq = ssq + dc * dc
end
if math.sqrt(ssq) <= r then
table.insert(male_palms,pos)
end
end
end
end
end
-- Update search statistics
local t1us = core.get_us_time()
if t1us < t0us then
-- Wraparound. Assume the search lasted less than 2^32 microseconds (~71 min)
-- (so no need to apply another correction)
t0us = t0us - 2^32
end
sect_search_stats.last_us = t0us
sect_search_stats.last_s = t0s
sect_search_stats.count = sect_search_stats.count + 1
sect_search_stats.sum = sect_search_stats.sum + t1us-t0us
if t1us - t0us < sect_search_stats.min then
sect_search_stats.min = t1us - t0us
end
if t1us - t0us > sect_search_stats.max then
sect_search_stats.max = t1us - t0us
end
return male_palms, female_palms, all_male_palms
end
local function dates_print_search_stats(log)
local stats
if sect_search_stats.count > 0 then
stats = string.format("Male date tree searching stats: searches: %d/%d: average: %d µs (%d..%d)",
sect_search_stats.count, sect_search_stats.count + sect_search_stats.skip,
sect_search_stats.sum/sect_search_stats.count, sect_search_stats.min, sect_search_stats.max)
else
stats = string.format("Male date tree searching stats: searches: 0/0: average: (no searches yet)")
end
if log then
minetest.log("action", "[moretrees] " .. stats)
end
return true, stats
end
minetest.register_chatcommand("dates_stats", {
description = "Print male date palm search statistics",
params = "|chat|log|reset",
privs = { server = true },
func = function(name, param)
param = string.lower(string.trim(param))
if param == "" or param == "chat" then
return dates_print_search_stats(false)
elseif param == "log" then
return dates_print_search_stats(true)
elseif param == "reset" then
reset_sect_search_stats()
return true
else
return false, "Invalid subcommand; expected: '' or 'chat' or 'log' or 'reset'"
end
end,
})
-- Find the female trunk near the female flowers to be pollinated
local function find_female_trunk(fbpos)
local trunks = minetest.find_nodes_in_area({x=fbpos.x-2, y=fbpos.y, z=fbpos.z-2},
{x=fbpos.x+2, y=fbpos.y, z=fbpos.z+2},
"moretrees:date_palm_ffruit_trunk")
local ftpos
local d = 99
for x, pos in pairs(trunks) do
local ssq = 0
for _, c in pairs({"x", "z"}) do
local dc = pos[c] - fbpos[c]
ssq = ssq + dc * dc
end
if math.sqrt(ssq) < d then
ftpos = pos
d = math.sqrt(ssq)
end
end
return ftpos
end
-- Find male blossom near a male trunk,
-- the male blossom must be in range of a specific female blossom as well
local function find_male_blossom_near_trunk(fbpos, mtpos)
local r = moretrees.dates_pollination_distance
local blossoms = minetest.find_nodes_in_area({x=mtpos.x-2, y=mtpos.y, z=mtpos.z-2},
{x=mtpos.x+2, y=mtpos.y, z=mtpos.z+2},
"moretrees:dates_m0")
for x, mbpos in pairs(blossoms) do
local ssq = 0
for _, c in pairs({"x", "z"}) do
local dc = mbpos[c] - fbpos[c]
ssq = ssq + dc * dc
end
if math.sqrt(ssq) <= r then
return mbpos
end
end
end
-- Find a male blossom in range of a specific female blossom,
-- using a nested list of male blossom positions
local function find_male_blossom_in_mpalms(ftpos, fbpos, mpalms)
-- Process the elements of mpalms.sect (index -4 .. 4) in random order
-- First, compute the order in which the sectors will be searched
local sect_index = {}
local sect_rnd = {}
for i = -4,4 do
local n = math.random(1023)
sect_index[n] = i
table.insert(sect_rnd, n)
end
table.sort(sect_rnd)
-- Search the sectors
local sect_old = 0
local sect_time = minetest.get_gametime()
for _, n in pairs(sect_rnd) do
-- Record the oldest sector, so that it can be searched if no male
-- blossoms were found
if not mpalms.sect_time[sect_index[n]] then
sect_old = sect_index[n]
sect_time = 0
elseif mpalms.sect_time[sect_index[n]] < sect_time then
sect_old = sect_index[n]
sect_time = mpalms.sect_time[sect_index[n]]
end
if mpalms.sect[sect_index[n]] and #mpalms.sect[sect_index[n]] then
for px, mtpos in pairs(mpalms.sect[sect_index[n]]) do
local node = minetest.get_node(mtpos)
if node and node.name == "moretrees:date_palm_mfruit_trunk" then
local mbpos = find_male_blossom_near_trunk(fbpos, mtpos)
if mbpos then
return mbpos
end
elseif node and node.name ~= "ignore" then
-- no more male trunk here.
mpalms.sect[sect_index[n]][px] = nil
end
end
end
end
return nil, sect_old
end
-- Find a male blossom in range of a specific female blossom,
-- using the cache associated with the given female trunk
-- If necessary, recompute part of the cache
local last_search_result = {}
local function find_male_blossom_with_ftrunk(fbpos,ftpos)
local meta = minetest.get_meta(ftpos)
local mpalms
local cache_changed = true
-- Load cache. If distance has changed, start with empty cache instead.
local mpalms_dist = meta:get_int("male_palms_dist")
if mpalms_dist and mpalms_dist == moretrees.dates_pollination_distance then
mpalms = meta:get_string("male_palms")
if mpalms and mpalms ~= "" then
mpalms = minetest.deserialize(mpalms)
cache_changed = false
end
end
if not mpalms or not mpalms.sect then
mpalms = {}
mpalms.sect = {}
mpalms.sect_time = {}
meta:set_int("male_palms_dist", moretrees.dates_pollination_distance)
cache_changed = true
end
local fpalms_list
local all_mpalms_list
local sector0_searched = false
-- Always make sure that sector 0 is cached
if not mpalms.sect[0] then
mpalms.sect[0], fpalms_list, all_mpalms_list = find_fruit_trunks_near(ftpos, {x = 0, z = 0})
mpalms.sect_time[0] = minetest.get_gametime()
sector0_searched = true
cache_changed = true
last_search_result.female = fpalms_list
last_search_result.male = all_mpalms_list
end
-- Find male palms
local mbpos, sect_old = find_male_blossom_in_mpalms(ftpos, fbpos, mpalms)
-- If not found, (re)generate the cache for an additional sector. But don't search it yet (for performance reasons)
-- (Use the globally cached results if possible)
if not mbpos and not sector0_searched then
if not mpalms.sect_time[0] or mpalms.sect_time[0] == 0 or math.random(3) == 1 then
-- Higher probability of re-searching the center sector
sect_old = 0
end
-- Use globally cached result if possible
mpalms.sect[sect_old] = nil
if sect_old == 0 and mpalms.sect_time[0] and mpalms.sect_time[0] > 0
and last_search_result.male and #last_search_result.male then
for _, pos in pairs(last_search_result.female) do
if pos.x == ftpos.x and pos.y == ftpos.y and pos.z == ftpos.z then
mpalms.sect[sect_old] = last_search_result.male
-- Next time, don't use the cached result
mpalms.sect_time[sect_old] = nil
cache_changed = true
end
end
end
-- Else do a new search
if not mpalms.sect[sect_old] then
mpalms.sect[sect_old], fpalms_list, all_mpalms_list = find_fruit_trunks_near(ftpos, {x = (sect_old + 4) % 3 - 1, z = (sect_old + 4) / 3 - 1})
cache_changed = true
if sect_old == 0 then
-- Save the results if it is sector 0
-- (chance of reusing results from another sector are smaller)
last_search_result.female = fpalms_list
last_search_result.male = all_mpalms_list
end
if mpalms.sect[sect_old] then
mpalms.sect_time[sect_old] = minetest.get_gametime()
else
mpalms.sect_time[sect_old] = nil
end
end
end
-- Share search results with other female trunks in the same area
-- Note that the list of female trunks doesn't (shouldn't :-) contain the current female trunk.
if fpalms_list and #fpalms_list and #all_mpalms_list then
local all_mpalms = {}
all_mpalms.sect = {}
all_mpalms.sect_time = {}
all_mpalms.sect[0] = all_mpalms_list
-- Don't set sect_time[0], so that the cached sector will be re-searched soon (if necessary)
local all_mpalms_serialized = minetest.serialize(all_mpalms)
for _, pos in pairs(fpalms_list) do
local fmeta = minetest.get_meta(pos)
local fdist = fmeta:get_int("male_palms_dist")
if not fdist or fdist ~= moretrees.dates_pollination_distance then
fmeta:set_string("male_palms", all_mpalms_serialized)
fmeta:set_int("male_palms_dist", moretrees.dates_pollination_distance)
end
end
end
-- Save cache.
if cache_changed then
meta:set_string("male_palms", minetest.serialize(mpalms))
end
return mbpos
end
-- Find a male blossom in range of a specific female blossom
local function find_male_blossom(fbpos)
local ftpos = find_female_trunk(fbpos)
if ftpos then
return find_male_blossom_with_ftrunk(fbpos, ftpos)
end
return nil
end
-- Growing function for dates
local dates_growfn = function(pos, elapsed)
local node = minetest.get_node(pos)
local delay = moretrees.dates_grow_interval
local r = moretrees.dates_pollination_distance
local action
if not node then
return
elseif not moretrees.dates_regrow_pollinated and dates_regrow_prob == 0 then
-- Regrowing of dates is disabled.
if string.find(node.name, "moretrees:dates_f") then
minetest.swap_node(pos, {name="moretrees:dates_f4"})
elseif string.find(node.name, "moretrees:dates_m") then
minetest.swap_node(pos, {name="moretrees:dates_n"})
else
minetest.swap_node(pos, biome_lib.air)
end
return
elseif node.name == "moretrees:dates_f0" and math.random(100) <= 100 * dates_regrow_prob then
-- Dates grow unpollinated
minetest.swap_node(pos, {name="moretrees:dates_f1"})
action = "nopollinate"
elseif node.name == "moretrees:dates_f0" and moretrees.dates_regrow_pollinated and find_male_blossom(pos) then
-- Pollinate flowers
minetest.swap_node(pos, {name="moretrees:dates_f1"})
action = "pollinate"
elseif string.match(node.name, "0$") then
-- Make female unpollinated and male flowers last a bit longer
if math.random(flowers_wither_ichance) == 1 then
if node.name == "moretrees:dates_f0" then
minetest.swap_node(pos, {name="moretrees:dates_fn"})
else
minetest.swap_node(pos, {name="moretrees:dates_n"})
end
action = "wither"
else
action = "nowither"
end
elseif node.name == "moretrees:dates_f4" then
-- Remove dates, and optionally drop them as items
if math.random(dates_drop_ichance) == 1 then
if moretrees.dates_item_drop_ichance > 0 and math.random(moretrees.dates_item_drop_ichance) == 1 then
local items = minetest.get_node_drops(minetest.get_node(pos).name)
for _, itemname in pairs(items) do
minetest.add_item(pos, itemname)
end
end
minetest.swap_node(pos, {name="moretrees:dates_n"})
action = "drop"
else
action = "nodrop"
end
elseif string.match(node.name, "n$") then
-- Remove stems.
if math.random(stems_drop_ichance) == 1 then
minetest.swap_node(pos, biome_lib.air)
return "stemdrop"
end
action = "nostemdrop"
else
-- Grow dates
local offset = 18
local n = string.sub(node.name, offset)
minetest.swap_node(pos, {name=string.sub(node.name, 1, offset-1)..n+1})
action = "grow"
end
-- Don't catch up when elapsed time is large. Regular visits are needed for growth...
local timer = minetest.get_node_timer(pos)
timer:start(delay + math.random(moretrees.dates_grow_interval))
return action
end
-- Alternate growth function for dates.
-- It calls the primary growth function, but also measures CPU time consumed.
-- Use this function to analyze date growing performance.
local stat = {}
stat.count = 0
local dates_growfn_profiling = function(pos, elapsed)
local t0 = core.get_us_time()
local action = dates_growfn(pos, elapsed)
local t1 = core.get_us_time()
if t1 < t0 then
t1 = t1 + 2^32
end
stat.count = stat.count + 1
if not stat[action] then
stat[action] = {}
stat[action].count = 0
stat[action].sum = 0
stat[action].min = 9999999999
stat[action].max = 0
end
stat[action].count = stat[action].count + 1
stat[action].sum = stat[action].sum + t1-t0
if t1-t0 < stat[action].min then
stat[action].min = t1-t0
end
if t1-t0 > stat[action].max then
stat[action].max = t1-t0
end
if stat.count % 10 == 0 then
io.write(".")
io.flush()
end
if stat.count % 100 == 0 then
print(string.format("Date grow statistics %5d:", stat.count))
local sum = 0
local count = 0
if sect_search_stats.count > 0 and stat.pollinate and stat.pollinate.count > 0 then
print(string.format("\t%-12s: %6d (%4.1f%%): %6dus (%d..%d)",
"search", sect_search_stats.count,
100*sect_search_stats.count/stat.pollinate.count,
sect_search_stats.sum/sect_search_stats.count,
sect_search_stats.min, sect_search_stats.max))
else
print(string.format("\t%-12s: %6d (%4.1f%%): %6dus (%d..%d)",
"search", sect_search_stats.count,
0, 0, 0, 0))
end
for action,data in pairs(stat) do
if action ~= "count" then
count = count + data.count
sum = sum + data.sum
print(string.format("\t%-12s: %6d (%4.1f%%): %6dus (%d..%d)",
action, data.count,
100*data.count/stat.count, data.sum/data.count,
data.min, data.max))
end
end
print(string.format("\t%-12s: %6d ( 100%%): %6dus",
"TOTAL", count, sum/count))
end
end
-- Register dates
local dates_starttimer = function(pos, elapsed)
local timer = minetest.get_node_timer(pos)
local base_interval = moretrees.dates_grow_interval * 2 / 3
timer:set(base_interval + math.random(base_interval), elapsed or 0)
end
local dates_drop = {
items = {
{items = { "moretrees:date" }},
{items = { "moretrees:date" }},
{items = { "moretrees:date" }},
{items = { "moretrees:date" }},
{items = { "moretrees:date" }, rarity = 2 },
{items = { "moretrees:date" }, rarity = 2 },
{items = { "moretrees:date" }, rarity = 2 },
{items = { "moretrees:date" }, rarity = 2 },
{items = { "moretrees:date" }, rarity = 5 },
{items = { "moretrees:date" }, rarity = 5 },
{items = { "moretrees:date" }, rarity = 5 },
{items = { "moretrees:date" }, rarity = 5 },
{items = { "moretrees:date" }, rarity = 20 },
{items = { "moretrees:date" }, rarity = 20 },
{items = { "moretrees:date" }, rarity = 20 },
{items = { "moretrees:date" }, rarity = 20 },
}
}
for _,suffix in ipairs({"f0", "f1", "f2", "f3", "f4", "m0", "fn", "n"}) do
local name
if suffix == "f0" or suffix == "m0" then
name = S("Date Flowers")
elseif suffix == "n" or suffix == "fn" then
name = S("Date Stem")
else
name = S("Dates")
end
local dropfn = suffix == "f4" and dates_drop or ""
local datedef = {
description = name,
tiles = {"moretrees_dates_"..suffix..".png"},
visual_scale = 2,
drawtype = "plantlike",
paramtype = "light",
sunlight_propagates = true,
walkable = false,
groups = { fleshy=3, dig_immediate=3, flammable=2, moretrees_dates=1 },
inventory_image = "moretrees_dates_"..suffix..".png^[transformR0",
wield_image = "moretrees_dates_"..suffix..".png^[transformR90",
sounds = default.node_sound_defaults(),
drop = dropfn,
selection_box = {
type = "fixed",
fixed = {-0.3, -0.3, -0.3, 0.3, 3.5, 0.3}
},
on_timer = dates_growfn,
on_construct = (moretrees.dates_regrow_pollinated or moretrees.dates_regrow_unpollinated_percent > 0)
and dates_starttimer,
}
minetest.register_node("moretrees:dates_"..suffix, datedef)
end
-- If regrowing was previously disabled, but is enabled now, make sure timers are started for existing dates
if moretrees.dates_regrow_pollinated or moretrees.dates_regrow_unpollinated_percent > 0 then
local spec = {
name = "moretrees:restart_dates_regrow_timer",
nodenames = "group:moretrees_dates",
action = function(pos, node, active_object_count, active_object_count_wider)
local timer = minetest.get_node_timer(pos)
if not timer:is_started() then
dates_starttimer(pos)
else
local timeout = timer:get_timeout()
local elapsed = timer:get_elapsed()
if timeout - elapsed > moretrees.dates_grow_interval * 4/3 then
dates_starttimer(pos, math.random(moretrees.dates_grow_interval * 4/3))
end
end
end,
}
if minetest.register_lbm then
minetest.register_lbm(spec)
else
spec.interval = 3557
spec.chance = 10
minetest.register_abm(spec)
end
end
|
-- This file is automatically generated, do not edit!
-- Item data (c) Grinding Gear Games
local itemBases = ...
itemBases["Driftwood Club"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "10% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 6, PhysicalMax = 8, CritChanceBase = 5, AttackRateBase = 1.45, Range = 11, },
req = { str = 14, },
}
itemBases["Tribal Club"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "10% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 8, PhysicalMax = 13, CritChanceBase = 5, AttackRateBase = 1.4, Range = 11, },
req = { level = 5, str = 26, },
}
itemBases["Spiked Club"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "10% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 13, PhysicalMax = 16, CritChanceBase = 5, AttackRateBase = 1.45, Range = 11, },
req = { level = 10, str = 41, },
}
itemBases["Stone Hammer"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "15% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 15, PhysicalMax = 27, CritChanceBase = 5, AttackRateBase = 1.3, Range = 11, },
req = { level = 15, str = 56, },
}
itemBases["War Hammer"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "10% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 13, PhysicalMax = 31, CritChanceBase = 5, AttackRateBase = 1.45, Range = 11, },
req = { level = 20, str = 71, },
}
itemBases["Bladed Mace"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "10% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 19, PhysicalMax = 32, CritChanceBase = 5, AttackRateBase = 1.4, Range = 11, },
req = { level = 24, str = 83, },
}
itemBases["Ceremonial Mace"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "15% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 32, PhysicalMax = 40, CritChanceBase = 5, AttackRateBase = 1.2, Range = 11, },
req = { level = 28, str = 95, },
}
itemBases["Dream Mace"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "10% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 21, PhysicalMax = 43, CritChanceBase = 5, AttackRateBase = 1.4, Range = 11, },
req = { level = 32, str = 107, },
}
itemBases["Wyrm Mace"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, not_for_sale = true, maraketh = true, },
implicit = "4% increased Attack Speed",
weapon = { PhysicalMin = 28, PhysicalMax = 42, CritChanceBase = 5, AttackRateBase = 1.35, Range = 11, },
req = { level = 34, str = 118, },
}
itemBases["Petrified Club"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "10% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 31, PhysicalMax = 51, CritChanceBase = 5, AttackRateBase = 1.25, Range = 11, },
req = { level = 35, str = 116, },
}
itemBases["Barbed Club"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "10% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 33, PhysicalMax = 42, CritChanceBase = 5, AttackRateBase = 1.4, Range = 11, },
req = { level = 38, str = 125, },
}
itemBases["Rock Breaker"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "15% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 37, PhysicalMax = 69, CritChanceBase = 5, AttackRateBase = 1.15, Range = 11, },
req = { level = 41, str = 134, },
}
itemBases["Battle Hammer"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "10% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 25, PhysicalMax = 59, CritChanceBase = 5, AttackRateBase = 1.4, Range = 11, },
req = { level = 44, str = 143, },
}
itemBases["Flanged Mace"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "10% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 38, PhysicalMax = 63, CritChanceBase = 5, AttackRateBase = 1.3, Range = 11, },
req = { level = 47, str = 152, },
}
itemBases["Ornate Mace"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "15% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 53, PhysicalMax = 67, CritChanceBase = 5, AttackRateBase = 1.2, Range = 11, },
req = { level = 50, str = 161, },
}
itemBases["Phantom Mace"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "10% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 33, PhysicalMax = 69, CritChanceBase = 5, AttackRateBase = 1.4, Range = 11, },
req = { level = 53, str = 170, },
}
itemBases["Dragon Mace"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, not_for_sale = true, maraketh = true, },
implicit = "4% increased Attack Speed",
weapon = { PhysicalMin = 44, PhysicalMax = 66, CritChanceBase = 5, AttackRateBase = 1.35, Range = 11, },
req = { level = 55, str = 184, },
}
itemBases["Ancestral Club"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "10% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 48, PhysicalMax = 80, CritChanceBase = 5, AttackRateBase = 1.25, Range = 11, },
req = { level = 56, str = 179, },
}
itemBases["Tenderizer"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "10% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 49, PhysicalMax = 62, CritChanceBase = 5, AttackRateBase = 1.4, Range = 11, },
req = { level = 58, str = 185, },
}
itemBases["Gavel"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "15% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 54, PhysicalMax = 101, CritChanceBase = 5, AttackRateBase = 1.15, Range = 11, },
req = { level = 60, str = 212, },
}
itemBases["Legion Hammer"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "10% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 35, PhysicalMax = 81, CritChanceBase = 5, AttackRateBase = 1.4, Range = 11, },
req = { level = 62, str = 212, },
}
itemBases["Pernarch"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "10% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 49, PhysicalMax = 82, CritChanceBase = 5, AttackRateBase = 1.3, Range = 11, },
req = { level = 64, str = 212, },
}
itemBases["Auric Mace"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "15% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 65, PhysicalMax = 82, CritChanceBase = 5, AttackRateBase = 1.2, Range = 11, },
req = { level = 66, str = 212, },
}
itemBases["Nightmare Mace"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, },
implicit = "10% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 38, PhysicalMax = 80, CritChanceBase = 5, AttackRateBase = 1.4, Range = 11, },
req = { level = 68, str = 212, },
}
itemBases["Behemoth Mace"] = {
type = "One Handed Mace",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, not_for_sale = true, maraketh = true, },
implicit = "6% increased Attack Speed",
weapon = { PhysicalMin = 49, PhysicalMax = 74, CritChanceBase = 5, AttackRateBase = 1.35, Range = 11, },
req = { level = 70, str = 220, },
}
itemBases["Driftwood Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "10% increased Elemental Damage",
weapon = { PhysicalMin = 5, PhysicalMax = 8, CritChanceBase = 6, AttackRateBase = 1.55, Range = 11, },
req = { str = 8, int = 8, },
}
itemBases["Darkwood Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "12% increased Elemental Damage",
weapon = { PhysicalMin = 8, PhysicalMax = 12, CritChanceBase = 6, AttackRateBase = 1.5, Range = 11, },
req = { level = 5, str = 14, int = 14, },
}
itemBases["Bronze Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "12% increased Elemental Damage",
weapon = { PhysicalMin = 10, PhysicalMax = 19, CritChanceBase = 6, AttackRateBase = 1.4, Range = 11, },
req = { level = 10, str = 22, int = 22, },
}
itemBases["Quartz Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "20% increased Elemental Damage",
weapon = { PhysicalMin = 14, PhysicalMax = 22, CritChanceBase = 6.5, AttackRateBase = 1.4, Range = 11, },
req = { level = 15, str = 25, int = 35, },
}
itemBases["Iron Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "14% increased Elemental Damage",
weapon = { PhysicalMin = 18, PhysicalMax = 27, CritChanceBase = 6, AttackRateBase = 1.4, Range = 11, },
req = { level = 20, str = 38, int = 38, },
}
itemBases["Ochre Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "16% increased Elemental Damage",
weapon = { PhysicalMin = 17, PhysicalMax = 31, CritChanceBase = 6, AttackRateBase = 1.45, Range = 11, },
req = { level = 24, str = 44, int = 44, },
}
itemBases["Ritual Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "16% increased Elemental Damage",
weapon = { PhysicalMin = 21, PhysicalMax = 50, CritChanceBase = 6, AttackRateBase = 1.2, Range = 11, },
req = { level = 28, str = 51, int = 51, },
}
itemBases["Shadow Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "22% increased Elemental Damage",
weapon = { PhysicalMin = 29, PhysicalMax = 44, CritChanceBase = 6.2, AttackRateBase = 1.25, Range = 11, },
req = { level = 32, str = 52, int = 62, },
}
itemBases["Horned Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, not_for_sale = true, maraketh = true, },
implicit = "Damage Penetrates 4% Elemental Resistances",
weapon = { PhysicalMin = 27, PhysicalMax = 50, CritChanceBase = 6, AttackRateBase = 1.3, Range = 11, },
req = { level = 36, str = 66, int = 66, },
}
itemBases["Grinning Fetish"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "18% increased Elemental Damage",
weapon = { PhysicalMin = 24, PhysicalMax = 36, CritChanceBase = 6, AttackRateBase = 1.5, Range = 11, },
req = { level = 35, str = 62, int = 62, },
}
itemBases["Sekhem"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "18% increased Elemental Damage",
weapon = { PhysicalMin = 30, PhysicalMax = 55, CritChanceBase = 6, AttackRateBase = 1.25, Range = 11, },
req = { level = 38, str = 67, int = 67, },
}
itemBases["Crystal Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "30% increased Elemental Damage",
weapon = { PhysicalMin = 35, PhysicalMax = 52, CritChanceBase = 6.5, AttackRateBase = 1.25, Range = 11, },
req = { level = 41, str = 59, int = 85, },
}
itemBases["Lead Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "22% increased Elemental Damage",
weapon = { PhysicalMin = 38, PhysicalMax = 57, CritChanceBase = 6, AttackRateBase = 1.25, Range = 11, },
req = { level = 44, str = 77, int = 77, },
}
itemBases["Blood Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "24% increased Elemental Damage",
weapon = { PhysicalMin = 30, PhysicalMax = 55, CritChanceBase = 6, AttackRateBase = 1.4, Range = 11, },
req = { level = 47, str = 81, int = 81, },
}
itemBases["Royal Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "24% increased Elemental Damage",
weapon = { PhysicalMin = 34, PhysicalMax = 80, CritChanceBase = 6, AttackRateBase = 1.2, Range = 11, },
req = { level = 50, str = 86, int = 86, },
}
itemBases["Abyssal Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "30% increased Elemental Damage",
weapon = { PhysicalMin = 45, PhysicalMax = 67, CritChanceBase = 6.2, AttackRateBase = 1.25, Range = 11, },
req = { level = 53, str = 83, int = 99, },
}
itemBases["Stag Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, not_for_sale = true, maraketh = true, },
implicit = "Damage Penetrates 4% Elemental Resistances",
weapon = { PhysicalMin = 39, PhysicalMax = 72, CritChanceBase = 6, AttackRateBase = 1.3, Range = 11, },
req = { level = 55, str = 98, int = 98, },
}
itemBases["Karui Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "26% increased Elemental Damage",
weapon = { PhysicalMin = 37, PhysicalMax = 55, CritChanceBase = 6, AttackRateBase = 1.5, Range = 11, },
req = { level = 56, str = 96, int = 96, },
}
itemBases["Tyrant's Sekhem"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "26% increased Elemental Damage",
weapon = { PhysicalMin = 43, PhysicalMax = 80, CritChanceBase = 6, AttackRateBase = 1.25, Range = 11, },
req = { level = 58, str = 99, int = 99, },
}
itemBases["Opal Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "40% increased Elemental Damage",
weapon = { PhysicalMin = 49, PhysicalMax = 73, CritChanceBase = 6.5, AttackRateBase = 1.25, Range = 11, },
req = { level = 60, str = 95, int = 131, },
}
itemBases["Platinum Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "30% increased Elemental Damage",
weapon = { PhysicalMin = 51, PhysicalMax = 76, CritChanceBase = 6, AttackRateBase = 1.25, Range = 11, },
req = { level = 62, str = 113, int = 113, },
}
itemBases["Vaal Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "32% increased Elemental Damage",
weapon = { PhysicalMin = 37, PhysicalMax = 70, CritChanceBase = 6, AttackRateBase = 1.4, Range = 11, },
req = { level = 64, str = 113, int = 113, },
}
itemBases["Carnal Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "32% increased Elemental Damage",
weapon = { PhysicalMin = 41, PhysicalMax = 95, CritChanceBase = 6, AttackRateBase = 1.2, Range = 11, },
req = { level = 66, str = 113, int = 113, },
}
itemBases["Void Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, },
implicit = "40% increased Elemental Damage",
weapon = { PhysicalMin = 50, PhysicalMax = 76, CritChanceBase = 6.2, AttackRateBase = 1.25, Range = 11, },
req = { level = 68, str = 104, int = 122, },
}
itemBases["Sambar Sceptre"] = {
type = "Sceptre",
socketLimit = 3,
tags = { default = true, weapon = true, onehand = true, mace = true, one_hand_weapon = true, sceptre = true, not_for_sale = true, maraketh = true, },
implicit = "Damage Penetrates 6% Elemental Resistances",
weapon = { PhysicalMin = 42, PhysicalMax = 78, CritChanceBase = 6, AttackRateBase = 1.3, Range = 11, },
req = { level = 70, str = 121, int = 113, },
}
itemBases["Driftwood Maul"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, },
implicit = "30% increased Stun Duration on Enemies",
weapon = { PhysicalMin = 10, PhysicalMax = 16, CritChanceBase = 5, AttackRateBase = 1.3, Range = 13, },
req = { str = 20, },
}
itemBases["Tribal Maul"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, },
implicit = "30% increased Stun Duration on Enemies",
weapon = { PhysicalMin = 17, PhysicalMax = 25, CritChanceBase = 5, AttackRateBase = 1.25, Range = 13, },
req = { level = 8, str = 35, },
}
itemBases["Mallet"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, },
implicit = "30% increased Stun Duration on Enemies",
weapon = { PhysicalMin = 16, PhysicalMax = 33, CritChanceBase = 5, AttackRateBase = 1.3, Range = 13, },
req = { level = 12, str = 47, },
}
itemBases["Sledgehammer"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, },
implicit = "45% increased Stun Duration on Enemies",
weapon = { PhysicalMin = 25, PhysicalMax = 38, CritChanceBase = 5, AttackRateBase = 1.3, Range = 13, },
req = { level = 17, str = 62, },
}
itemBases["Jagged Maul"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, },
implicit = "30% increased Stun Duration on Enemies",
weapon = { PhysicalMin = 27, PhysicalMax = 49, CritChanceBase = 5, AttackRateBase = 1.3, Range = 13, },
req = { level = 22, str = 77, },
}
itemBases["Brass Maul"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, },
implicit = "30% increased Stun Duration on Enemies",
weapon = { PhysicalMin = 40, PhysicalMax = 60, CritChanceBase = 5, AttackRateBase = 1.2, Range = 13, },
req = { level = 27, str = 92, },
}
itemBases["Fright Maul"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, },
implicit = "30% increased Stun Duration on Enemies",
weapon = { PhysicalMin = 46, PhysicalMax = 62, CritChanceBase = 5, AttackRateBase = 1.25, Range = 13, },
req = { level = 32, str = 107, },
}
itemBases["Morning Star"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, not_for_sale = true, maraketh = true, },
implicit = "15% increased Area of Effect",
weapon = { PhysicalMin = 45, PhysicalMax = 68, CritChanceBase = 5, AttackRateBase = 1.25, Range = 13, },
req = { level = 34, str = 118, },
}
itemBases["Totemic Maul"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, },
implicit = "30% increased Stun Duration on Enemies",
weapon = { PhysicalMin = 57, PhysicalMax = 85, CritChanceBase = 5, AttackRateBase = 1.1, Range = 13, },
req = { level = 36, str = 119, },
}
itemBases["Great Mallet"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, },
implicit = "30% increased Stun Duration on Enemies",
weapon = { PhysicalMin = 43, PhysicalMax = 88, CritChanceBase = 5, AttackRateBase = 1.25, Range = 13, },
req = { level = 40, str = 131, },
}
itemBases["Steelhead"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, },
implicit = "45% increased Stun Duration on Enemies",
weapon = { PhysicalMin = 54, PhysicalMax = 81, CritChanceBase = 5, AttackRateBase = 1.3, Range = 13, },
req = { level = 44, str = 143, },
}
itemBases["Spiny Maul"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, },
implicit = "30% increased Stun Duration on Enemies",
weapon = { PhysicalMin = 55, PhysicalMax = 103, CritChanceBase = 5, AttackRateBase = 1.25, Range = 13, },
req = { level = 48, str = 155, },
}
itemBases["Plated Maul"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, },
implicit = "30% increased Stun Duration on Enemies",
weapon = { PhysicalMin = 72, PhysicalMax = 108, CritChanceBase = 5, AttackRateBase = 1.2, Range = 13, },
req = { level = 51, str = 164, },
}
itemBases["Dread Maul"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, },
implicit = "30% increased Stun Duration on Enemies",
weapon = { PhysicalMin = 77, PhysicalMax = 104, CritChanceBase = 5, AttackRateBase = 1.25, Range = 13, },
req = { level = 54, str = 173, },
}
itemBases["Solar Maul"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, not_for_sale = true, maraketh = true, },
implicit = "15% increased Area of Effect",
weapon = { PhysicalMin = 75, PhysicalMax = 113, CritChanceBase = 5, AttackRateBase = 1.25, Range = 13, },
req = { level = 56, str = 187, },
}
itemBases["Karui Maul"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, },
implicit = "45% increased Stun Duration on Enemies",
weapon = { PhysicalMin = 112, PhysicalMax = 168, CritChanceBase = 5, AttackRateBase = 1, Range = 13, },
req = { level = 57, str = 182, },
}
itemBases["Colossus Mallet"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, },
implicit = "30% increased Area Damage",
weapon = { PhysicalMin = 65, PhysicalMax = 135, CritChanceBase = 5.5, AttackRateBase = 1.3, Range = 13, },
req = { level = 59, str = 188, },
}
itemBases["Piledriver"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, },
implicit = "20% reduced Enemy Stun Threshold",
weapon = { PhysicalMin = 77, PhysicalMax = 115, CritChanceBase = 5, AttackRateBase = 1.35, Range = 13, },
req = { level = 61, str = 212, },
}
itemBases["Meatgrinder"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, },
implicit = "5% chance to deal Double Damage",
weapon = { PhysicalMin = 74, PhysicalMax = 138, CritChanceBase = 5, AttackRateBase = 1.25, Range = 13, },
req = { level = 63, str = 212, },
}
itemBases["Imperial Maul"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, },
implicit = "10% increased Strength",
weapon = { PhysicalMin = 102, PhysicalMax = 153, CritChanceBase = 5, AttackRateBase = 1.1, Range = 13, },
req = { level = 65, str = 212, },
}
itemBases["Terror Maul"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, },
implicit = "25% chance to double Stun Duration",
weapon = { PhysicalMin = 101, PhysicalMax = 137, CritChanceBase = 6, AttackRateBase = 1.15, Range = 13, },
req = { level = 67, str = 212, },
}
itemBases["Coronal Maul"] = {
type = "Two Handed Mace",
socketLimit = 6,
tags = { default = true, weapon = true, twohand = true, mace = true, two_hand_weapon = true, not_for_sale = true, maraketh = true, },
implicit = "20% increased Area of Effect",
weapon = { PhysicalMin = 91, PhysicalMax = 136, CritChanceBase = 5, AttackRateBase = 1.2, Range = 13, },
req = { level = 69, str = 220, },
}
|
Lexer = require 'lexer'
Parser = require 'parser'
examples = {
[1] = [[-~not-~#dog and friend + cheese]],
[2] = [[{['-'] = 'what', happy = true, ['rain'] = 'nice'; 5+5,}]],
[3] = [[wow.would['you']():look(at).that]],
[4] = [[x.y:z('heh')]],
[5] = [['hello' .. "world"]],
[6] = [[
function testFunction(word)
return "lol what's up" .. word
end]],
[7] = io.open('parser.lua', 'r'):read('a'),
[8] = io.open('lexer.lua', 'r'):read('a'),
}
lexes = {}
function printRecursive(node, indent)
indent = indent or 0
if node then
if type(node) == 'table' then
for k,v in pairs(node) do
printRecursive(v, indent + 1)
end
else
print(string.rep(' ', indent) .. tostring(node))
end
end
end
function printLex(lex)
for i,token in ipairs(lex) do
print(token.token, token.type)
end
end
--Used to reload the modules and re-run the tests while I was developing in the Lua REPL
function r()
package.loaded['lexer'] = nil
package.loaded['parser'] = nil
dofile 'parse_test.lua'
end
for i,example in ipairs(examples) do
local tokens = Lexer.tokenize(example)
print('Lexed ' .. #tokens .. ' tokens for example ' .. i)
table.insert(lexes, tokens)
end
-- verboseMode = true
parses = {
Parser(lexes[1]):parse_exp(),
Parser(lexes[2]):parse_exp(),
Parser(lexes[3]):parse_exp(),
Parser(lexes[4]):parse_exp(),
Parser(lexes[5]):parse_exp(),
Parser(lexes[6]):parse_chunk(),
Parser(lexes[7]):parse_chunk(),
Parser(lexes[8]):parse_chunk(),
}
|
return {
name = "Bomb",
desc = "Explosive fun",
sprite = 'bomb',
usage = 'bomb'
}
|
-- for Super Metroid
script_filename = @@LUA_SCRIPT_FILENAME@@
script_dir = script_filename:match("^(.*[/\\])")
-- first instructions of a wait for NMI loop
wait_start_addrs = {0x808343, 0x82e526, 0x85813c, 0x82e06b}
-- the first instruction after those loops (in no particular order)
wait_end_addrs = {0x808348, 0x82e52b, 0x858141, 0x82e070}
-- first instruction of NMI handler
nmi_addr = 0x9583
-- first instruction of reset handler
reset_addr = 0x841c
-- doors wait for the APU to complete, which means they are a big problem!
-- function that checks if the APU is done
door_check_addr = 0x82e2b0
-- if the function decides it is done, this addr is hit and next frame will
-- continue loading
door_pass_addr = 0x82e2d3
out_f = nil
-- are we waiting? where did we start?
currently_waiting = false
wait_frame = 0
wait_hcounter = 0
wait_vcounter = 0
-- how many times has the game accessed the hardware registers?
apu_reads = 0
apu_writes = 0
joy_reads = 0
joy_writes = 0
door_check = 0
door_pass = 0
joy_regs = {0x4218, 0x4219, 0x421A, 0x421B, 0x421C, 0x421D, 0x421E, 0x421F,
0x4016, 0x4017}
apu_regs = {0x2140, 0x2141, 0x2142, 0x2143}
-- we need to know when latches happened relative to NMI so we can insert
-- frequency adjustments at the appropriate points
function latch_handler()
local out_str = string.format("l,%d,%d,%d\n",
movie.currentframe(),
memory.getregister("vcounter"),
memory.getregister("hcounter")
)
if out_f ~= nil then
out_f:write(out_str)
end
end
callback.register("latch", latch_handler)
-- we keep track of APU and joypad hardware registers more for curiousity than
-- any useful purpose
function apu_looked(addr, value) apu_reads = apu_reads + 1 end
function apu_touched(addr, value) apu_writes = apu_writes + 1 end
function joy_looked(addr, value) joy_reads = joy_reads + 1 end
function joy_touched(addr, value) joy_writes = joy_writes + 1 end
-- register the hardware register access. the game can access them through any
-- of 128 different banks, so we have to stick our callbacks at all of them.
for bank=0,0x7F do
if bank >= 0x40 then bank = bank + 0x40 end
bank = bank * 0x10000
for i, apu_reg in ipairs(apu_regs) do
memory.registerread("BUS", bank+apu_reg, apu_looked)
memory.registerwrite("BUS", bank+apu_reg, apu_touched)
end
for i, joy_reg in ipairs(joy_regs) do
memory.registerread("BUS", bank+joy_reg, joy_looked)
memory.registerwrite("BUS", bank+joy_reg, joy_touched)
end
end
function started_waiting(addr, value)
if not currently_waiting then
-- if we're not waiting yet, note that we started here. otherwise, we're
-- just in the wait loop still.
wait_frame = movie.currentframe()
wait_hcounter = memory.getregister("hcounter")
wait_vcounter = memory.getregister("vcounter")
currently_waiting = true
end
end
function ended_waiting(addr, value)
currently_waiting = false
end
function nmi_fired(addr, value)
local nmi_frame, nmi_hcounter, nmi_vcounter
nmi_frame = movie.currentframe()
nmi_hcounter = memory.getregister("hcounter")
nmi_vcounter = memory.getregister("vcounter")
-- if we never ended waiting, then, well, we have now!
if not currently_waiting then
wait_frame = nmi_frame
wait_hcounter = nmi_hcounter
wait_vcounter = nmi_vcounter
end
local out_str = string.format('n,'..string.rep("%d,", 11).."%d\n",
wait_frame,
wait_vcounter,
wait_hcounter,
nmi_frame,
nmi_vcounter,
nmi_hcounter,
apu_reads,
apu_writes,
joy_reads,
joy_writes,
door_check,
door_pass
)
out_f:write(out_str)
currently_waiting = false
apu_reads = 0
apu_writes = 0
joy_reads = 0
joy_writes = 0
door_check = 0
door_pass = 0
end
function door_check_hit(addr, value) door_check = 1 end
function door_pass_hit(addr, value) door_pass = 1 end
function measure(out_fname)
-- register the addresses we were given
for i, wait_start_addr in ipairs(wait_start_addrs) do
memory.registerexec("BUS", wait_start_addr, started_waiting)
end
for i, wait_end_addr in ipairs(wait_end_addrs) do
memory.registerexec("BUS", wait_end_addr, ended_waiting)
end
memory.registerexec("BUS", nmi_addr, nmi_fired)
memory.registerexec("BUS", door_check_addr, door_check_hit)
memory.registerexec("BUS", door_pass_addr, door_pass_hit)
out_f = io.open(script_dir .. "/" .. out_fname, "w")
out_f:write("hello from measure_emulator.lua v1\n")
out_f:write(string.format("c,%d,%d\n",
bsnes.get_cpu_frequency(), bsnes.get_smp_frequency()))
end
|
print("CTEST_FULL_OUTPUT")
require "Scene"
function expectSuccess(script)
print("Expect success:", script)
loadstring(script)()
print("OK!")
end
function expectAnythingButCrash(script)
print("Expect success or failure but no crash:", script)
local f = loadstring(script)
local success, retval = pcall(f)
if success then
print("OK! Call succeeded")
else
print("OK! Call reported an error:", retval)
end
end
function expectError(script)
print("Expect error:", script)
local f = loadstring(script)
local success, retval = pcall(f)
if success then
error("Should have failed!")
end
print("OK! Reported error:", retval)
end
expectSuccess [[MatrixTransform{}.Matrix = osg.Matrixd()]]
expectAnythingButCrash [[MatrixTransform{}.Matrix = osg.Matrixf()]]
expectSuccess [[MatrixTransform{}.Matrix = MatrixTransform{}.Matrix]]
-- Invalid types for property
expectError [[MatrixTransform{}.Matrix = nil]]
expectError [[MatrixTransform{}.Matrix = osg.Matrixd():makeIdentity()]] -- this is a "void" pushed as a "nil"
print("Done!")
|
#!/usr/bin/env bcc-lua
--[[
Copyright 2016 GitHub, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]
local ffi = require("ffi")
return function(BPF)
local b = BPF:new{src_file="bashreadline.c", debug=0}
b:attach_uprobe{name="/bin/bash", sym="readline", fn_name="printret", retprobe=true}
local function print_readline(cpu, event)
print("%-9s %-6d %s" % {os.date("%H:%M:%S"), tonumber(event.pid), ffi.string(event.str)})
end
b:get_table("events"):open_perf_buffer(print_readline, "struct { uint64_t pid; char str[80]; }", nil)
print("%-9s %-6s %s" % {"TIME", "PID", "COMMAND"})
b:perf_buffer_poll_loop()
end
|
require 'loadcaffe'
prototxt_name = '/home/zagoruys/deploy.prototxt'
binary_name = '/home/zagoruys/bvlc_reference_caffenet.caffemodel'
model = loadcaffe.load(prototxt_name, binary_name, 'ccn2')
|
local util = {}
util.colorsUsed = {}
util.bg = "#000000"
util.fg = "#ffffff"
local function hexToRgb(hex_str)
local hex = "[abcdef0-9][abcdef0-9]"
local pat = "^#(" .. hex .. ")(" .. hex .. ")(" .. hex .. ")$"
hex_str = string.lower(hex_str)
assert(string.find(hex_str, pat) ~= nil, "hex_to_rgb: invalid hex_str: " .. tostring(hex_str))
local r, g, b = string.match(hex_str, pat)
return { tonumber(r, 16), tonumber(g, 16), tonumber(b, 16) }
end
---@param fg string foreground color
---@param bg string background color
---@param alpha number number between 0 and 1. 0 results in bg, 1 results in fg
function util.blend(fg, bg, alpha)
bg = hexToRgb(bg)
fg = hexToRgb(fg)
local blendChannel = function(i)
local ret = (alpha * (fg[i]) + ((1 - alpha) * (bg[i])))
return math.floor(math.min(math.max(0, ret), 255) + .5)
end
return string.format("#%02X%02X%02X", blendChannel(1), blendChannel(2), blendChannel(3))
end
function util.darken(hex, amount, bg) return util.blend(hex, bg or util.bg, math.abs(amount)) end
function util.lighten(hex, amount, fg) return util.blend(hex, fg or util.fg, math.abs(amount)) end
function util.highlight(group, color)
if color.fg then util.colorsUsed[color.fg] = true end
if color.bg then util.colorsUsed[color.bg] = true end
if color.sp then util.colorsUsed[color.sp] = true end
local style = color.style and "gui=" .. color.style or "gui=NONE"
local fg = color.fg and "guifg=" .. color.fg or "guifg=NONE"
local bg = color.bg and "guibg=" .. color.bg or "guibg=NONE"
local sp = color.sp and "guisp=" .. color.sp or ""
vim.cmd("highlight " .. group .. " " .. style .. " " .. fg .. " " .. bg .. " " .. sp)
if color.link then vim.cmd("highlight! link " .. group .. " " .. color.link) end
end
function util.debug(colors)
colors = colors or require("tokyonight.colors")
-- Dump unused colors
for name, color in pairs(colors) do
if type(color) == "table" then
util.debug(color)
else
if util.colorsUsed[color] == nil then print("not used: " .. name .. " : " .. color) end
end
end
end
---@param config Config
function util.autocmds(config)
vim.cmd [[augroup TokyoNight]]
vim.cmd [[ autocmd!]]
if config.dev then
vim.cmd [[ autocmd BufWritePost */lua/tokyonight/** nested colorscheme tokyonight]]
end
for _, sidebar in ipairs(config.sidebars) do
if sidebar == "terminal" then
vim.cmd [[ autocmd TermOpen * setlocal winhighlight=Normal:NormalSB,SignColumn:SignColumnSB]]
else
vim.cmd([[ autocmd BufWinEnter ]] .. sidebar ..
[[ setlocal winhighlight=Normal:NormalSB,SignColumn:SignColumnSB]])
end
end
vim.cmd [[augroup end]]
end
-- Simple string interpolation.
--
-- Example template: "${name} is ${value}"
--
---@param str string template string
---@param table table key value pairs to replace in the string
function util.template(str, table)
return (str:gsub("($%b{})", function(w) return table[w:sub(3, -2)] or w end))
end
function util.syntax(syntax) for group, colors in pairs(syntax) do util.highlight(group, colors) end end
---@param colors ColorScheme
function util.terminal(colors)
-- dark
vim.g.terminal_color_0 = colors.terminal_black
vim.g.terminal_color_8 = colors.terminal_black
-- light
vim.g.terminal_color_7 = colors.fg_dark
vim.g.terminal_color_15 = colors.fg
-- colors
vim.g.terminal_color_1 = colors.red
vim.g.terminal_color_9 = colors.red
vim.g.terminal_color_2 = colors.green
vim.g.terminal_color_10 = colors.green
vim.g.terminal_color_3 = colors.yellow
vim.g.terminal_color_11 = colors.yellow
vim.g.terminal_color_4 = colors.blue
vim.g.terminal_color_12 = colors.blue
vim.g.terminal_color_5 = colors.magenta
vim.g.terminal_color_13 = colors.magenta
vim.g.terminal_color_6 = colors.cyan
vim.g.terminal_color_14 = colors.cyan
end
---@param theme Theme
function util.load(theme)
vim.cmd("hi clear")
if vim.fn.exists("syntax_on") then vim.cmd("syntax reset") end
vim.o.background = "dark"
vim.o.termguicolors = true
vim.g.colors_name = "tokyonight"
-- load base theme
util.syntax(theme.base)
-- load syntax for plugins and terminal async
local async
async = vim.loop.new_async(vim.schedule_wrap(function()
util.terminal(theme.colors)
util.syntax(theme.plugins)
util.autocmds(theme.config)
async:close()
end))
async:send()
end
return util
|
local NAME, S = ...
S.VERSION = GetAddOnMetadata(NAME, "Version")
S.BUILD = "Release"
KethoInstanceTimer = LibStub("AceAddon-3.0"):NewAddon(NAME, "AceEvent-3.0", "AceConsole-3.0", "LibSink-2.0")
local KIT = KethoInstanceTimer
KIT.S = S -- debug purpose
S.isClassic = (WOW_PROJECT_ID == WOW_PROJECT_CLASSIC)
local L = S.L
local profile, char
function KIT:RefreshDB1()
profile = self.db.profile
char = self.db.char
end
local date, time = date, time
local floor = floor
local format, gsub = format, gsub
S.args = {}
local args = S.args
--------------
--- Events ---
--------------
S.Events = {
"PLAYER_ENTERING_WORLD",
"COMBAT_LOG_EVENT_UNFILTERED",
"CHAT_MSG_SYSTEM",
-- fallback/secondary events
"LFG_PROPOSAL_SUCCEEDED",
"LFG_COMPLETION_REWARD",
"SCENARIO_COMPLETED",
}
S.ClassicEvents = {
"PLAYER_ENTERING_WORLD",
"COMBAT_LOG_EVENT_UNFILTERED",
"CHAT_MSG_SYSTEM",
}
----------------------
--- Instance Types ---
----------------------
-- also used for color
S.pve = {
party = "A8A8FF",
raid = "FF7F00",
scenario = "FFFFFF",
seasonal = "FFD700", -- imaginary instance type
}
S.pvp = {
pvp = true,
arena = true,
}
S.npc = {
Creature = true,
Vehicle = true,
}
-- garrison is classified as a "party" instancetype, which is a false positive for us
-- http://wow.gamepedia.com/InstanceMapID#Garrisons
S.garrison = {
[1152] = true, -- FW Horde Garrison Level 1
[1330] = true, -- FW Horde Garrison Level 2
[1153] = true, -- FW Horde Garrison Level 3
[1154] = true, -- FW Horde Garrison Level 4
[1158] = true, -- SMV Alliance Garrison Level 1
[1331] = true, -- SMV Alliance Garrison Level 2
[1159] = true, -- SMV Alliance Garrison Level 3
[1160] = true, -- SMV Alliance Garrison Level 4
}
-- http://wow.gamepedia.com/DifficultyID
-- GetDifficultyInfo(difficultyID)
S.difficulty = {}
if not S.isClassic then
for i = 1, 30 do
S.difficulty[i] = GetDifficultyInfo(i)
end
end
local normalRaid = {
[3] = true, -- "10 Player" raid
[4] = true, -- "25 Player" raid
[5] = true, -- "10 Player (Heroic)" raid
[6] = true, -- "25 Player (Heroic)" raid
[14] = true, -- "Normal" raid
[15] = true, -- "Heroic" raid
[16] = true, -- "Mythic" raid
}
function S.IsNormalRaid()
return normalRaid[select(3, GetInstanceInfo())]
end
--------------
--- Bosses ---
--------------
-- all normal dungeons are a scenario now
-- there is no need to check for those specific boss deaths, since the fallback events will fire
S.BossIDs = { -- untested
-- [60] Classic
[11502] = true, -- Ragnaros; Molten Core
[11583] = true, -- Nefarian; Blackwing Lair
[15339] = true, -- Ossirian the Unscarred; Ruins of Ahn'Qiraj
[15727] = true, -- C'Thun; Temple of Ahn'Qiraj
-- [70] The Burning Crusade
[15690] = true, -- Prince Malchezaar; Karazhan
[17257] = true, -- Magtheridon; Hellfire Citadel: Magtheridon's Lair
[17968] = true, -- Archimonde; Caverns of Time: Hyjal Summit
[19044] = true, -- Gruul the Dragonkiller; Gruul's Lair
[19622] = true, -- Kael'thas Sunstrider; Tempest Keep: The Eye
[21212] = true, -- Lady Vashj; Coilfang Reservoir: Serpentshrine Cavern
[22917] = true, -- Illidan Stormrage; Black Temple
[25315] = true, -- Kil'jaeden; Sunwell Plateau
-- [80] Wrath of the Lich King
[10184] = true, -- Onyxia; Onyxia's Lair
[15990] = true, -- Kel'Thuzad; Naxxramas
[28859] = true, -- Malygos; The Nexus: The Eye of Eternity
[28860] = true, -- Sartharion; Wyrmrest Temple: The Obsidian Sanctum
[33288] = true, -- Yogg-Saron; Ulduar
[34564] = true, -- Anub'arak; Crusaders' Coliseum: Trial of the Crusader
[36597] = true, -- The Lich King; Icecrown Citadel
[38433] = true, -- Toravon the Ice Watcher; Vault of Archavon
[39863] = true, -- Halion; Wyrmrest Temple: The Ruby Sanctum
-- [85] Cataclysm
[41376] = true, -- Nefarian; Blackwing Descent
[43324] = true, -- Cho'gall; The Bastion of Twilight
[46753] = true, -- Al'Akir; Throne of the Four Winds
[52363] = true, -- Occu'thar; Baradin Hold
[52409] = true, -- Ragnaros; Firelands
[56173] = true, -- Deathwing (no death); Dragon Soul
-- [90] Mists of Pandaria
[60400] = true, -- Jan-xi; Mogu'shan Vaults
[60999] = true, -- Sha of Fear; Terrace of Endless Spring
[62837] = true, -- Grand Empress Shek'zeer; Heart of Fear
-- [100] Warlords of Draenor
[77428] = true, -- Imperator Mar'gok; Highmaul
[77325] = true, -- Blackhand; Blackrock Foundry
[91331] = true, -- Archimonde; Hellfire Citadel
-- [110] Legion (untested)
[102206] = true, -- Xavius; The Emerald Nightmare
[110533] = true, -- Gul'dan; The Nighthold
[114537] = true, -- Helya; Trial of Valor
[117269] = true, -- Kil'jaeden; Tomb of Sargeras
[124828] = true, -- Argus the Unmaker; Antorus, the Burning Throne
-- [120] Battle for Azeroth (untested)
[132998] = true, -- G'huun; Uldir
[149684] = true, -- Lady Jaina Proudmoore; Battle of Dazar'alor
[150397] = true, -- King Mechagon; Operation: Mechagon
[155126] = true, -- Queen Azshara; The Eternal Palace
}
S.ClassicBossIDs = {
[639] = true, -- Edwin VanCleef; Deadmines
[1716] = true, -- Bazil Thredd; Stormwind Stockade
[1853] = true, -- Darkmaster Gandling; Scholomance
[2748] = true, -- Archaedas; Uldaman
[3654] = true, -- Mutanus the Devourer; Wailing Caverns
[3977] = true, -- High Inquisitor Whitemane; Scarlet Monastery
[4275] = true, -- Archmage Arugal; Shadowfang Keep
[4421] = true, -- Charlga Razorflank; Razorfen Kraul
[4829] = true, -- Aku'mai; Blackfathom Deeps
[5709] = true, -- Shade of Eranikus; Sunken Temple
[7267] = true, -- Chief Ukorz Sandscalp; Zul'Farrak
[7358] = true, -- Amnennar the Coldbringer; Razorfen Downs
[7800] = true, -- Mekgineer Thermaplugg; Gnomeregan
[9019] = true, -- Emperor Dagran Thaurissan; Blackrock Depths
[9568] = L["Lower Blackrock Spire"], -- Overlord Wyrmthalak
[10363] = L["Upper Blackrock Spire"], -- General Drakkisath
[10813] = L["Stratholme - Main Gate"], -- Balnazzar
[10440] = L["Stratholme - Service Entrance"], -- Lord Aurius Rivendare
[11501] = true, -- King Gordok; Dire Maul
[11520] = true, -- Taragaman the Hungerer; Ragefire Chasm
[12201] = true, -- Princess Theradras; Maraudon
}
-- /run for i = 1, GetNumRFDungeons() do print(GetRFDungeonInfo(i)) end
-- GetLFGDungeonInfo(i)
S.DungeonName = {}
-- remap boss id to localized dungeon names
function S.RemapDungeon() -- wait for init S.DungeonName
S.DungeonIDs = {
-- Seasonal
[23682] = S.DungeonName[285], -- "The Headless Horseman"; "Headless Horseman"; Hallow's End
[25740] = S.DungeonName[286], -- "The Frost Lord Ahune"; "Ahune"; Midsummer Fire Festival; transforms into "Frozen Core"
[25865] = S.DungeonName[286], -- "The Frost Lord Ahune"; "Frozen Core"; Midsummer Fire Festival
[23872] = S.DungeonName[287], -- "Coren Direbrew", Brewfest
[36296] = S.DungeonName[288], -- "The Crown Chemical Co."; "Apothecary Hummel"; Love is in the Air
[36565] = S.DungeonName[288], -- "The Crown Chemical Co."; "Apothecary Baxter"; Love is in the Air
[36272] = S.DungeonName[288], -- "The Crown Chemical Co."; "Apothecary Frye"; Love is in the Air
-- Multiple Parts Dungeon
[12258] = S.DungeonName[26], -- "Maraudon - Foulspore Cavern"; Razorlash
[12236] = S.DungeonName[272], -- "Maraudon - The Wicked Grotto"; Lord Vyletongue
[12201] = S.DungeonName[273], -- "Maraudon - Earth Song Falls"; Princess Theradras
[9018] = S.DungeonName[30], -- "Blackrock Depths - Detention Block"; High Interrogator Gerstahn
[9019] = S.DungeonName[276], -- "Blackrock Depths - Upper City"; Emperor Dagran Thaurissan
[11486] = S.DungeonName[36], -- "Dire Maul - Capital Gardens"; Prince Tortheldrin
[11492] = S.DungeonName[34], -- "Dire Maul - Warpwood Quarter"; Alzzin the Wildshaper
[11501] = S.DungeonName[38], -- "Dire Maul - Gordok Commons"; King Gordok
[10813] = S.DungeonName[40], -- "Stratholme - Main Gate"; Balnazzar
[45412] = S.DungeonName[274], -- "Stratholme - Service Entrance"; Lord Aurius Rivendare
[9568] = S.DungeonName[32], -- "Lower Blackrock Spire"; Overlord Wyrmthalak
[10363] = S.DungeonName[330], -- "Upper Blackrock Spire"; General Drakkisath
[77120] = S.DungeonName[860], -- "Upper Blackrock Spire" (WoD); Warlord Zaela
-- [85] Cataclysm
-- Dragon Soul
[55689] = S.DungeonName[416], -- "The Siege of Wyrmrest Temple"; Hagara the Stormbinder
[56173] = S.DungeonName[417], -- "Fall of Deathwing"; Deathwing (no death)
-- [90] Mists of Pandaria
-- ...
-- [100] Warlords of Draenor
-- Highmaul
[78491] = S.DungeonName[849], -- "Walled City"; Brackenspore
[79015] = S.DungeonName[850], -- "Arcane Sanctum"; Ko'ragh
[77428] = S.DungeonName[851], -- "Imperator's Rise"; Imperator Mar'gok
-- Blackrock Foundry
[76806] = S.DungeonName[847], -- "Slagworks"; "Heart of the Mountain" (Blast Furnace)
[77692] = S.DungeonName[846], -- "The Black Forge"; "Kromog"
[77557] = S.DungeonName[848], -- "Iron Assembly"; "Admiral Gar'an"
[77231] = S.DungeonName[848], -- "Iron Assembly"; "Enforcer Sorka"
[77477] = S.DungeonName[848], -- "Iron Assembly"; "Marak the Blooded"
[77325] = S.DungeonName[823], -- "Blackhand's Crucible"; "Blackhand"
-- Hellfire Citadel
[90435] = S.DungeonName[982], -- "Hellbreach"; "Kormrok"
[91809] = S.DungeonName[983], -- "Halls of Blood"; "Gorefiend"
[93439] = S.DungeonName[984], -- "Bastion of Shadows"; "Tyrant Velhari"
[91349] = S.DungeonName[985], -- "Destructor's Rise"; "Mannoroth"
[91331] = S.DungeonName[986], -- "The Black Gate"; "Archimonde"
-- [110] Legion
-- ...
}
end
S.SpecialDungeon = {
[285] = true, -- "The Headless Horseman"; Hallow's End
[286] = true, -- "The Frost Lord Ahune"; Midsummer Fire Festival
[287] = true, -- "Coren Direbrew", Brewfest
[288] = true, -- "The Crown Chemical Co."; Love is in the Air
[26] = true, -- "Maraudon - Foulspore Cavern"
[272] = true, -- "Maraudon - The Wicked Grotto"
[273] = true, -- "Maraudon - Earth Song Falls"
[30] = true, -- "Blackrock Depths - Detention Block"
[276] = true, -- "Blackrock Depths - Upper City"
[34] = true, -- "Dire Maul - Warpwood Quarter"
[36] = true, -- "Dire Maul - Capital Gardens"
[38] = true, -- "Dire Maul - Gordok Commons"
[40] = true, -- "Stratholme - Main Gate"
[274] = true, -- "Stratholme - Service Entrance"
[32] = true, -- "Lower Blackrock Spire"
[330] = true, -- "Upper Blackrock Spire"
[860] = true, -- "Upper Blackrock Spire" (WoD)
}
S.Multiple = {
[36296] = "The Crown Chemical Co.", -- "Apothecary Hummel"
[36565] = "The Crown Chemical Co.", -- "Apothecary Baxter"
[36272] = "The Crown Chemical Co.", -- "Apothecary Frye"
[77557] = "Iron Assembly", -- "Admiral Gar'an"
[77231] = "Iron Assembly", -- "Enforcer Sorka"
[77477] = "Iron Assembly", -- "Marak the Blooded"
}
S.MultipleCache = {} -- second table for tracking npc deaths
local multipleHash = {} -- hash table
for k, v in pairs(S.Multiple) do
multipleHash[v] = multipleHash[v] or {}
multipleHash[v][k] = true
end
function S.CheckMultiple(v)
if S.Multiple[v] then
S.MultipleCache[v] = true
for k in pairs(multipleHash[S.Multiple[v]]) do
if not S.MultipleCache[k] then
return
end
end
end
return true
end
---------------------
--- Instance Time ---
---------------------
function KIT:StartData()
local serverTime = GetServerTime()
char.timeInstance = serverTime
char.startDate = date("%Y.%m.%d", serverTime)
char.startTime = date("%H:%M", serverTime)
-- reset so the broker timer can start counting again
S.LastInst = nil
end
function KIT:ResetTime(isLeave)
char.timeInstance = 0
char.startDate = ""
char.startTime = ""
if isLeave then
S.LastInst = nil
end
end
------------
--- Time ---
------------
function KIT:SecondsTime(v)
return SecondsToTime(v, profile.TimeOmitSec, not profile.TimeAbbrev, profile.TimeMaxCount)
end
do
-- not capitalized
local D_SECONDS = strlower(D_SECONDS)
local D_MINUTES = strlower(D_MINUTES)
local D_HOURS = strlower(D_HOURS)
local D_DAYS = strlower(D_DAYS)
-- exception for German capitalization
if GetLocale() == "deDE" then
D_SECONDS = _G.D_SECONDS
D_MINUTES = _G.D_MINUTES
D_HOURS = _G.D_HOURS
D_DAYS = _G.D_DAYS
end
function KIT:TimeString(v, full)
local sec = floor(v) % 60
local minute = floor(v/60) % 60
local hour = floor(v/3600) % 24
local day = floor(v/86400)
local fsec = format(D_SECONDS, sec)
local fmin = format(D_MINUTES, minute)
local fhour = format(D_HOURS, hour)
local fday = format(D_DAYS, day)
if v >= 86400 then
return (hour > 0 or full) and format("%s, %s", fday, fhour) or fday
elseif v >= 3600 then
return (minute > 0 or full) and format("%s, %s", fhour, fmin) or fhour
elseif v >= 60 then
return (sec > 0 or full) and format("%s, %s", fmin, fsec) or fmin
elseif v >= 0 then
return fsec
else
return v
end
end
end
do
local b = CreateFrame("Button")
function KIT:Time(v)
local s
if profile.LegacyTime then
s = self:TimeString(v, not profile.TimeOmitZero)
else
s = self:SecondsTime(v)
s = profile.TimeLowerCase and s:lower() or s
end
-- sanitize for SendChatMessage by removing any pipe characters
return b:GetText(b:SetText(s)) or ""
end
end
---------------------------
--- Time Format Example ---
---------------------------
do
local tday, thour, tmin, tsec = random(9), random(23), random(59), random(59)
S.TimeUnits = {
60*tmin,
60*tmin + tsec,
3600*thour + 60*tmin + tsec,
86400*tday + 3600*thour + 60*tmin + tsec,
}
S.TimeOmitZero = 3600*thour
end
-----------------
--- Stopwatch ---
-----------------
function S.StopwatchStart()
if S.pve[S.instance] then
if char.timeInstance > 0 then
StopwatchTicker.timer = GetServerTime() - char.timeInstance
else
Stopwatch_Clear()
end
elseif S.pvp[S.instance] then
StopwatchTicker.timer = GetBattlefieldInstanceRunTime()/1000
end
StopwatchFrame:Show()
Stopwatch_Play()
end
function S.StopwatchEnd()
Stopwatch_Clear()
StopwatchFrame:Hide()
end
function S.StopwatchPause()
-- recalibrate
StopwatchTicker.timer = GetServerTime() - char.timeInstance
StopwatchTicker_Update()
Stopwatch_Pause()
end
-- for when we're not sure whether the player is in an instance
function S.IsStopwatch()
return (profile.Stopwatch and S.instance ~= "none" and not S.IsGarrison())
end
-- garrison instance type == "party"
function S.IsGarrison()
local instanceID = select(8, GetInstanceInfo())
return S.garrison[instanceID]
end
--------------------
--- Class Colors ---
--------------------
S.classCache = setmetatable({}, {__index = function(t, k)
local color = (CUSTOM_CLASS_COLORS or RAID_CLASS_COLORS)[k]
local v = format("%02X%02X%02X", color.r*255, color.g*255, color.b*255)
rawset(t, k, v)
return v
end})
function KIT:WipeCache()
wipe(S.classCache)
end
------------
--- Rest ---
------------
function KIT:Zone()
return GetRealZoneText() or GetSubZoneText() or ZONE
end
function KIT:Finalize()
if profile.Stopwatch then
S.StopwatchPause()
end
if profile.Screenshot then
C_Timer.After(1, Screenshot)
end
-- pause LibDataBroker display
S.LastInst = (char.timeInstance > 0) and GetServerTime() - char.timeInstance
-- reset variables
self:ResetTime()
wipe(S.MultipleCache)
end
--------------
--- Record ---
--------------
-- Save Instance Timer data
function KIT:Record(zoneName)
-- tried recycling "party" and that was kinda dumb of me
local party = {}
-- don't record (party) members for raid instances
if not IsInRaid() and IsInGroup() then
for i = 1, GetNumSubgroupMembers() do
local name, realm = UnitName("party"..i)
local class = select(2, UnitClass("party"..i))
if not realm or realm == "" then
realm = GetRealmName() -- WoD empty string fix
end
party[i] = {name, realm, class}
end
end
tinsert(char.TimeInstanceList, {
date = char.startDate,
start = char.startTime,
["end"] = date("%H:%M", GetServerTime()),
zone = zoneName or self:Zone(),
instanceType = S.instance,
difficulty = select(3, GetInstanceInfo()),
time = GetServerTime() - char.timeInstance,
party = party,
})
end
---------------
--- Replace ---
---------------
local function ReplaceArgs(msg, args)
-- new random messages init as nil
if not msg then return "" end
for k in gmatch(msg, "%b<>") do
-- remove <>, make case insensitive
local s = strlower(gsub(k, "[<>]", ""))
-- escape special characters
s = gsub(args[s] or s, "(%p)", "%%%1")
k = gsub(k, "(%p)", "%%%1")
msg = msg:gsub(k, s)
end
wipe(args)
return msg
end
--------------
--- Report ---
--------------
local exampleTime = random(3600)
function KIT:InstanceText(isPreview, name)
wipe(args)
local serverTime = GetServerTime()
if isPreview then
args.instance = "|cffA8A8FF"..self:Zone().."|r"
args.time = "|cff71D5FF"..self:Time(char.timeInstance > 0 and serverTime - char.timeInstance or exampleTime).."|r"
args.start = "|cffF6ADC6"..(char.timeInstance > 0 and char.startTime or date("%H:%M", serverTime)).."|r" -- note startTime can be an empty string
args["end"] = "|cffADFF2F"..date("%H:%M", serverTime + exampleTime).."|r" -- can't use keywords as a table key o_O
args.date = "|cff0070DD"..date("%Y.%m.%d", serverTime).."|r"
args.date2 = "|cff0070DD"..date("%m/%d/%y", serverTime).."|r"
args.difficulty = "|cffFFFF00"..(select(4, GetInstanceInfo()) or UNKNOWN).."|r"
else
args.instance = name or self:Zone()
args.time = self:Time(char.timeInstance > 0 and serverTime - char.timeInstance or 0)
args.start = char.startTime
args["end"] = date("%H:%M", serverTime)
args.date = date("%Y.%m.%d",serverTime)
args.date2 = date("%m/%d/%y", serverTime)
args.difficulty = select(4, GetInstanceInfo()) or UNKNOWN
end
return ReplaceArgs(profile.InstanceTimerMsg, args)
end
|
project ("App_RobotSimulator")
language "C++"
kind "ConsoleApp"
includedirs {"../../src", "../../examples",
"../../examples/ThirdPartyLibs"}
defines {"B3_USE_ROBOTSIM_GUI", "PHYSICS_IN_PROCESS_EXAMPLE_BROWSER"}
if _OPTIONS["enable_grpc"] then
initGRPC()
files {
"../../examples/SharedMemory/PhysicsClientGRPC.cpp",
"../../examples/SharedMemory/PhysicsClientGRPC.h",
"../../examples/SharedMemory/PhysicsClientGRPC_C_API.cpp",
"../../examples/SharedMemory/PhysicsClientGRPC_C_API.h",
}
end
links{"BulletRobotics", "BulletExampleBrowserLib", "gwen", "OpenGL_Window","BulletFileLoader","BulletWorldImporter","BulletSoftBody", "BulletInverseDynamicsUtils", "BulletInverseDynamics", "BulletDynamics","BulletCollision","LinearMath","Bullet3Common"}
initOpenGL()
initGlew()
includedirs {
".",
"../../src",
"../../examples/SharedMemory",
"../ThirdPartyLibs",
}
if os.is("MacOSX") then
links{"Cocoa.framework"}
end
if not _OPTIONS["no-enet"] then
includedirs {"../../examples/ThirdPartyLibs/enet/include"}
if os.is("Windows") then
-- targetextension {"dylib"}
defines { "WIN32" }
links {"Ws2_32","Winmm"}
end
if os.is("Linux") then
end
if os.is("MacOSX") then
end
links {"enet"}
files {
"../../examples/SharedMemory/PhysicsClientUDP.cpp",
"../../examples/SharedMemory/PhysicsClientUDP.h",
"../../examples/SharedMemory/PhysicsClientUDP_C_API.cpp",
"../../examples/SharedMemory/PhysicsClientUDP_C_API.h",
}
defines {"BT_ENABLE_ENET"}
end
if not _OPTIONS["no-clsocket"] then
includedirs {"../../examples/ThirdPartyLibs/clsocket/src"}
if os.is("Windows") then
defines { "WIN32" }
links {"Ws2_32","Winmm"}
end
if os.is("Linux") then
defines {"_LINUX"}
end
if os.is("MacOSX") then
defines {"_DARWIN"}
end
links {"clsocket"}
files {
"../../examples/SharedMemory/PhysicsClientTCP.cpp",
"../../examples/SharedMemory/PhysicsClientTCP.h",
"../../examples/SharedMemory/PhysicsClientTCP_C_API.cpp",
"../../examples/SharedMemory/PhysicsClientTCP_C_API.h",
}
defines {"BT_ENABLE_CLSOCKET"}
end
if _OPTIONS["audio"] then
files {
"../TinyAudio/b3ADSR.cpp",
"../TinyAudio/b3AudioListener.cpp",
"../TinyAudio/b3ReadWavFile.cpp",
"../TinyAudio/b3SoundEngine.cpp",
"../TinyAudio/b3SoundSource.cpp",
"../TinyAudio/b3WriteWavFile.cpp",
"../TinyAudio/RtAudio.cpp",
}
defines {"B3_ENABLE_TINY_AUDIO"}
if _OPTIONS["serial"] then
defines{"B3_ENABLE_SERIAL"}
includedirs {"../../examples/ThirdPartyLibs/serial/include"}
links {"serial"}
end
if os.is("Windows") then
links {"winmm","Wsock32","dsound"}
defines {"WIN32","__WINDOWS_MM__","__WINDOWS_DS__"}
end
if os.is("Linux") then initX11()
defines {"__OS_LINUX__","__LINUX_ALSA__"}
links {"asound","pthread"}
end
if os.is("MacOSX") then
links{"Cocoa.framework"}
links{"CoreAudio.framework", "coreMIDI.framework", "Cocoa.framework"}
defines {"__OS_MACOSX__","__MACOSX_CORE__"}
end
end
files {
"RobotSimulatorMain.cpp",
"b3RobotSimulatorClientAPI.cpp",
"b3RobotSimulatorClientAPI.h",
"MinitaurSetup.cpp",
"MinitaurSetup.h",
"../../examples/ExampleBrowser/InProcessExampleBrowser.cpp",
"../../examples/SharedMemory/PhysicsServerExample.cpp",
"../../examples/SharedMemory/PhysicsServerExampleBullet2.cpp",
"../../examples/SharedMemory/SharedMemoryInProcessPhysicsC_API.cpp",
}
if (_OPTIONS["enable_static_vr_plugin"]) then
files {"../../examples/SharedMemory/plugins/vrSyncPlugin/vrSyncPlugin.cpp"}
end
if os.is("Linux") then
initX11()
end
if _OPTIONS["serial"] then
project ("App_VRGloveHandSimulator")
language "C++"
kind "ConsoleApp"
includedirs {"../../src", "../../examples",
"../../examples/ThirdPartyLibs"}
defines {"PHYSICS_IN_PROCESS_EXAMPLE_BROWSER"}
hasCL = findOpenCL("clew")
links{"BulletRobotics", "BulletExampleBrowserLib","gwen", "OpenGL_Window","BulletFileLoader","BulletWorldImporter","BulletSoftBody", "BulletInverseDynamicsUtils", "BulletInverseDynamics", "BulletDynamics","BulletCollision","LinearMath","BussIK","Bullet3Common"}
initOpenGL()
initGlew()
includedirs {
".",
"../../src",
"../ThirdPartyLibs",
}
if os.is("MacOSX") then
links{"Cocoa.framework"}
end
if (hasCL) then
links {
"Bullet3OpenCL_clew",
"Bullet3Dynamics",
"Bullet3Collision",
"Bullet3Geometry",
"Bullet3Common",
}
end
if _OPTIONS["audio"] then
files {
"../TinyAudio/b3ADSR.cpp",
"../TinyAudio/b3AudioListener.cpp",
"../TinyAudio/b3ReadWavFile.cpp",
"../TinyAudio/b3SoundEngine.cpp",
"../TinyAudio/b3SoundSource.cpp",
"../TinyAudio/b3WriteWavFile.cpp",
"../TinyAudio/RtAudio.cpp",
}
defines {"B3_ENABLE_TINY_AUDIO"}
defines{"B3_ENABLE_SERIAL"}
includedirs {"../../examples/ThirdPartyLibs/serial/include"}
links {"serial"}
if os.is("Windows") then
links {"winmm","Wsock32","dsound"}
defines {"WIN32","__WINDOWS_MM__","__WINDOWS_DS__"}
end
if os.is("Linux") then initX11()
defines {"__OS_LINUX__","__LINUX_ALSA__"}
links {"asound","pthread"}
end
if os.is("MacOSX") then
links{"Cocoa.framework"}
links{"CoreAudio.framework", "coreMIDI.framework", "Cocoa.framework"}
defines {"__OS_MACOSX__","__MACOSX_CORE__"}
end
end
files {
"VRGloveSimulatorMain.cpp",
"b3RobotSimulatorClientAPI.cpp",
"b3RobotSimulatorClientAPI.h",
}
if (_OPTIONS["enable_static_vr_plugin"]) then
files {"../../examples/SharedMemory/plugins/vrSyncPlugin/vrSyncPlugin.cpp"}
end
if os.is("Linux") then
initX11()
end
end
project ("App_HelloBulletRobotics")
language "C++"
kind "ConsoleApp"
links{"BulletRobotics","BulletFileLoader","BulletWorldImporter","BulletSoftBody", "BulletInverseDynamicsUtils", "BulletInverseDynamics", "BulletDynamics","BulletCollision","LinearMath","Bullet3Common"}
includedirs {
".",
"../../src",
"../../examples/SharedMemory",
"../ThirdPartyLibs",
}
if not _OPTIONS["no-enet"] then
includedirs {"../../examples/ThirdPartyLibs/enet/include"}
if os.is("Windows") then
defines { "WIN32" }
links {"Ws2_32","Winmm"}
end
if os.is("Linux") then
end
if os.is("MacOSX") then
end
links {"enet"}
defines {"BT_ENABLE_ENET"}
end
if not _OPTIONS["no-clsocket"] then
includedirs {"../../examples/ThirdPartyLibs/clsocket/src"}
if os.is("Windows") then
defines { "WIN32" }
links {"Ws2_32","Winmm"}
end
if os.is("Linux") then
defines {"_LINUX"}
end
if os.is("MacOSX") then
defines {"_DARWIN"}
end
links {"clsocket"}
defines {"BT_ENABLE_CLSOCKET"}
end
if os.is("MacOSX") then
links{"Cocoa.framework"}
end
if os.is("Linux") then initX11()
links {"pthread"}
end
files {
"HelloBulletRobotics.cpp"
}
|
print("Hello Lua")
|
local PLUGIN = PLUGIN
local PANEL = {}
AccessorFunc(PANEL, "money", "Money", FORCE_NUMBER)
function PANEL:Init()
self:DockPadding(1, 1, 1, 1)
self:SetTall(24)
self:Dock(BOTTOM)
self.moneyBtn = self:Add("DButton")
self.moneyBtn:Dock(FILL)
self.moneyBtn:SetFont("ixGenericFont")
self.moneyBtn:SetText("")
self.moneyBtn:SetIcon("icon16/money_dollar.png")
self.moneyBtn:SetTextInset(2, 0)
self.moneyBtn:SizeToContents()
self.moneyBtn.Paint = function(t, w, h)
derma.SkinFunc("PaintButtonFilled", t, w, h)
end
self.moneyBtn.OnMousePressed = function(t, code)
if (code == MOUSE_LEFT) then
surface.PlaySound("ui/buttonclick.wav")
Derma_NumericRequest("", L"stash_enter_money", self.money, function(text)
local amount = math.max(0, math.Round(tonumber(text) or 0))
if (amount != 0) then
self:OnTransfer(amount)
end
end)
elseif (code == MOUSE_RIGHT) then
surface.PlaySound("ui/buttonclick.wav")
self:OnTransfer(0, MOUSE_RIGHT)
end
end
self.bNoBackgroundBlur = true
end
function PANEL:SetMoney(money)
self.money = math.max(math.Round(tonumber(money) or 0), 0)
self.moneyBtn:SetText(ix.currency.Get(money))
end
function PANEL:OnTransfer(amount, code)
end
function PANEL:Paint(width, height)
derma.SkinFunc("PaintBaseFrame", self, width, height)
end
vgui.Register("ixStashMoney", PANEL, "EditablePanel")
local PANEL = {}
PANEL.itemSize = 92
function PANEL:Init()
self:SetSize(self.itemSize, self.itemSize * 1.4)
self.stack = 1
self.stack_keys = {}
end
function PANEL:IncStack(key)
self.stack = self.stack + 1
self.stack_keys[key] = true
end
function PANEL:DecStack(key)
self.stack = math.max(0, self.stack - 1)
self.stack_keys[key] = nil
if (IsValid(ix.gui.stash)) then
if (self.stack <= 0) then
self:Remove()
return true
else
ix.gui.stash:GetStackKey(self.idxPanel, self.stack_keys)
end
end
return false
end
function PANEL:SetItem(itemTable)
self.itemTable = itemTable
self.key = 0
self.isStackable = itemTable.isStackable
self.name = self:Add("DLabel")
self.name:Dock(TOP)
self.name:SetText(itemTable.GetName and itemTable:GetName() or L(itemTable.name))
self.name:SetContentAlignment(5)
self.name:SetTextColor(color_white)
self.name:SetFont("ixSmallFont")
self.name:SetExpensiveShadow(1, ColorAlpha(color_black, 200))
self.name.Paint = function(this, w, h)
surface.SetDrawColor(0, 0, 0, 75)
surface.DrawRect(0, 0, w, h)
end
self.icon = self:Add("SpawnIcon")
--self.icon:Droppable("ixStashItem")
self.icon:SetZPos(1)
self.icon:SetSize(self:GetWide(), self:GetWide())
self.icon:Dock(FILL)
self.icon:DockMargin(5, 5, 5, 10)
self.icon:InvalidateLayout(true)
self.icon:SetModel(itemTable:GetModel(), itemTable:GetSkin())
self.icon:SetHelixTooltip(function(tooltip)
ix.hud.PopulateItemTooltip(tooltip, self.itemTable)
end)
self.icon.DoClick = function(this)
if ((LocalPlayer().next_stash_click or 0) < CurTime()) then
LocalPlayer().next_stash_click = CurTime() + 1.25
else
return
end
local invPanel = ix.gui.inv1
if (!IsValid(invPanel)) then return end
local allStack = input.IsShiftDown()
local inventory = LocalPlayer():GetCharacter():GetInventory()
local w, h = self.itemTable.width, self.itemTable.height
local stackItem = inventory:CanItemFitStack(self.itemTable, true)
local x2, y2
for x = 1, inventory.w do
if (x2 and y2) then break end
for y = 1, inventory.h do
if (stackItem) then
local slot = (inventory.slots[x] or {})[y]
if (slot and slot.isStackable and slot.uniqueID == stackItem.uniqueID and slot:GetData("quantity", slot.maxQuantity or 16) < (slot.maxQuantity or 16)) then
x2 = x2 or x
y2 = y2 or y
break
end
else
if (invPanel:IsAllEmpty(x, y, w, h)) then
x2 = x2 or x
y2 = y2 or y
break
end
end
end
end
if !(x2 and y2) then
LocalPlayer():NotifyLocalized("noFit")
return
end
net.Start("ixStashWithdrawItem")
net.WriteUInt(self.key, 32)
net.WriteBool(allStack)
net.SendToServer()
if (IsValid(ix.gui.stash)) then
local quantity = 1
if (allStack and self.isStackable) then
quantity = self.itemTable:GetData("quantity", 1)
local diff = quantity - (self.itemTable.maxQuantity or 16)
if (diff > 0) then
quantity = quantity - diff
end
end
ix.gui.stash:TakeItem(self.key, self.itemTable, quantity)
end
end
self.icon.PaintOver = function(t, w, h)
if (self.stack > 1 and !self.isStackable) then
draw.SimpleTextOutlined("x" .. self.stack, "GmodZ.Numeric", w, h - 10, color_white, TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER, 1, color_black)
end
if (itemTable and itemTable.PaintOver) then
itemTable.PaintOver(t, itemTable, w, h)
end
end
if ((itemTable.iconCam and !ICON_RENDER_QUEUE[itemTable.uniqueID]) or itemTable.forceRender) then
local iconCam = itemTable.iconCam
iconCam = {
cam_pos = iconCam.pos,
cam_fov = iconCam.fov,
cam_ang = iconCam.ang,
}
ICON_RENDER_QUEUE[itemTable.uniqueID] = true
self.icon:RebuildSpawnIconEx(
iconCam
)
end
end
function PANEL:Paint(w, h)
derma.SkinFunc("PaintMerchantSlot", self, w, h)
end
vgui.Register("ixStashItem", PANEL, "DPanel")
DEFINE_BASECLASS("Panel")
PANEL = {}
PANEL.cCategoryRect = Color(38, 38, 38, 255)
PANEL.cCategoryBorder = Color(204, 204, 204, 100)
AccessorFunc(PANEL, "fadeTime", "FadeTime", FORCE_NUMBER)
AccessorFunc(PANEL, "frameMargin", "FrameMargin", FORCE_NUMBER)
function PANEL:Init()
if (IsValid(ix.gui.stash)) then
ix.gui.stash:Remove()
end
ix.gui.stash = self
self.character = LocalPlayer():GetCharacter()
self:SetSize(ScrW(), ScrH())
self:SetPos(0, 0)
self:SetFadeTime(0.25)
self:SetFrameMargin(4)
-- Player inventory
ix.gui.inv1 = self:Add("ixInventory")
ix.gui.inv1.bNoBackgroundBlur = true
ix.gui.inv1:ShowCloseButton(true)
ix.gui.inv1.Close = function(t)
self:Remove()
end
-- TODO: Позже прикрутить и PaintDragPreview
--[[ ix.gui.inv1:Receiver("ixStashItem", function(this, panels, dropped)
if (dropped and panels[1]) then
local hoveredPanel = vgui.GetHoveredPanel()
local itemPanel = panels[1]:GetParent()
if (IsValid(hoveredPanel) and hoveredPanel != itemPanel) then
net.Start("ixStashWithdrawItem")
net.WriteUInt(itemPanel.key, 32)
net.SendToServer()
ix.gui.stash:TakeItem(itemPanel.key, itemPanel.itemTable)
end
end
end) ]]
-- Inventory label -> money
self.invMoney = ix.gui.inv1:Add("ixStashMoney")
self.invMoney.OnTransfer = function(_, amount, keyCode)
if (self.character:GetMoney() <= 0) then
return
end
if (keyCode == MOUSE_RIGHT) then
amount = self.character:GetMoney()
end
net.Start("ixStashDepositMoney")
net.WriteUInt(amount, 32)
net.SendToServer()
end
self.invMoney:SetVisible(false)
-- Stash
self.invStash = self:Add("DFrame")
self.invStash:SetTitle(L'stash_title')
self.invStash:SetSize(ScrW() / 3, ScrH() / 1.25)
self.invStash:ShowCloseButton(true)
self.invStash:SetDraggable(true)
self.invStash:SetSizable(false)
self.invStash.bNoBackgroundBlur = true
self.invStash.Paint = function(t, w, h)
derma.SkinFunc("PaintFrame2", t, w, h)
end
self.invStash.Close = function(t)
self:Remove()
end
self.invStash.lblTitle.UpdateColours = function(label)
return label:SetTextStyleColor(color_white)
end
self.invStashMoney = self.invStash:Add("ixStashMoney")
self.invStashMoney.OnTransfer = function(_, amount, keyCode)
if (self.character:GetStashMoney() <= 0) then
return
end
if (keyCode == MOUSE_RIGHT) then
amount = self.character:GetStashMoney()
end
net.Start("ixStashWithdrawMoney")
net.WriteUInt(amount, 32)
net.SendToServer()
end
self.invStashMoney:SetVisible(false)
self.categories = self.invStash:Add("DScrollPanel")
self.categories:Dock(FILL)
self.categories:DockMargin(0, 2, 4, 0)
self.categories:SetPaintBackground(true)
self.categories:Receiver("ixInventoryItem", function(this, panels, dropped)
if (dropped and panels[1]) then
PLUGIN:DepositItem(self.character, panels[1], panels[1].itemTable)
end
end)
self.categoryPanels = {}
self.items = {}
self:SetAlpha(0)
self:AlphaTo(255, self:GetFadeTime())
self.invStash:MakePopup()
ix.gui.inv1:MakePopup()
end
function PANEL:SetLocalInventory(inventory, money)
if (IsValid(ix.gui.inv1) and !IsValid(ix.gui.menu)) then
ix.gui.inv1:SetInventory(inventory)
ix.gui.inv1:SetPos(self:GetWide() / 2 - ix.gui.inv1:GetWide() - 2, self:GetTall() / 2 - ix.gui.inv1:GetTall() / 2)
end
if (!self.invMoney:IsVisible()) then
self.invMoney:SetVisible(true)
ix.gui.inv1:SetTall(ix.gui.inv1:GetTall() + self.invMoney:GetTall() + 2)
end
self.invMoney:SetMoney(money)
end
function PANEL:TakeItem(key, item, amt)
local panel
if (!item.isStackable) then
local idxPanel = self:CanStackItem(item, key)
panel = self.items[idxPanel]
self.entityItems[key] = nil
PLUGIN.virtual_items[key] = nil
if (IsValid(panel) and panel:DecStack(key)) then
self.items[idxPanel] = nil
panel = nil
end
else
panel = self.items[key]
if (IsValid(panel)) then
panel.stack = math.max(0, panel.stack - (amt or 1))
PLUGIN.virtual_items[key]:SetData("quantity", panel.stack)
if (panel.stack <= 0) then
self.entityItems[key] = nil
PLUGIN.virtual_items[key] = nil
self.items[key] = nil
panel:Remove()
panel = nil
end
end
end
end
function PANEL:GetStackKey(idxPanel, stack_keys)
if (idxPanel and IsValid(self.items[idxPanel])) then
self.items[idxPanel].key = select(2, table.Random(stack_keys))
end
end
function PANEL:CanStackItem(item, default)
local index = default or item.id
if (!item.isStackable) then
for idx, panel in pairs(self.items) do
if (!IsValid(panel) or panel.itemTable.uniqueID != item.uniqueID) then continue end
if (item.CanStack and item:CanStack(panel.itemTable, true) and (item.price or 0) == (panel.itemTable.price or 0)
or table.IsEmpty(item.data) and table.IsEmpty(panel.itemTable.data)) then
index = idx
break
end
end
end
return index
end
function PANEL:AddItem(key, itemTable)
local item = PLUGIN:MakeVirtualItem(itemTable.uniqueID, key)
item.data = itemTable.data or {}
self:AddCategory(item)
local index = self:CanStackItem(item)
if (!IsValid(self.items[index])) then
local itemSlot = self.categoryPanels[item.category][1]:Add("ixStashItem")
itemSlot:SetItem(item)
itemSlot.key = key
itemSlot.idxPanel = index
if (item.isStackable) then
itemSlot.stack = item.data.quantity
PLUGIN.virtual_items[key]:SetData("quantity", item.data.quantity)
end
self.items[index] = itemSlot
else
if (item.isStackable) then
self.items[index].stack = item.data.quantity
PLUGIN.virtual_items[key]:SetData("quantity", item.data.quantity)
else
self.items[index]:IncStack(key)
end
end
end
function PANEL:AddCategory(item)
if (item and !self.categoryPanels[item.category]) then
local cat = vgui.Create('DCollapsibleCategory', self.categories)
cat.Paint = function() end
cat.Header:SetFont("ixSmallFont")
cat.Header:SetContentAlignment(5)
cat.Header.Paint = function(t, w, h)
derma.SkinFunc("PaintButton2", t, w, h, t:IsHovered() and ix.config.Get("color"))
end
cat:SetLabel(L(item.category))
cat:Dock(TOP)
cat.Think = function(t)
if (#t.Contents:GetChildren() < 1) then
t:Remove()
self.categoryPanels[item.category] = nil
end
end
local slot = vgui.Create('DIconLayout', cat)
slot:SetSpaceX(5)
slot:SetSpaceY(5)
slot:SetBorder(5)
slot:Dock(TOP)
slot:InvalidateLayout(true)
cat:SetContents(slot)
self.categoryPanels[item.category] = {slot, cat}
end
end
function PANEL:SetStash(items)
self.invStash:SetPos(self:GetWide() / 2 + self:GetFrameMargin() / 2, self:GetTall() / 2 - self.invStash:GetTall() / 2)
if (!table.IsEmpty(self.categoryPanels)) then
for _, panels in pairs(self.categoryPanels) do
panels[2]:Clear()
panels[2]:InvalidateLayout(true)
end
end
self.entityItems = items
-- init items
for k, data in SortedPairs(items) do
if (k == 0) then continue end
self:AddItem(k, data)
end
if (!self.invStashMoney:IsVisible()) then
self.invStashMoney:SetVisible(true)
self.invStash:SetTall(self.invStash:GetTall() + self.invStashMoney:GetTall() + 2)
end
self.loaded = true
end
function PANEL:Paint(width, height)
ix.util.DrawBlurAt(0, 0, width, height)
for _, v in ipairs(self:GetChildren()) do
v:PaintManual()
end
end
function PANEL:Remove()
self:SetAlpha(255)
self:AlphaTo(0, self:GetFadeTime(), 0, function()
table.Empty(PLUGIN.virtual_items)
for _, v in ipairs(ents.FindInSphere(EyePos(), 256)) do
if (v and v:GetClass() == "gmodz_stash") then
v:EmitSound("items/ammocrate_close.wav")
break
end
end
BaseClass.Remove(self)
end)
end
function PANEL:Think()
if (self.loaded) then
if ((self.nextThink or 0) < CurTime()) then
if (self.character) then
if (self.invMoney.money != self.character:GetMoney()) then
self.invMoney:SetMoney(self.character:GetMoney())
end
if (self.invStashMoney.money != self.character:GetStashMoney()) then
self.invStashMoney:SetMoney(self.character:GetStashMoney())
end
-- Resync
local weight = self.character:GetStashWeight()
if (table.IsEmpty(self.categoryPanels) and weight > 0) then
self:SetStash(self.character:GetStash())
end
self.invStash:SetTitle(L("stash_title_count", weight, self.character:GetStashWeightMax()))
end
self.nextThink = CurTime() + 0.25
end
end
end
vgui.Register("ixStashView", PANEL, "Panel")
|
local default_msg_data = {
sender = nil,
listeners = {},
data = {},
position = nil,
radius = 0,
filter = nil,
rich = false,
size = Config.get('default_font_size', 20),
text = nil,
team_chat = false
}
local filters = {}
local client_mode = false
function Chatbox.add_filter(id, data)
filters[id] = data
end
function Chatbox.can_hear(listener, message_data)
if Plugin.call('PlayerCanHear', listener, message_data) then
return true
end
if IsValid(listener) and listener:has_initialized() then
local position, radius = message_data.position, message_data.radius
if !isnumber(radius) then return false end
if radius == 0 then return true end
if radius < 0 then return false end
if istable(position) then
for k, v in pairs(position) do
if isvector(v) and v:Distance(listener:EyePos()) <= radius then
return true
end
end
end
if isvector(position) and position:Distance(listener:EyePos()) <= radius then
return true
end
end
return false
end
function Chatbox.add_text(listeners, ...)
local message_data = {
sender = nil,
listeners = listeners or {},
data = {},
position = nil,
radius = 0,
filter = nil,
rich = false,
size = Config.get('default_font_size', 20),
text = nil,
team_chat = false
}
if !istable(listeners) then
if IsValid(listeners) then
listeners = { listeners }
else
listeners = _player.GetAll()
end
end
local last_string = false
-- Compile the initial message data table.
for k, v in ipairs({ ... }) do
if isstring(v) then
if !last_string then
table.insert(message_data.data, v)
else
local str = table.last(message_data.data)
message_data.data[#message_data.data] = str..v
end
if k == 1 then
message_data.text = v
end
last_string = true
else
last_string = false
if isnumber(v) then
table.insert(message_data.data, v)
elseif IsColor(v) then
table.insert(message_data.data, v)
elseif istable(v) then
if !v.is_data and !client_mode then
table.merge(message_data, v)
else
table.insert(message_data.data, v)
end
elseif IsValid(v) then
table.insert(message_data.data, v)
end
end
end
for k, v in ipairs(listeners) do
local data = message_data
hook.run('AdjustMessageData', v, data)
if Chatbox.can_hear(v, data) then
Cable.send(v, 'fl_chat_message_add', data)
end
end
end
function Chatbox.set_client_mode(val)
client_mode = val
end
function Chatbox.message_to_string(message_data, concatenator)
local to_string = {}
for k, v in pairs(message_data) do
if isnumber(v) then continue end
if isstring(v) then
table.insert(to_string, v)
elseif IsValid(v) then
local name = ''
if v:IsPlayer() then
name = hook.run('GetPlayerName', v) or v:name()
else
name = tostring(v) or v:GetClass()
end
table.insert(to_string, name)
end
end
return table.concat(to_string, concatenator)
end
function Chatbox.player_say(player, text, team_chat)
if !IsValid(player) then return end
local player_say_override = hook.run('PlayerSay', player, text, team_chat)
if isstring(player_say_override) then
if player_say_override == '' then return end
text = player_say_override
end
text = text:trim()
local message = {
hook.run('ChatboxGetPlayerIcon', player, text, team_chat) or {},
hook.run('ChatboxGetPlayerColor', player, text, team_chat) or _team.GetColor(player:Team()),
player,
hook.run('ChatboxGetMessageColor', player, text, team_chat) or Color(255, 255, 255),
': ',
text,
{ sender = player }
}
hook.run('ChatboxAdjustPlayerSay', player, text, message)
Chatbox.add_text(nil, unpack(message))
end
Cable.receive('fl_chat_text_add', function(player, ...)
if !IsValid(player) then return end
Chatbox.set_client_mode(true)
Chatbox.add_text(player, ...)
Chatbox.set_client_mode(false)
end)
Cable.receive('fl_chat_player_say', function(player, text, team_chat)
Chatbox.player_say(player, text, team_chat)
end)
|
--sox 08.ogg -t u8 -c 1 -b 8 -r 8k 08.u8
--sox gun.wav -t wav -c 1 -b 8 -r 8k gun1.wav
--@see https://docs.yate.ro/wiki/ConvertingAudio
local songs = {
{
name = "White noise audio",
desc = "30 seconds of white noise",
path = "songs/noise_8k.u8"
},
{
name = "Empty audio",
desc = "30 seconds of nothing",
path = "songs/empty_8k.u8"
},
{
name = "Bensound sunny",
desc = "Gentle acoustic royalty free music featuring guitar, marimba...",
path = "songs/bensound-sunny_8k.u8"
},
{
name = "Bensound allthat",
desc = "Chill-Hop royalty free music track featuring jazz samples, a hip ...",
path = "songs/bensound-allthat_8k.u8"
}
}
return songs
|
require("examples/benchmark")
|
--[[
阵形基类
]]
-- 显示延时
local C_SHOW_DELAY = 0.8
-- 显示配置
local C_SHOW_CONFIG = {
usecursor = false,
usesound = false,
quickshow = true,
linefeed = true,
ctrl_quick = false,
ctrl_complete = false,
}
local _FormationBase = class("_FormationBase", require("app.main.modules.script.ScriptBase"))
-- 战场动作
function _FormationBase:doActionInBattle(onComplete,isgatking,doAction)
local function _beforeAction(onComplete_)
if isgatking then
onComplete_()
else
self.role:selectForward(true,onComplete_)
end
end
local function _doAction(onComplete_)
if not doAction then
onComplete_()
else
doAction(onComplete_,isgatking)
end
end
local function _afterAction(onComplete_)
if isgatking then
onComplete_()
else
self.role:selectForward(false,onComplete_)
end
end
if self.role:isDead() then
if onComplete then onComplete() end
else
_beforeAction(function ()
_doAction(function ()
_afterAction(function ()
if onComplete then onComplete() end
end)
end)
end)
end
end
-- 战场上设置
function _FormationBase:setInBattle(onComplete,fnSet)
self:doActionInBattle(onComplete,self.role:getScene():isGeneralAttack(),
function (onComplete_,isgatking)
local msgui = self.role:isEnemy() and "message" or "ourmessage"
local extvars = {
formation = formationMgr:getName(self.formation),
role = self.role:getEntity():getName()
}
if #self.role:getTeam():getAliveRoles() < formationMgr:getSetRoles(self.formation) then
if isgatking then
if onComplete_ then onComplete_(false) end
else
local msgwin = uiMgr:openUI(msgui)
msgwin:showMessage({
texts = gameMgr:getStrings("NOTSET_FORMATION", extvars),
showconfig = C_SHOW_CONFIG,
onComplete = function ()
performWithDelay(msgwin,function ()
uiMgr:closeUI(msgui)
if onComplete_ then onComplete_(false) end
end, C_SHOW_DELAY)
end
})
end
else
if self.role:getEntity():getTeam():tryConsumeSP(self.sp) then
fnSet(onComplete_,isgatking,msgui,extvars,C_SHOW_CONFIG)
else
if isgatking then
if onComplete_ then onComplete_(false) end
else
local msgwin = uiMgr:openUI(msgui)
local msg = self.role:getEntity():getTeam():getAdviser() and "LACK_SP" or "NO_ADVISER"
msgwin:showMessage({
texts = gameMgr:getStrings(msg),
showconfig = C_SHOW_CONFIG,
onComplete = function ()
performWithDelay(msgwin,function ()
uiMgr:closeUI(msgui)
if onComplete_ then onComplete_(false) end
end,C_SHOW_DELAY)
end
})
end
end
end
end)
end
-- 地图上设置
function _FormationBase:setInMap(onComplete,fnSet)
local extvars = {
formation = formationMgr:getName(self.formation),
role = self.role:getName()
}
if table.nums(self.role:getTeam():getRoles(),function (v) return not v:isDead() end) <
formationMgr:getSetRoles(self.formation) then
uiMgr:openUI("message",{
texts = gameMgr:getStrings("NOTSET_FORMATION",extvars),
onComplete = function ()
if onComplete then onComplete(false) end
end
})
else
local fsp = formationMgr:getSP(self.formation)
if self.role:getTeam():tryConsumeSP(fsp) then
fnSet(onComplete,extvars)
else
uiMgr:openUI("message",{
texts = gameMgr:getStrings("LACK_SP"),
onComplete = function ()
if onComplete then onComplete(false) end
end
})
end
end
end
return _FormationBase
|
local small_explosion_LUQ = table.deepcopy(data.raw.explosion["uranium-explosion-LUQ"])
small_explosion_LUQ.name = "small-uranium-explosion-LUQ"
small_explosion_LUQ.animations[1].scale = small_explosion_LUQ.animations[1].scale/2
small_explosion_LUQ.animations[1].shift = {-8,-8}
local small_explosion_RUQ = table.deepcopy(data.raw.explosion["uranium-explosion-RUQ"])
small_explosion_RUQ.name = "small-uranium-explosion-RUQ"
small_explosion_RUQ.animations[1].scale = small_explosion_RUQ.animations[1].scale/2
small_explosion_RUQ.animations[1].shift = {8,-8}
local small_explosion_LLQ = table.deepcopy(data.raw.explosion["uranium-explosion-LLQ"])
small_explosion_LLQ.name = "small-uranium-explosion-LLQ"
small_explosion_LLQ.animations[1].scale = small_explosion_LLQ.animations[1].scale/2
small_explosion_LLQ.animations[1].shift = {-8,8}
local small_explosion_RLQ = table.deepcopy(data.raw.explosion["uranium-explosion-RLQ"])
small_explosion_RLQ.name = "small-uranium-explosion-RLQ"
small_explosion_RLQ.animations[1].scale = small_explosion_RLQ.animations[1].scale/2
small_explosion_RLQ.animations[1].shift = {8,8}
data:extend({small_explosion_LUQ,small_explosion_RUQ,small_explosion_LLQ,small_explosion_RLQ})
--allow definition of high-res versions.
if (data.raw.explosion["big-uranium-explosion-LUQ"] ==nil) then
local big_explosion_LUQ = table.deepcopy(data.raw.explosion["uranium-explosion-LUQ"])
big_explosion_LUQ.name = "big-uranium-explosion-LUQ"
big_explosion_LUQ.animations[1].scale = big_explosion_LUQ.animations[1].scale*2
big_explosion_LUQ.animations[1].shift = {-32,-32}
local big_explosion_RUQ = table.deepcopy(data.raw.explosion["uranium-explosion-RUQ"])
big_explosion_RUQ.name = "big-uranium-explosion-RUQ"
big_explosion_RUQ.animations[1].scale = big_explosion_RUQ.animations[1].scale*2
big_explosion_RUQ.animations[1].shift = {32,-32}
local big_explosion_LLQ = table.deepcopy(data.raw.explosion["uranium-explosion-LLQ"])
big_explosion_LLQ.name = "big-uranium-explosion-LLQ"
big_explosion_LLQ.animations[1].scale = big_explosion_LLQ.animations[1].scale*2
big_explosion_LLQ.animations[1].shift = {-32,32}
local big_explosion_RLQ = table.deepcopy(data.raw.explosion["uranium-explosion-RLQ"])
big_explosion_RLQ.name = "big-uranium-explosion-RLQ"
big_explosion_RLQ.animations[1].scale = big_explosion_RLQ.animations[1].scale*2
big_explosion_RLQ.animations[1].shift = {32,32}
data:extend({big_explosion_LUQ,big_explosion_RUQ,big_explosion_LLQ,big_explosion_RLQ})
end
local huge_explosion_LUQ = table.deepcopy(data.raw.explosion["big-uranium-explosion-LUQ"])
huge_explosion_LUQ.name = "huge-uranium-explosion-LUQ"
huge_explosion_LUQ.animations[1].scale = huge_explosion_LUQ.animations[1].scale*2
huge_explosion_LUQ.animations[1].shift = {-64,-64}
local huge_explosion_RUQ = table.deepcopy(data.raw.explosion["big-uranium-explosion-RUQ"])
huge_explosion_RUQ.name = "huge-uranium-explosion-RUQ"
huge_explosion_RUQ.animations[1].scale = huge_explosion_RUQ.animations[1].scale*2
huge_explosion_RUQ.animations[1].shift = {64,-64}
local huge_explosion_LLQ = table.deepcopy(data.raw.explosion["big-uranium-explosion-LLQ"])
huge_explosion_LLQ.name = "huge-uranium-explosion-LLQ"
huge_explosion_LLQ.animations[1].scale = huge_explosion_LLQ.animations[1].scale*2
huge_explosion_LLQ.animations[1].shift = {-64,64}
local huge_explosion_RLQ = table.deepcopy(data.raw.explosion["big-uranium-explosion-RLQ"])
huge_explosion_RLQ.name = "huge-uranium-explosion-RLQ"
huge_explosion_RLQ.animations[1].scale = huge_explosion_RLQ.animations[1].scale*2
huge_explosion_RLQ.animations[1].shift = {64,64}
data:extend({huge_explosion_LUQ,huge_explosion_RUQ,huge_explosion_LLQ,huge_explosion_RLQ})
local really_huge_explosion_LUQ = table.deepcopy(data.raw.explosion["big-uranium-explosion-LUQ"])
really_huge_explosion_LUQ.name = "really-huge-uranium-explosion-LUQ"
really_huge_explosion_LUQ.animations[1].scale = really_huge_explosion_LUQ.animations[1].scale*4
really_huge_explosion_LUQ.animations[1].shift = {-128,-128}
local really_huge_explosion_RUQ = table.deepcopy(data.raw.explosion["big-uranium-explosion-RUQ"])
really_huge_explosion_RUQ.name = "really-huge-uranium-explosion-RUQ"
really_huge_explosion_RUQ.animations[1].scale = really_huge_explosion_RUQ.animations[1].scale*4
really_huge_explosion_RUQ.animations[1].shift = {128,-128}
local really_huge_explosion_LLQ = table.deepcopy(data.raw.explosion["big-uranium-explosion-LLQ"])
really_huge_explosion_LLQ.name = "really-huge-uranium-explosion-LLQ"
really_huge_explosion_LLQ.animations[1].scale = really_huge_explosion_LLQ.animations[1].scale*4
really_huge_explosion_LLQ.animations[1].shift = {-128,128}
local really_huge_explosion_RLQ = table.deepcopy(data.raw.explosion["big-uranium-explosion-RLQ"])
really_huge_explosion_RLQ.name = "really-huge-uranium-explosion-RLQ"
really_huge_explosion_RLQ.animations[1].scale = really_huge_explosion_RLQ.animations[1].scale*4
really_huge_explosion_RLQ.animations[1].shift = {128,128}
data:extend({really_huge_explosion_LUQ, really_huge_explosion_RUQ, really_huge_explosion_LLQ, really_huge_explosion_RLQ})
|
local config = {
numOfJobWorkers = 0,
mysql = {
--path = "/tmp/mysql.sock",
path = "/var/run/mysqld/mysqld.sock",
--host = "192.168.0.55",
--port = 3306,
database = "loginMaster",
--user = "funkii",
--password = "12345678",
user = "root",
password = "qcfs_db20180628",
max_packet_size = 1024 * 1024,
},
}
return config
|
---------------------------------------------------------------------------------------------
-- Requirements summary:
-- [PolicyTableUpdate] PoliciesManager must initiate PTU in case getting 'device consent' from the user
--
-- Description:
-- SDL should request PTU in case gets 'device consent' from the user
-- 1. Used preconditions
-- SDL is built with "-DEXTENDED_POLICY: EXTERNAL_PROPRIETARY" flag
-- Connect mobile phone.
-- Register new application.
-- 2. Performed steps
-- Activate application.
-- User consent device
--
-- Expected result:
-- PTU is requested. PTS is created.
-- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED)
---------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
local utils = require ('user_modules/utils')
--[[ Local Functions ]]
local function check_file_exists(name)
local f = io.open(name, "r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFileAndPolicyTable()
testCasesForPolicyTable.Delete_Policy_table_snapshot()
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
require('user_modules/AppTypes')
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:ActivateApp()
local requestId1 = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications["Test Application"] })
EXPECT_HMIRESPONSE(requestId1)
:Do(function(_, data1)
if data1.result.isSDLAllowed ~= true then
local requestId2 = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage",
{ language = "EN-US", messageCodes = { "DataConsent" } })
EXPECT_HMIRESPONSE(requestId2)
:Do(function(_, _)
self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality",
{ allowed = true, source = "GUI", device = { id = utils.getDeviceMAC(), name = utils.getDeviceName() } })
EXPECT_HMICALL("BasicCommunication.ActivateApp")
:Do(function(_, data2)
self.hmiConnection:SendResponse(data2.id,"BasicCommunication.ActivateApp", "SUCCESS", { })
end)
:Times(1)
end)
end
end)
EXPECT_HMICALL("BasicCommunication.PolicyUpdate")
end
function Test:ValidateSnapshot()
local system_file_path = commonFunctions:read_parameter_from_smart_device_link_ini("SystemFilesPath")
if not check_file_exists(system_file_path .. "/sdl_snapshot.json") then
self:FailTestCase("PTS file is NOT created")
end
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_Stop()
StopSDL()
end
return Test
|
require('bqf').setup({
auto_enable = true,
})
|
dyinclude("classes/abstract.logger.class.lua",true);
CLogger = class(CAbstractLogger,
function (self, copyfrom)
self.file = nil;
self.filename = nil;
self.dateformat = "%Y/%m/%d %H:%M:%S";
self.lastMsgTime = 0; -- last time we log a message
self.lastMsg = "<UNKNOWN>"; -- last mesage we log
self.repeatTimer = 20; -- at least x second until repat same message
if( fn ) then
self:openFile(fn);
end
end
);
|
-- DESCRIPTION
-- ========================================================================
-- Widget to show the IP
-- LIBRARY
-- ========================================================================
local awful = require("awful")
local wibox = require("wibox")
local gears = require("gears")
local beautiful = require("beautiful")
local naughty = require("naughty")
local dpi = require("beautiful.xresources").apply_dpi
-- VARIABLES
-- ========================================================================
local ip = {}
-- WIDGET
-- ========================================================================
local function factory(args)
local args = args or {}
local function split(string_to_split, separator)
if separator == nil then separator = "%s" end
local t = {}
for str in string.gmatch(string_to_split, "([^".. separator .."]+)") do
table.insert(t, str)
end
return t
end
args.font = args.font or beautiful.ip_font or beautiful.font
args.fg = args.fg or beautiful.ip_fg or "#000000"
args.bg = args.bg or beautiful.ip_bg or "#FFFFFF"
args.shape = args.shape or beautiful.ip_shape or gears.shape.rect
args.icon = args.icon or beautiful.ip_icon or ""
args.icon_vpn = args.icon_vpn or beautiful.ip_icon_vpn or ""
args.timeout = args.timeout or beautiful.ip_timeout or 30
args.height = args.height or beautiful.ip_height or beautiful.wibar_height
local ip = wibox.widget {
{
{
{
id = "ip_value",
widget = wibox.widget.textbox,
-- https://awesomewm.org/apidoc/classes/wibox.widget.textbox.html
markup = "<span foreground='"..args.fg.."'>" ..
string.format("%s %s", args.icon, "0.0.0.0") ..
"</span>",
ellipsize = "end", -- start, middle, end
wrap = "word_char", -- word, char, word_char
valign = "center", -- top, center, bottom
align = "center", -- left, center, right
font = font,
opacity = 100,
visible = true,
},
layout = wibox.layout.align.horizontal,
},
widget = wibox.container.margin(_, 15, 15, 0, 0),
},
fg = args.fg,
bg = args.bg,
shape = args.shape,
widget = wibox.container.background,
set_ip = function(self, ip)
self:get_children_by_id("ip_value")[1].markup = "" ..
"<span foreground='" .. args.fg .. "'>" ..
string.format("%s %s", args.icon, ip) ..
"</span>"
end
}
local update_widget = function (widget, stdout, stderr, exitcode, exitreason)
local route = {}
for _,line in ipairs(split(stdout,'\r\n')) do
if string.find(line, "src") then
route = split(line," ")
widget:set_ip(route[7])
return
end
end
end
awful.widget.watch('ip route get 8.8.8.8', args.timeout, update_widget, ip)
return ip
end
return setmetatable(ip, { __call = function(_, ...)
return factory(...)
end })
-- vim: fdm=indent
|
local ffi = require 'ffi'
local x11 = require './x11'
local gc = require './gc'
local font = require './font'
return function(opts)
local rects = ffi.new('xcb_rectangle_t[1]')
x11.change_gc(gc, {
foreground = opts.colors.bg;
})
rects[0].x = opts.x + 1
rects[0].y = opts.y + 1
rects[0].width = opts.width - 2
rects[0].height = opts.height - 2
x11.xcb.xcb_poly_fill_rectangle(x11.conn, opts.xwin, gc, 1, rects)
x11.change_gc(gc, {
foreground = opts.colors.border;
line_width = 1;
})
rects[0].x = opts.x
rects[0].y = opts.y
rects[0].width = opts.width - 1
rects[0].height = opts.height - 1
x11.xcb.xcb_poly_rectangle(x11.conn, opts.xwin, gc, 1, rects)
x11.change_gc(gc, {
font = font;
foreground = opts.colors.title;
background = opts.colors.bg;
})
x11.xcb.xcb_image_text_8(x11.conn, #opts.title, opts.xwin, gc, opts.x + 5, opts.y + opts.height - 4, opts.title)
end
|
-- common
-- //-----------------------------------------------------------------------
function print_info(info)
print("[info] " .. info)
end
function print_warning(warning)
print("[warn] " .. warning)
end
function print_err(error)
print("[error!] " .. error)
end
function os.capture(cmd, raw)
print("--------------------------------------------------------------")
print_info(cmd)
local f = assert(io.popen(cmd, 'r'))
local s = assert(f:read('*all'))
print_info(s)
print("--------------------------------------------------------------")
f:close()
end
-- utils
function get_project_path(moduleName, projectName)
return SRC_DIR .. "/" .. moduleName .. "/" .. projectName
end
function project_include(moduleName, projectName)
print_info(moduleName .. "." .. projectName)
dofile(get_project_path(moduleName, projectName) .. "/premake.lua")
end
function get_project_pesudonym(moduleName, projectName)
local projectPseudoNym = moduleName .. "." .. projectName
return projectPseudoNym
end
-- //-----------------------------------------------------------------------
function project_common(moduleName, projectName)
local projectPseudoNym = get_project_pesudonym(moduleName, projectName)
project(projectPseudoNym)
local generatedLocation = path.getabsolute(os.getcwd())
--print_info("generating " .. generatedLocation)
location(generatedLocation)
local outDir = path.getabsolute(TARGET_DIR)
targetdir (outDir)
local vpathDir = "../src/" .. moduleName .. "/" .. projectName .. "/*"
--print_info("vpaths " .. vpathDir)
vpaths { ["*"] = vpathDir }
libdirs {
outDir
}
end
|
local json = require "json"
local database = require "database"
local exit = require "exit"
local template = require'template'
template.caching(false)
-- Compile template, disable cache, enable plain text view to skip filesystem loading
local view = template.compile([[<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>{% for _,f in ipairs(fortunes) do %}<tr><td>{{ f.id }}</td><td>{{ f.message }}</td></tr>{% end %}</table></body></html>]], nil, true)
local function process (db)
local fortunes = db:find({Fortune = {}})
table.insert(fortunes, {id = 0, message = "Additional fortune added at request time."})
table.sort(fortunes, function(a, b)
return a.message < b.message
end)
return fortunes
end
local status, db = pcall(database.connect)
if not status then exit(db) end
local status, res = pcall(process, db)
db:close()
if status then
local html = view({fortunes = res})
ngx.header.content_type = 'text/html; charset=utf-8'
ngx.header.content_length = #html
ngx.print(html)
else
exit(res)
end
|
--[[-------------------------------------------------------------------------
StormFox2.Sun.SetTimeUp(nTime) Sets how long the sun is on the sky.
StormFox2.Sun.IsUp() Returns true if the sun is on the sky.
StormFox2.Moon.SetTimeUp(nTime) Sets how long the moon is on the sky.
---------------------------------------------------------------------------]]
local clamp = math.Clamp
StormFox2.Sun = {}
StormFox2.Moon = {}
StormFox2.Sky = {}
SF_SKY_DAY = 0
SF_SKY_SUNRISE = 1
SF_SKY_SUNSET = 2
SF_SKY_CEVIL = 3
SF_SKY_BLUE_HOUR = 4
SF_SKY_NAUTICAL = 5
SF_SKY_ASTRONOMICAL = 6
SF_SKY_NIGHT = 7
StormFox2.Setting.AddSV("sunrise",360,nil, "Time", 0, 1440)
StormFox2.Setting.SetType("sunrise", "Time")
StormFox2.Setting.AddSV("sunset",1080,nil, "Time", 0, 1440)
StormFox2.Setting.SetType("sunset", "Time")
StormFox2.Setting.AddSV("sunyaw",90,nil, "Effects", 0, 360)
StormFox2.Setting.AddSV("moonlock",false,nil,"Effects")
StormFox2.Setting.AddSV("enable_skybox",true,nil, "Effect")
StormFox2.Setting.AddSV("use_2dskybox",false,nil, "Effects")
StormFox2.Setting.AddSV("overwrite_2dskybox","",nil, "Effects")
-- SunRise and SunSet
-- The sun is up ½ of the day; 1440 / 2 = 720
local SunDelta = 180 / (StormFox2.Data.Get("sun_sunset",1080) - StormFox2.Data.Get("sun_sunrise",360))
local SunMidday = (StormFox2.Data.Get("sun_sunrise",360) + StormFox2.Data.Get("sun_sunset",1080)) / 2
local function SunDeltaUpdate()
SunDelta = 180 / StormFox2.Time.DeltaTime(StormFox2.Data.Get("sun_sunrise",360),StormFox2.Data.Get("sun_sunset",1080))
SunMidday = (StormFox2.Data.Get("sun_sunrise",360) + StormFox2.Data.Get("sun_sunset",1080)) / 2
--[[-------------------------------------------------------------------------
Gets called when the sunset and sunrise changes.
---------------------------------------------------------------------------]]
hook.Run("StormFox2.Sun.DeltaChange")
end
--[[-------------------------------------------------------------------------
Sets the time for sunrise.
---------------------------------------------------------------------------]]
function StormFox2.Sun.SetSunRise(nTime)
if StormFox2.Sun.GetSunRise() == nTime then return end
StormFox2.Network.Set("sun_sunrise",nTime)
SunDeltaUpdate()
end
StormFox2.Setting.Callback("sunrise",StormFox2.Sun.SetSunRise,"StormFox2.heaven.sunrise")
--[[-------------------------------------------------------------------------
Sets the tiem for sunsets.
---------------------------------------------------------------------------]]
function StormFox2.Sun.SetSunSet(nTime)
if StormFox2.Sun.GetSunSet() == nTime then return end
StormFox2.Network.Set("sun_sunset",nTime)
SunDeltaUpdate()
end
StormFox2.Setting.Callback("sunset",StormFox2.Sun.SetSunSet,"StormFox2.heaven.sunset")
--[[-------------------------------------------------------------------------
Returns the time for sunrises.
---------------------------------------------------------------------------]]
function StormFox2.Sun.GetSunRise()
return StormFox2.Data.Get("sun_sunrise",360)
end
--[[-------------------------------------------------------------------------
Returns the time for sunsets.
---------------------------------------------------------------------------]]
function StormFox2.Sun.GetSunSet()
return StormFox2.Data.Get("sun_sunset",1080)
end
--[[
Returns the time when sun is at its higest
]]
function StormFox2.Sun.GetSunAtHigest()
return SunMidday or 720
end
-- Sun functions
--[[-------------------------------------------------------------------------
Sets the sunyaw. This will also affect the moon.
---------------------------------------------------------------------------]]
function StormFox2.Sun.SetYaw(nYaw)
StormFox2.Network.Set("sun_yaw",nYaw)
end
StormFox2.Setting.Callback("sunyaw",StormFox2.Sun.SetYaw,"StormFox2.heaven.sunyaw")
--[[-------------------------------------------------------------------------
Returns the sunyaw.
---------------------------------------------------------------------------]]
function StormFox2.Sun.GetYaw()
return StormFox2.Data.Get("sun_yaw",90)
end
--[[-------------------------------------------------------------------------
Returns true if the sun is on the sky.
---------------------------------------------------------------------------]]
function StormFox2.Sun.IsUp(nTime)
return StormFox2.Time.IsBetween(StormFox2.Sun.GetSunRise(), StormFox2.Sun.GetSunSet(),nTime)
end
--[[-------------------------------------------------------------------------
Sets the sunsize. (Normal is 30)
---------------------------------------------------------------------------]]
function StormFox2.Sun.SetSize(n)
StormFox2.Network.Set("sun_size",n)
end
--[[-------------------------------------------------------------------------
Returns the sunsize. (Normal is 30)
---------------------------------------------------------------------------]]
function StormFox2.Sun.GetSize()
return StormFox2.Data.Get("sun_size",30)
end
--[[-------------------------------------------------------------------------
Sets the suncolor.
---------------------------------------------------------------------------]]
function StormFox2.Sun.SetColor(cCol)
StormFox2.Network.Set("sun_color",cCol)
end
--[[-------------------------------------------------------------------------
Returns the suncolor.
---------------------------------------------------------------------------]]
function StormFox2.Sun.GetColor()
StormFox2.Data.Get("sun_color")
end
--[[-------------------------------------------------------------------------
Returns the sunangle for the current or given time.
---------------------------------------------------------------------------]]
local function GetSunPitch(nTime)
local t = nTime or StormFox2.Time.Get()
local p = (t - StormFox2.Data.Get("sun_sunrise",360)) * SunDelta
if p < -90 or p > 270 then p = -90 end -- Sun stays at -90 pitch, the pitch is out of range
return p
end
function StormFox2.Sun.GetAngle(nTime)
local a = Angle(-GetSunPitch(nTime),StormFox2.Data.Get("sun_yaw",90),0)
return a
end
-- We need a sun-stamp. Since we can't go by time.
-- 0 = day
-- 1 = golden hour
-- 2 = cevil
-- 3 = blue hour
-- 4 = nautical
-- 5 = astronomical
-- 6 = night
local stamp = {
[0] = {SF_SKY_SUNRISE,6,"SunRise"}, -- 6 OK
[6] = {SF_SKY_DAY,168,"Day"}, -- 180 - 6 OK
[174] = {SF_SKY_SUNSET,6,"SunSet"}, -- 174 + 6
[180] = {SF_SKY_CEVIL,4,"Cevil"}, -- 4
[184] = {SF_SKY_BLUE_HOUR,2,"Blue Hour"}, -- 6
[186] = {SF_SKY_NAUTICAL,6,"Nautical"}, -- 12
[192] = {SF_SKY_ASTRONOMICAL,6,"Astronomical"}, -- 18
[198] = {SF_SKY_NIGHT,168,"Night"}, -- 144
[342] = {SF_SKY_ASTRONOMICAL,6,"Astronomical"}, -- 18
[348] = {SF_SKY_NAUTICAL,6,"Nautical"}, -- 12
[354] = {SF_SKY_BLUE_HOUR,2,"Blue Hour"}, -- 6
[356] = {SF_SKY_CEVIL,4,"Cevil"}, -- 4
[360] = {SF_SKY_SUNRISE,6,"SunRise"}, -- 6 OK
}
local lC,lCV = -1,-1
local function GetsunSize()
if lC > CurTime() then return lCV end
lC = CurTime() + 2
local x = StormFox2.Sun.GetSize()
lCV = (-0.00019702 * x^2 + 0.149631 * x - 0.0429803) / 2
return lCV
end
local function GetStamp(nTime,nOffsetDegree)
local sunSize = GetsunSize()
local p = ( GetSunPitch(nTime) + (nOffsetDegree or 0) ) % 360
if p > 90 and p < 270 then -- Sunrise
p = (p - sunSize) % 360
else -- Sunset
p = (p + sunSize) % 360
end
local c_stamp = -1
for p_from,stamp in pairs(stamp) do
if p >= p_from and c_stamp < p_from then
c_stamp = p_from
end
end
return c_stamp,p
end
--[[-------------------------------------------------------------------------
Returns the sun-stamp.
First argument:
0 = day, 1 = golden hour, 2 = cevil, 3 = blue hour
4 = nautical, 5 = astronomical, 6 = night
Second argument:
Time until next sunstamp.
---------------------------------------------------------------------------]]
local lastStamp = 0
function StormFox2.Sky.GetLastStamp()
return lastStamp
end
function StormFox2.Sky.GetStamp(nTime,nOffsetDegree)
local c_stamp,p = GetStamp(nTime,nOffsetDegree)
local d_delta = stamp[c_stamp][2] - (p - c_stamp) -- +degrees
local time_fornextStamp = d_delta / SunDelta
return stamp[c_stamp][1],time_fornextStamp -- 1 = Stamp, 2 = Type of stamp
end
-- Sky hook. Used to update the sky colors and other things.
local nextStamp = -1
hook.Add("StormFox2.Time.Changed","StormFox2.Sky.UpdateStamp",function()
nextStamp = -1
end)
timer.Create("StormFox2.Sky.Stamp", 1, 0, function()
--local c_t = CurTime()
--if c_t < nextStamp then return end
local stamp,n_t = StormFox2.Sky.GetStamp(nil,6) -- Look 6 degrees into the furture so we can lerp the colors.
--nextStamp = c_t + (n_t * SunDelta) / StormFox2.Time.GetSpeed()
--[[-------------------------------------------------------------------------
This hook gets called when the sky-stamp changes. This is used to change the sky-colors and other things.
First argument:
0 = day, 1 = golden hour, 2 = cevil, 3 = blue hour
4 = nautical, 5 = astronomical, 6 = night
Second argument:
The lerp-time to change the variable.
---------------------------------------------------------------------------]]
if lastStamp == stamp then return end -- Don't call it twice.
lastStamp = stamp
hook.Run("StormFox2.Sky.StampChange", stamp, 3 / SunDelta )
end)
-- It takes the moon 27 days to orbit eath .. and about 12.5 hours avage on the sky each night
-- 29.5 days for a full cyckle
--[[-------------------------------------------------------------------------
Sets the moon-offset it gains each day. (Default 7.5)
---------------------------------------------------------------------------]]
function StormFox2.Moon.SetDaysForFullCycle(nVar)
StormFox2.Network.Set("moon_cycle",360 / nVar)
end
hook.Add("StormFox2.Time.NextDay","StormFox2.MoonPhase",function()
local d = StormFox2.Data.Get("moon_magicnumber",0) + StormFox2.Data.Get("moon_cycle",12.203)
StormFox2.Network.Set("moon_magicnumber",d % 360)
end)
--[[-------------------------------------------------------------------------
Returns the moon angles for the given or current time.
---------------------------------------------------------------------------]]
local tf = 0
local a = 7.4 / 7
function StormFox2.Moon.GetAngle(nTime)
--if true then return Angle(300,StormFox2.Data.Get("sun_yaw",90),0) end
local day_f = (nTime or StormFox2.Time.Get()) / 1440
tf = math.max(tf, day_f)
local day_n = tf + StormFox2.Date.GetYearDay()
local p_c = ((day_n * a) % 8) * 45 + StormFox2.Data.Get("magic_moonnumber",0)
return Angle(-p_c % 360,StormFox2.Data.Get("sun_yaw",90),0)
end
--[[-------------------------------------------------------------------------
Returns true if the moon is up.
---------------------------------------------------------------------------]]
function StormFox2.Moon.IsUp()
local t = StormFox2.Moon.GetAngle().p
local s = StormFox2.Data.Get("moonSize",20) / 6.9
return t > 180 - s or t < s
end
--[[-------------------------------------------------------------------------
Sets the moon phase
---------------------------------------------------------------------------]]
SF_MOON_NEW = 0
SF_MOON_WAXIN_CRESCENT = 1
SF_MOON_FIRST_QUARTER = 2
SF_MOON_WAXING_GIBBOUS = 3
SF_MOON_FULL = 4
SF_MOON_WANING_GIBBOUS = 5
SF_MOON_LAST_QUARTER = 6
SF_MOON_WANING_CRESCENT = 7
-- Around 7.4 days. Angle 270 == up
if SERVER then
local a = 7.4 / 7
function StormFox2.Moon.SetPhase( moon_phase, nTime )
local day_f = (nTime or StormFox2.Time.Get()) / 1440
local day_n = day_f + StormFox2.Date.GetYearDay()
local pitch = ((day_n * a) % 8) * 360 -- Current moon angle
local dif = pitch - GetSunPitch(nTime) + 180
StormFox2.Network.Set("magic_moonnumber",dif)
end
end
--[[
When angle is 270, it is a max
]]
--[[-------------------------------------------------------------------------
Returns the moon phase for the current day
---------------------------------------------------------------------------]]
function StormFox2.Moon.GetPhase()
local mp = StormFox2.Data.Get("moon_phase",SF_MOON_FULL)
local yd = StormFox2.Date.GetYearDay()
local dif = (mp - yd) % 8
return dif
end
--[[-------------------------------------------------------------------------
Returns the current moon phase
5 = Full moon
3 = Half moon
0 = New moon
Seconary returns the angle towards the sun from the moon.
---------------------------------------------------------------------------]]
function StormFox2.Moon.GetPhaseold(nTime)
-- Calculate the distance between the two (Somewhat real scale)
local mAng = StormFox2.Moon.GetAngle(nTime)
local A = StormFox2.Sun.GetAngle(nTime):Forward() * 14975
local B = mAng:Forward() * 39
-- Get the angle towards the sun from the moon
local moonTowardSun = (A - B):Angle()
local C = mAng
C.r = 0
local dot = C:Forward():Dot(moonTowardSun:Forward())
return clamp(2.5 - (5.5 * dot) / 2,0,5),moonTowardSun
end
--[[-------------------------------------------------------------------------
Returns the moon phase name
---------------------------------------------------------------------------]]
function StormFox2.Moon.GetPhaseName(nTime)
local n = StormFox2.Moon.GetPhase(nTime)
local pDif = math.AngleDifference(StormFox2.Moon.GetAngle(nTime).p, StormFox2.Sun.GetAngle(nTime).p)
if n >= 4.9 then
return "Full Moon"
elseif n <= 0.1 then
return "New Moon"
elseif pDif > 0 then
return "Third Quarder"
else
return "First Quarder"
end
end
-- Skybox
local function SkyTick(b)
b = b and StormFox2.Setting.SFEnabled()
if b then -- Reenable skybox
local _2d = StormFox2.Setting.GetCache("use_2dskybox", false)
if not _2d then
RunConsoleCommand("sv_skyname", "painted")
else
local sky_over = StormFox2.Setting.GetCache("overwrite_2dskybox", "")
if sky_over == "" then
sky_over = StormFox2.Weather.GetCurrent():Get("skyBox",StormFox2.Sky.GetLastStamp()) or "skybox/sky_day02_06_hdrbk"
if type(sky_over) == "table" then
sky_over = table.Random(sky_over)
end
end
RunConsoleCommand("sv_skyname", sky_over)
end
else -- Disable skybox
local map_ent = StormFox2.Map.Entities()[1]
if not map_ent then
StormFox2.Warning("No map-entity?")
RunConsoleCommand("sv_skyname", "skybox/sky_day02_06_hdrbk")
return
end
local sky_name = map_ent["skyname"] or "skybox/sky_day02_06_hdrbk"
StormFox2.Map.Set2DSkyBoxDarkness( 1 )
RunConsoleCommand("sv_skyname", sky_name)
end
end
local func = function(b)
SkyTick(StormFox2.Setting.GetCache("enable_skybox", true))
end
StormFox2.Setting.Callback("enable", func, "disable_heavens")
StormFox2.Setting.Callback("clenable", func, "disable_heavenscl")
StormFox2.Setting.Callback("enable_skybox",SkyTick,"enable_skybox_call")
|
if not wac then return end
if SERVER then AddCSLuaFile('shared.lua') end
ENT.Base = "wac_pl_base"
ENT.Type = "anim"
ENT.Category = wac.aircraft.spawnCategoryC
ENT.PrintName = "F-4 Phantom II"
ENT.Author = "SentryGunMan"
ENT.Spawnable = true
ENT.AdminSpawnable = true
ENT.Model = "models/sentry/f4.mdl"
ENT.RotorPhModel = "models/props_junk/sawblade001a.mdl"
ENT.RotorModel = "models/props_junk/PopCan01a.mdl"
ENT.rotorPos = Vector(0,0,74)
ENT.TopRotorDir = 1.0
ENT.AutomaticFrameAdvance = true
ENT.EngineForce = 500
ENT.Weight = 18825
ENT.SeatSwitcherPos = Vector(0,0,0)
ENT.AngBrakeMul = 0.02
ENT.SmokePos = Vector(-155,24,65)
ENT.FirePos = Vector(-155,24,65)
if CLIENT then
ENT.thirdPerson = {
distance = 550
}
end
ENT.Agility = {
Thrust = 10
}
ENT.Wheels={
{
mdl="models/sentry/f4_bw.mdl",
pos=Vector(-43,96,14),
friction=10,
mass=600,
},
{
mdl="models/sentry/f4_bw.mdl",
pos=Vector(-43,-96,14),
friction=10,
mass=600,
},
{
mdl="models/sentry/f4_fw.mdl",
pos=Vector(217.25,0,12),
friction=10,
mass=1200,
},
}
ENT.Seats = {
{
pos=Vector(178,0,75.5),
exit=Vector(178,100,40),
weapons={"M61 Vulcan"},
},
{
pos=Vector(123, 0, 85),
exit=Vector(123,100,40),
weapons={"Bomb"}
},
}
ENT.Weapons = {
["M61 Vulcan"] = {
class = "wac_pod_gatling",
info = {
Pods = {
Vector(107,0,35),
Vector(107,0,35),
},
Sounds = {
shoot = "WAC/f4/gun.wav",
stop = "WAC/f4/gun_stop.wav"
}
}
},
["Bomb"] = {
class = "wac_pod_bomb",
info = {
Pods = {
Vector(40,75,20),
Vector(40,-75,20),
Vector(40,60,40),
Vector(40,90,40),
Vector(40,-60,40),
Vector(40,-90,40),
},
model="models/props_phx/ww2bomb.mdl",
}
}
}
ENT.Sounds={
Start="WAC/f4/Start.wav",
Blades="WAC/f4/external.wav",
Engine="WAC/f4/internal.wav",
MissileAlert="HelicopterVehicle/MissileNearby.mp3",
MissileShoot="HelicopterVehicle/MissileShoot.mp3",
MinorAlarm="HelicopterVehicle/MinorAlarm.mp3",
LowHealth="HelicopterVehicle/LowHealth.mp3",
CrashAlarm="HelicopterVehicle/CrashAlarm.mp3"
}
// heatwave
if CLIENT then
local cureffect=0
function ENT:Think()
self:base("wac_pl_base").Think(self)
local throttle = self:GetNWFloat("up", 0)
local active = self:GetNWBool("active", false)
local ent=LocalPlayer():GetVehicle():GetNWEntity("wac_aircraft")
if ent==self and active and throttle > 0.2 and CurTime()>cureffect then
cureffect=CurTime()+0.02
local ed=EffectData()
ed:SetEntity(self)
ed:SetOrigin(Vector(-155,0,65)) // offset
ed:SetMagnitude(throttle)
ed:SetRadius(30)
util.Effect("wac_heatwave", ed)
end
end
end
//function ENT:DrawWeaponSelection() end
|
-- register data
local _static_data = {
name = "steam-geyser",
entity_name = "steam-geyser-bare",
default_floor = "sand",
position = {
offset = { 300, 400 },
}
}
local _upgrade_data = {
name = "steam-geyser-bare",
upgrades = {
["restored-steam-geyser"] = {
entity_name = "steam-geyser-pump",
}
}
}
local _event_data = {
entity_name = "steam-geyser-pump",
on_tick = script.generate_event_name(),
attract_biters = {
chance = { 0.0, 0.5 },
cycle = 600 * Time.SECOND,
count = { 1, 10 },
}
}
local _composite_data = {
base_entity = "steam-geyser-bare",
destroy_origional = false,
component_entities = {
{ entity_name = "invisible-label-1x1", offset = { x=0, y=0 }, operable=false, lable="Steam Geyser" }
}
}
remote.call( "k-static-entities", "register", _static_data )
remote.call( "k-upgradable-entities", "register", _upgrade_data )
remote.call( "k-entity-events", "register", _event_data )
remote.call( "k-composite-entities", "register", _composite_data )
-- if the pump has created any water, make it 100 degrees
Event.register(_event_data.on_tick, function(event)
if event.entity and event.entity.valid and event.entity.fluidbox then
for i = 1, #event.entity.fluidbox do
if event.entity.fluidbox[i] and event.entity.fluidbox[i].temperature then
local _box = event.entity.fluidbox[i]
_box.temperature = 100
event.entity.fluidbox[i] = _box
end
end
end
end)
|
--------------------------------------------------------------------------------
--<[ Внутренние события ]>------------------------------------------------------
--------------------------------------------------------------------------------
addEvent( "Popup.onServerShowPopup", true ) -- Сервер показал popup ( string message, string / nil messageType, string / nil icon, number / nil delay )
--------------------------------------------------------------------------------
--<[ Модуль Popup ]>------------------------------------------------------------
--------------------------------------------------------------------------------
Popup = {
init = function()
addEventHandler( "Popup.onServerShowPopup", resourceRoot, Popup.onServerShowPopup )
Main.setModuleLoaded( "Popup", 1 )
end;
-- Показать всплывающую подсказку
-- > message string - текст подсказки
-- > messageType string / nil - тип подсказки (по умолчанию info)
-- > icon string / nil - значок возле подсказки (FontAwesome)
-- > delay number / nil - время видимости окошка в мс. (по умолчанию 5000)
-- = void
show = function( message, messageType, icon, delay )
GUI.sendJS( "Popup.show", message, messageType, icon, tonumber( delay ) )
end;
----------------------------------------------------------------------------
--<[ Обработчики событий ]>-------------------------------------------------
----------------------------------------------------------------------------
-- Сервер показал popup
onServerShowPopup = function( message, messageType, icon, delay )
Popup.show( message, messageType, icon, delay )
end;
};
addEventHandler( "onClientResourceStart", resourceRoot, Popup.init )
|
local Schema = require "kong.db.schema"
local ts = require "kong.db.schema.topological_sort"
describe("schemas_topological_sort", function()
local function collect_names(schemas)
local names = {}
for i = 1, #schemas do
names[i] = schemas[i].name
end
return names
end
local function schema_new(s)
return assert(Schema.new(s))
end
it("sorts an array of unrelated schemas alphabetically by name", function()
local a = schema_new({ name = "a", fields = {} })
local b = schema_new({ name = "b", fields = {} })
local c = schema_new({ name = "c", fields = {} })
local x = ts({ c, a, b })
assert.same({"a", "b", "c"}, collect_names(x))
end)
it("it puts destinations first", function()
local a = schema_new({ name = "a", fields = {} })
local c = schema_new({
name = "c",
fields = {
{ a = { type = "foreign", reference = "a" }, },
}
})
local b = schema_new({
name = "b",
fields = {
{ a = { type = "foreign", reference = "a" }, },
{ c = { type = "foreign", reference = "c" }, },
}
})
local x = ts({ a, b, c })
assert.same({"a", "c", "b"}, collect_names(x))
end)
it("puts core entities first, even when no relations", function()
local a = schema_new({ name = "a", fields = {} })
local routes = schema_new({ name = "routes", fields = {} })
local x = ts({ a, routes })
assert.same({"routes", "a"}, collect_names(x))
end)
it("puts workspaces before core and others, when no relations", function()
local a = schema_new({ name = "a", fields = {} })
local workspaces = schema_new({ name = "workspaces", fields = {} })
local routes = schema_new({ name = "routes", fields = {} })
local x = ts({ a, routes, workspaces })
assert.same({"workspaces", "routes", "a"}, collect_names(x))
end)
it("puts workspaces first, core entities second, and other entities afterwards, even with relations", function()
local a = schema_new({ name = "a", fields = {} })
local services = schema_new({ name = "services", fields = {} })
local b = schema_new({
name = "b",
fields = {
{ service = { type = "foreign", reference = "services" }, },
{ a = { type = "foreign", reference = "a" }, },
}
})
local routes = schema_new({
name = "routes",
fields = {
{ service = { type = "foreign", reference = "services" }, },
}
})
local workspaces = schema_new({ name = "workspaces", fields = {} })
local x = ts({ services, b, a, workspaces, routes })
assert.same({ "workspaces", "services", "routes", "a", "b" }, collect_names(x))
end)
it("overrides core order if dependencies force it", function()
-- This scenario is here in case in the future we allow plugin entities to precede core entities
-- Not applicable today (kong 2.3.x) but maybe in future releases
local a = schema_new({ name = "a", fields = {} })
local services = schema_new({ name = "services", fields = {
{ a = { type = "foreign", reference = "a" } } -- we somehow forced services to depend on a
}})
local workspaces = schema_new({ name = "workspaces", fields = {
{ a = { type = "foreign", reference = "a" } } -- we somehow forced workspaces to depend on a
} })
local x = ts({ services, a, workspaces })
assert.same({ "a", "workspaces", "services" }, collect_names(x))
end)
it("returns an error if cycles are found", function()
local a = schema_new({
name = "a",
fields = {
{ b = { type = "foreign", reference = "b" }, },
}
})
local b = schema_new({
name = "b",
fields = {
{ a = { type = "foreign", reference = "a" }, },
}
})
local x, err = ts({ a, b })
assert.is_nil(x)
assert.equals("Cycle detected, cannot sort topologically", err)
end)
end)
|
-----------------------------------
-- Area: Bastok Markets
-- NPC: Nbu Latteh
-- Starts & Finishes Quest: Mom, The Adventurer?
-- Starts Quest: The Signpost Marks the Spot
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/quests");
local ID = require("scripts/zones/Bastok_Markets/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local pFame = player:getFameLevel(BASTOK);
local momTheAdventurer = player:getQuestStatus(BASTOK,tpz.quest.id.bastok.MOM_THE_ADVENTURER);
local questStatus = player:getCharVar("MomTheAdventurer_Event");
if (player:needToZone()) then
player:startEvent(127); -- chat about my work
elseif (pFame < 2 and momTheAdventurer ~= QUEST_ACCEPTED and questStatus == 0) then
player:startEvent(230);
elseif (momTheAdventurer >= QUEST_ACCEPTED and questStatus == 2) then
if (player:seenKeyItem(tpz.ki.LETTER_FROM_ROH_LATTEH)) then
player:startEvent(234);
elseif (player:hasKeyItem(tpz.ki.LETTER_FROM_ROH_LATTEH)) then
player:startEvent(233);
else
player:startEvent(231);
end
elseif (pFame >= 2 and player:getQuestStatus(BASTOK,tpz.quest.id.bastok.THE_SIGNPOST_MARKS_THE_SPOT) == QUEST_AVAILABLE) then
player:startEvent(235);
else
player:startEvent(127);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 230 and option == 0) then
if (player:getFreeSlotsCount(0) > 0) then
player:setCharVar("MomTheAdventurer_Event",1);
player:addItem(4096);
player:messageSpecial(ID.text.ITEM_OBTAINED,4096); -- Fire Crystal
if (player:getQuestStatus(BASTOK,tpz.quest.id.bastok.MOM_THE_ADVENTURER) == QUEST_AVAILABLE) then
player:addQuest(BASTOK,tpz.quest.id.bastok.MOM_THE_ADVENTURER);
end
else
player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,4096);
end
elseif (csid == 233 or csid == 234) then
if (player:seenKeyItem(tpz.ki.LETTER_FROM_ROH_LATTEH)) then
gilReward = 100;
else
gilReward = 200;
end
player:needToZone(true);
player:delKeyItem(tpz.ki.LETTER_FROM_ROH_LATTEH);
player:addTitle(tpz.title.RINGBEARER);
player:addGil(GIL_RATE*gilReward);
player:messageSpecial(ID.text.GIL_OBTAINED, GIL_RATE*gilReward);
player:setCharVar("MomTheAdventurer_Event",0);
if (player:getQuestStatus(BASTOK,tpz.quest.id.bastok.MOM_THE_ADVENTURER) == QUEST_ACCEPTED) then
player:addFame(BASTOK,20);
player:completeQuest(BASTOK,tpz.quest.id.bastok.MOM_THE_ADVENTURER);
else
player:addFame(BASTOK,8)
end
elseif (csid == 235 and option == 0) then
player:addQuest(BASTOK,tpz.quest.id.bastok.THE_SIGNPOST_MARKS_THE_SPOT);
player:setCharVar("MomTheAdventurer_Event",0);
end
end;
|
--------------------------------------------------------------------------------
-- 81-501 controller panel
--------------------------------------------------------------------------------
-- Copyright (C) 2013-2018 Metrostroi Team & FoxWorks Aerospace s.r.o.
-- Contains proprietary code. See license.txt for additional information.
--------------------------------------------------------------------------------
Metrostroi.DefineSystem("81_501_Panel")
function TRAIN_SYSTEM:Initialize()
-- Выключатель батареи (ВБ)
self.Train:LoadSystem("VB","Relay","Switch", {bass = true})
self.Train:LoadSystem("AV","Relay","Switch", {bass = true})
self.Train:LoadSystem("KSD","Relay","Switch", {bass = true}) --???
self.Train:LoadSystem("KPVU","Relay","Switch", {bass = true})
self.Train:LoadSystem("VKF","Relay","Switch", {bass = true})
self.Train:LoadSystem("VU","Relay","Switch", {bass = true})
self.Train:LoadSystem("VU1","Relay","Switch", {bass = true}) --Heater
self.Train:LoadSystem("VU2","Relay","Switch", {bass = true}) --EmergencyLights
self.Train:LoadSystem("VU3","Relay","Switch", {bass = true}) --CabLights
self.Train:LoadSystem("KRZD","Relay","Switch", {bass = true})
self.Train:LoadSystem("KDL","Relay","Switch", {bass = true})
self.Train:LoadSystem("LOn","Relay","Switch", {bass = true})
self.Train:LoadSystem("LOff","Relay","Switch", {bass = true})
self.Train:LoadSystem("VozvratRP","Relay","Switch", {bass = true})
self.Train:LoadSystem("KSN","Relay","Switch", {bass = true})
self.Train:LoadSystem("KDP","Relay","Switch", {bass = true})
self.Train:LoadSystem("VMK","Relay","Switch", {bass = true})
self.Train:LoadSystem("VUS","Relay","Switch", {bass = true})
self.Train:LoadSystem("VUD","Relay","Switch", {bass = true})
self.Train:LoadSystem("VDL","Relay","Switch", {bass = true})
self.Train:LoadSystem("KDPH","Relay","Switch", {bass = true})
self.Train:LoadSystem("PanelLamp","Relay","Switch", {bass = true, normally_closed=true})
self.V1 = 0
self.S6 = 0
self.S1 = 0
self.S2 = 0
self.SSN = 0
self.SSD = 0
self.TW18 = 0
self.Headlights1 = 0
self.Headlights2 = 0
self.RedLights = 0
self.EmergencyLights1 = 0
self.EmergencyLights2 = 0
self.MainLights1 = 0
self.MainLights2 = 0
self.BrY = 0
self.DoorsW = 0
self.DoorsWC = 0
self.GreenRP = 0
self.AnnouncerPlaying = 0
self.UPOPower = 0
end
function TRAIN_SYSTEM:Outputs()
return { "V1","GreenRP","S6","S1","S2","SSN","SSD","TW18","Headlights1","Headlights2","RedLights","EmergencyLights1","EmergencyLights2","MainLights1","MainLights2","BrY","DoorsW","DoorsWC","AnnouncerPlaying","UPOPower"}
end
|
local loremipsum = {}
local mattata = require('mattata')
local HTTP = require('socket.http')
function loremipsum:init(configuration)
loremipsum.arguments = 'loremipsum'
loremipsum.commands = mattata.commands(self.info.username, configuration.commandPrefix):c('loremipsum').table
loremipsum.help = configuration.commandPrefix .. 'loremipsum - Generates a few Lorem Ipsum sentences!'
end
function loremipsum:onChannelPost(channel_post, configuration)
local str, res = HTTP.request('http://loripsum.net/api/1/medium/plaintext')
if res ~= 200 then
mattata.sendMessage(channel_post.chat.id, configuration.errors.connection, nil, true, false, channel_post.message_id)
return
end
mattata.sendMessage(channel_post.chat.id, str, nil, true, false, channel_post.message_id)
end
function loremipsum:onMessage(message, language)
local str, res = HTTP.request('http://loripsum.net/api/1/medium/plaintext')
if res ~= 200 then
mattata.sendMessage(message.chat.id, language.errors.connection, nil, true, false, message.message_id)
return
end
mattata.sendMessage(message.chat.id, str, nil, true, false, message.message_id)
end
return loremipsum
|
bit32 = bit
---Indicates a call when the server first starts up.
RESET_REASON_BOOT = 0
---Indicates a call by the engine, usually when the round/day resets in default game modes.
RESET_REASON_ENGINECALL = 1
---Indicates a call after the Lua state was manually reset.
RESET_REASON_LUARESET = 2
---Indicates a call from Server:reset.
RESET_REASON_LUACALL = 3
---In round-based modes, the player list screen is shown in this state to those who aren't spawned in.
STATE_PREGAME = 1
---Game is ongoing. In round-based modes, players not spawned in will spectate. World players can spawn as they please.
STATE_GAME = 2
---Used in round-based modes when the game is over and the player list is shown before reset.
STATE_RESTARTING = 3
---Driving mode.
---@deprecated
TYPE_DRIVING = 1
---Racing mode.
---@deprecated
TYPE_RACE = 2
---Round mode.
TYPE_ROUND = 3
---World mode.
TYPE_WORLD = 4
---Eliminator mode.
TYPE_TERMINATOR = 5
---Co-op mode.
TYPE_COOP = 6
---Versus mode.
TYPE_VERSUS = 7
---The hook library which hooked events will call upon.
---The hook.run function must be defined to use hooks.
hook = {
persistentMode = ''
}
---Append to the prefix of the next printed line.
---@param prefix string The string to add to the next prefix.
---@deprecated
function printAppend(prefix) end
---Recreate the Lua state completely at the start of the next logic tick.
---Runs lua/main.lua again after reset.
---@param mode string The string to set to hook.persistentMode in the new state.
function flagStateForReset(mode) end
---Create a new Vector with 0 for every coordinate.
---@return Vector vector The created vector.
function Vector() end
---Create a new Vector with given coordinates.
---@param x number
---@param y number
---@param z number
---@return Vector vector The created vector.
function Vector(x, y, z) end
---Create a new RotMatrix.
---@param x1 number
---@param y1 number
---@param z1 number
---@param x2 number
---@param y2 number
---@param z2 number
---@param x3 number
---@param y3 number
---@param z3 number
---@return RotMatrix rotMatrix The created rotation matrix.
function RotMatrix(
x1, y1, z1,
x2, y2, z2,
x3, y3, z3
) end
---Library for sending HTTP(S) requests.
http = {}
---@class HTTPResponse
---@field status integer The HTTP status code.
---@field body string The response body.
---@field headers table<string, string> The response headers.
---Send an HTTP(S) GET request asynchronously.
---@param scheme string The hostname of the server to send the request to, with optional protocol and port. Ex. google.com, https://google.com, https://google.com:443
---@param path string The path to request from the server.
---@param headers table<string, string> The table of request headers.
---@param callback fun(response: HTTPResponse?) The function to be called when the response is received or there was an error.
function http.get(scheme, path, headers, callback) end
---Send an HTTP(S) POST request asynchronously.
---@param scheme string The hostname of the server to send the request to, with optional protocol and port. Ex. google.com, https://google.com, https://google.com:443
---@param path string The path to request from the server.
---@param headers table<string, string> The table of request headers.
---@param body string The request body.
---@param contentType string The request body MIME type.
---@param callback fun(response: HTTPResponse?) The function to be called when the response is received or there was an error.
function http.post(scheme, path, headers, body, contentType, callback) end
---Library for creating networked events.
event = {}
---Play a sound.
---@param soundType integer The type of the sound.
---@param position Vector The position of the sound.
---@param volume number The volume of the sound, where 1.0 is standard.
---@param pitch number The pitch of the sound, where 1.0 is standard.
function event.sound(soundType, position, volume, pitch) end
---Play a sound.
---@param soundType integer The type of the sound.
---@param position Vector The position of the sound.
function event.sound(soundType, position) end
---Display a grenade explosion.
---@param position Vector The position to show the explosion at.
function event.explosion(position) end
---Indicate a bullet has hit a person or thing.
---@param hitType integer The type of hit. 0 = bullet hole (stays until round reset), 1 = human hit (blood), 2 = car hit (metal), 3 = blood drip (bleeding).
---@param position Vector The position the bullet hit.
---@param normal Vector The normal of the surface the bullet hit.
function event.bulletHit(hitType, position, normal) end
---Library for using generic physics functions of the engine.
physics = {}
---@class LineIntersectResult
---@field hit boolean Whether it hit. If false, all other fields will be nil.
---@field pos Vector? The global position where the ray hit.
---@field normal Vector? The normal of the surface the ray hit.
---@field fraction number? How far along the ray the hit was (0.0 - 1.0).
---@field bone integer? Which bone the ray hit, if it was cast on a human.
---@field face integer? Which face the ray hit, if not a wheel, if it was cast on a vehicle.
---@field wheel integer? Which wheel the ray hit, if not a face, if it was cast on a vehicle.
---Cast a ray in the level and find where it hits.
---@param posA Vector The start point of the ray.
---@param posB Vector The end point of the ray.
---@return LineIntersectResult result The result of the intersection.
function physics.lineIntersectLevel(posA, posB) end
---Cast a ray on a single human.
---@param human Human The human to cast the ray on.
---@param posA Vector The start point of the ray.
---@param posB Vector The end point of the ray.
---@return LineIntersectResult result The result of the intersection.
function physics.lineIntersectHuman(human, posA, posB) end
---Cast a ray on a single vehicle.
---@param vehicle Vehicle The vehicle to cast the ray on.
---@param posA Vector The start point of the ray.
---@param posB Vector The end point of the ray.
---@return LineIntersectResult result The result of the intersection.
function physics.lineIntersectVehicle(vehicle, posA, posB) end
---Cast a ray on an arbitrary triangle.
---The vertices of the triangle must be clockwise relative to the normal.
---The vector passed to outPosition will be modified by the function.
---@param outPosition Vector A vector whose values will be set to the position the ray hit.
---@param normal Vector The normal of the triangle.
---@param posA Vector The start point of the ray.
---@param posB Vector The end point of the ray.
---@param triA Vector The first vertex of the triangle.
---@param triB Vector The second vertex of the triangle.
---@param triC Vector The third vertex of the triangle.
---@return number? fraction How far along the ray hit was (0.0 - 1.0). Nil if it did not hit.
function physics.lineIntersectTriangle(outPosition, normal, posA, posB, triA, triB, triC) end
---Remove all bullets that have no time remaining.
---May shift bullets in memory if any are removed.
function physics.garbageCollectBullets() end
---Library for sending chat messages.
chat = {}
---Display a message in the chat box to everybody.
---@param message string The message to send. Max length 63.
function chat.announce(message) end
---Display a message in the chat box only to admins.
---More specifically, all players whose connection has `adminVisible` set to true.
---@param message string The message to send. Max length 63.
function chat.tellAdmins(message) end
---Add a message to chat using the engine's expected values.
---@param speakerType integer The type of message. 0 = dead chat, 1 = human speaking, 2 = item speaking, 3 = MOTD, 4 = to admins, 5 = billboard, 6 = to player.
---@param message string The message to send. Max length 63.
---@param speakerIndex integer The index of the speaker object of the corresponding type, if applicable, or -1.
---@param volumeLevel integer The volume to speak at. 0 = whisper, 1 = normal, 2 = yell.
---@deprecated
function chat.addRaw(speakerType, message, speakerIndex, volumeLevel) end
---Library for managing Account objects.
---accounts[index: integer] -> Account
accounts = {}
---Save all accounts to the `server.srk` file.
function accounts.save() end
---Get all accounts.
---@return Account[] accounts A list of all Account objects.
function accounts.getAll() end
---Get the number of accounts.
---@return integer count How many Account objects there are.
function accounts.getCount() end
---Find an account by phone number.
---@param phoneNumber integer The phone identifier to search for.
---@return Account? account The found account, or nil.
function accounts.getByPhone(phoneNumber) end
---Library for managing Player objects.
---players[index: integer] -> Player
players = {}
---Get all players.
---@return Player[] players A list of all Player objects.
function players.getAll() end
---Get the number of players.
---@return integer count How many Player objects there are.
function players.getCount() end
---Find a player by phone number.
---@param phoneNumber integer The phone identifier to search for.
---@return Player? player The found player, or nil.
function players.getByPhone(phoneNumber) end
---Get all players, excluding bots.
---@return Player[] players A list of all Player objects, excluding bots.
function players.getNonBots() end
---Create a new bot player.
---@return Player? bot The created bot player, or nil on failure.
function players.createBot() end
---Library for managing Human objects.
---humans[index: integer] -> Human
humans = {}
---Get all humans.
---@return Human[] humans A list of all Human objects.
function humans.getAll() end
---Get the number of humans.
---@return integer count How many Human objects there are.
function humans.getCount() end
---Create a new human.
---@param position Vector The position of the new Human.
---@param rotation RotMatrix The rotation of the new Human.
---@param player Player The player whose human this will be.
---@return Human? human The created human, or nil on failure.
function humans.create(position, rotation, player) end
---Library for managing ItemType objects.
---itemTypes[index: integer] -> ItemType
itemTypes = {}
---Get all item types.
---@return ItemType[] itemTypes A list of all ItemType objects.
function itemTypes.getAll() end
---Get the number of item types.
---@return integer count How many ItemType objects there are.
function itemTypes.getCount() end
---Library for managing Item objects.
---items[index: integer] -> Item
items = {}
---Get all items.
---@return Item[] items A list of all Item objects.
function items.getAll() end
---Get the number of items.
---@return integer count How many Item objects there are.
function items.getCount() end
---Create a new item.
---@param type integer The type of the item.
---@param position Vector The position of the item.
---@param rotation RotMatrix The rotation of the item.
---@return Item? item The created item, or nil on failure.
function items.create(type, position, rotation) end
---Create a new item.
---@param type integer The type of the item.
---@param position Vector The position of the item.
---@param velocity Vector The initial velocity of the item.
---@param rotation RotMatrix The rotation of the item.
---@return Item? item The created item, or nil on failure.
function items.create(type, position, velocity, rotation) end
---Create a floppy rope consisting of many items.
---@param position Vector The position of the rope. Seems to be offset.
---@param rotation Vector The rotation of the rope.
---@return Item? item The created item, or nil on failure.
---@deprecated
function items.createRope(position, rotation) end
---Library for managing Vehicle objects.
---vehicles[index: integer] -> Vehicle
vehicles = {}
---Get all vehicles.
---@return Vehicle[] vehicles A list of all Vehicle objects.
function vehicles.getAll() end
---Get the number of vehicles.
---@return integer count How many Vehicle objects there are.
function vehicles.getCount() end
---Create a new vehicle.
---@param type integer The type of the vehicle.
---@param position Vector The position of the vehicle.
---@param rotation RotMatrix The rotation of the vehicle.
---@param color integer The color of the vehicle.
---@return Vehicle? vehicle The created vehicle, or nil on failure.
function vehicles.create(type, position, rotation, color) end
---Library for managing Bullet objects.
bullets = {}
---Get all bullets.
---@return Bullet[] bullets A list of all Bullet objects.
function bullets.getAll() end
---Get the number of bullets.
---@return integer count How many Bullet objects there are.
function bullets.getCount() end
---Library for managing RigidBody objects.
---rigidBodies[index: integer] -> RigidBody
rigidBodies = {}
---Get all rigid bodies.
---@return RigidBody[] rigidBodies A list of all RigidBody objects.
function rigidBodies.getAll() end
---Get the number of rigid bodies.
---@return integer count How many RigidBody objects there are.
function rigidBodies.getCount() end
---Library for managing Bond objects.
---bonds[index: integer] -> Bond
bonds = {}
---Get all bonds.
---@return Bond[] bonds A list of all Bond objects.
function bonds.getAll() end
---Get the number of bonds.
---@return integer count How many Bond objects there are.
function bonds.getCount() end
---Library for managing Street objects.
---streets[index: integer] -> Street
streets = {}
---Get all streets.
---@return Street[] streets A list of all Street objects.
function streets.getAll() end
---Get the number of streets.
---@return integer count How many Street objects there are.
function streets.getCount() end
---Library for managing StreetIntersection objects.
---intersections[index: integer] -> StreetIntersection
intersections = {}
---Get all street intersections.
---@return StreetIntersection[] intersections A list of all StreetIntersection objects.
function intersections.getAll() end
---Get the number of street intersections.
---@return integer count How many StreetIntersection objects there are.
function intersections.getCount() end
---@class ListDirectoryEntry
---@field isDirectory boolean Whether the entry is a directory.
---@field name string The name of the file/directory. Ex. "asphalt2.png".
---@field stem string The stem of the filename if this is a file. Ex. "asphalt2".
---@field extension string The extension of the filename if this is a file. Ex. ".png".
---Get the contents of a directory.
---@param path string The path to the directory to scan.
---@return ListDirectoryEntry[] entries A list of all entries in the directory.
function os.listDirectory(path) end
---Create a directory if it does not already exist.
---@param path string The path of the directory.
---@return boolean created Whether the directory was created.
function os.createDirectory(path) end
|
require 'SRC.strict'
-- define some convenience functions
function get_point_by_name (container, name)
for key, value in ipairs(container) do
if value["name"] == name then
value["coordinates"] = value["point"]
return value
end
end
print('container does not contain point with name: ', name)
end
function get_sphere_inertia (mass, radius)
local val
val = 2.0/5.0 * mass * radius * radius
return {
{val, 0.0, 0.0},
{0.0, val, 0.0},
{0.0, 0.0, val}
}
end
function get_box_inertia (mass, width, height, depth)
local valx, valy, valz
valx = 1.0/12.0 * mass * (height*height + depth*depth)
valy = 1.0/12.0 * mass * (width*width + height*height)
valz = 1.0/12.0 * mass * (width*width + depth*depth)
return {
{valx, 0.0, 0.0},
{ 0.0, valy, 0.0},
{ 0.0, 0.0, valz}
}
end
-- define some constants
cart_w = 0.50 -- x-axis
cart_d = 0.20 -- y-axis
cart_h = 0.20 -- z-axis
cart_m = 10.0
cart_com = {
0.0, 0.0, 0.0---cart_h/4.0
}
pend_l = 0.5
pend_r = 0.1
pend_m = 1.0
pend_com = {
0.0, 0.0, pend_l
}
-- build model
bodies = {
cart = {mass = cart_m, com = cart_com, inertia = get_box_inertia(cart_m, cart_w, cart_h, cart_d)},
pendulum = {mass = pend_m, com = pend_com, inertia = get_sphere_inertia(pend_m, pend_r)},
}
meshes = {
cart = {
name = "cart",
dimensions = {cart_w, cart_d, cart_h},
color = {0.0, 1.0, 0.0},
mesh_center = {0, 0, 0},
translate = {0, 0, 0},
rotate = {0.0, 0.0, 0.0},
src = "meshes/unit_cube.obj",
},
cart_com = {
name = "cart_com",
dimensions = {0.05, 0.05, 0.05},
color = {0.0, 0.0, 0.0},
mesh_center = cart_com,
translate = {0, 0, 0},
rotate = {0.0, 0.0, 0.0},
src = "meshes/unit_cube.obj",
},
link = {
name = "link",
dimensions = {0.02, 0.02, pend_l},
color = {0.5, 0.5, 0.0},
mesh_center = {0, 0, 0},
translate = {0, 0, pend_l/2.0},
rotate = {0.0, 0.0, 0.0},
src = "meshes/unit_cube.obj",
},
pendulum = {
name = "pendulum",
dimensions = {pend_r, pend_r, pend_r},
color = {1.0, 0.0, 0.0},
mesh_center = {0, 0, 0},
translate = {0, 0, pend_l},
rotate = {0.0, 0.0, 0.0},
src = "meshes/unit_sphere_medres.obj",
},
pend_com = {
name = "pend_com",
dimensions = {0.05, 0.05, 0.05},
color = {0.0, 0.0, 0.0},
mesh_center = pend_com,
translate = {0, 0, 0},
rotate = {0.0, 0.0, 0.0},
src = "meshes/unit_cube.obj",
},
}
joints = {
fixed = {},
trans_x = {
{ 0., 0., 0., 1., 0., 0.},
},
rot_y = {
{ 0., 1., 0., 0., 0., 0.},
},
base = {
{ 0., 0., 0., 1., 0., 0.},
{ 0., 0., 0., 0., 0., 1.},
{ 0., 1., 0., 0., 0., 0.},
},
}
contact_points = {
{name = "mass", point = {0., 0., pend_l}, body = "pendulum",},
}
model = {
gravity = { 0., 0., -9.81},
configuration = {
axis_front = { 1., 0., 0.},
axis_right = { 0., -1., 0.},
axis_up = { 0., 0., 1.}
},
points = contact_points,
frames = {
-- free flyer cart
{
name = "cart",
parent = "ROOT",
body = bodies.cart,
joint = joints.trans_x,
joint_frame = {
r = {0.0, 0.0, 0.0},
E = {
{1.0, 0.0, 0.0},
{0.0, 1.0, 0.0},
{0.0, 0.0, 1.0},
}
},
visuals = {
meshes.cart,
meshes.cart_com,
}
},
-- unactuated pendulum
{
name = "pendulum",
parent = "cart",
body = bodies.pendulum,
joint = joints.rot_y,
joint_frame = {
r = {0.0, 0.0, 0.0},
E = {
{1.0, 0.0, 0.0},
{0.0, 1.0, 0.0},
{0.0, 0.0, 1.0},
}
},
visuals = {
meshes.pendulum,
meshes.pend_com,
meshes.link,
}
},
-- dummy frame for curve plotting
{
name = "pendulum_com",
parent = "pendulum",
joint = joints.fixed,
joint_frame = {
r = pend_com,
E = {
{1.0, 0.0, 0.0},
{0.0, 1.0, 0.0},
{0.0, 0.0, 1.0},
}
},
point = get_point_by_name(contact_points, "mass"),
visuals = {
},
},
}
}
return model
|
local GUI = require("GUI")
local internet = require("Internet")
local system = require("System")
local filesystem = require("Filesystem")
local image = require("Image")
local color = require("Color")
local screen = require("Screen")
local paths = require("Paths")
local text = require("Text")
local keyboard = require("Keyboard")
local args, options = system.parseArguments(...)
--------------------------------------------------------------------
local recentColorsLimit = 52
local recentFilesLimit = 10
local config = {
recentColors = {},
recentFiles = {},
transparencyBackground = 0xFFFFFF,
transparencyForeground = 0xD2D2D2,
}
local locale = system.getCurrentScriptLocalization()
local currentScriptDirectory = filesystem.path(system.getCurrentScript())
local toolsPath = currentScriptDirectory .. "Tools/"
local configPath = paths.user.applicationData .. "Picture Edit/Config2.cfg"
local savePath
local saveItem
local tool
local workspace, window, menu = system.addWindow(GUI.filledWindow(1, 1, 125, 37, 0x1E1E1E))
--------------------------------------------------------------------
window.newInput = function(...)
return GUI.input(1, 1, 1, 1, 0x1E1E1E, 0xC3C3C3, 0x5A5A5A, 0x1E1E1E, 0xD2D2D2, ...)
end
window.newSlider = function(...)
local slider = GUI.slider(1, 1, 1, 0x66DB80, 0x1E1E1E, 0xE1E1E1, 0x878787, ...)
slider.roundValues = true
return slider
end
window.newSwitch = function(...)
return GUI.switchAndLabel(1, 1, 1, 6, 0x66DB80, 0x1E1E1E, 0xE1E1E1, 0x878787, ...)
end
window.newButton1 = function(...)
return GUI.roundedButton(1, 1, 36, 1, 0xE1E1E1, 0x4B4B4B, 0x4B4B4B, 0xE1E1E1, ...)
end
window.newButton2 = function(...)
local button = GUI.roundedButton(1, 1, 36, 1, 0x4B4B4B, 0xE1E1E1, 0x2D2D2D, 0xE1E1E1, ...)
button.colors.disabled.background, button.colors.disabled.text = 0x4B4B4B, 0x787878
return button
end
--------------------------------------------------------------------
local function saveConfig()
filesystem.writeTable(configPath, config)
end
local function loadConfig()
if filesystem.exists(configPath) then
config = filesystem.readTable(configPath)
else
local perLine = 13
local value, step = 0, 360 / (recentColorsLimit - perLine)
for i = 1, recentColorsLimit - perLine do
table.insert(config.recentColors, color.HSBToInteger(value, 1, 1))
value = value + step
end
value, step = 0, 255 / perLine
for i = 1, perLine do
table.insert(config.recentColors, color.RGBToInteger(math.floor(value), math.floor(value), math.floor(value)))
value = value + step
end
saveConfig()
end
end
local function addRecentFile(path)
for i = 1, #config.recentFiles do
if config.recentFiles[i] == path then
return
end
end
table.insert(config.recentFiles, 1, path)
if #config.recentFiles > recentFilesLimit then
table.remove(config.recentFiles, #config.recentFiles)
end
saveConfig()
end
loadConfig()
local function addTitle(container, text)
local titleContainer = container:addChild(GUI.container(1, 1, container.width, 1))
titleContainer:addChild(GUI.panel(1, 1, titleContainer.width, 1, 0x1E1E1E))
titleContainer:addChild(GUI.text(2, 1, 0xD2D2D2, text))
return titleContainer
end
window.image = window:addChild(GUI.object(1, 1, 1, 1))
window.image.data = {}
window.sidebarPanel = window:addChild(GUI.panel(1, 1, 28, 1, 0x2D2D2D))
window.sidebarLayout = window:addChild(GUI.layout(1, 1, window.sidebarPanel.width, 1, 1, 1))
window.sidebarLayout:setAlignment(1, 1, GUI.ALIGNMENT_HORIZONTAL_CENTER, GUI.ALIGNMENT_VERTICAL_TOP)
window.sidebarLayout.eventHandler = function(workspace, object, e1, e2, e3, e4, e5)
if e1 == "scroll" then
local h, v = window.sidebarLayout:getMargin(1, 1)
local from = 0
local to = -window.sidebarLayout.cells[1][1].childrenHeight + 2
v = v + (e5 > 0 and 2 or -2)
if v > from then
v = from
elseif v < to then
v = to
end
window.sidebarLayout:setMargin(1, 1, h, v)
end
end
addTitle(window.sidebarLayout, locale.recentColors)
local recentColorsContainer = window.sidebarLayout:addChild(GUI.container(1, 1, window.sidebarLayout.width - 2, 4))
local x, y = 1, 1
for i = 1, #config.recentColors do
local button = recentColorsContainer:addChild(GUI.button(x, y, 2, 1, 0x0, 0x0, 0x0, 0x0, " "))
button.onTouch = function()
window.primaryColorSelector.color = config.recentColors[i]
end
x = x + 2
if x > recentColorsContainer.width - 1 then
x, y = 1, y + 1
end
end
local currentToolTitle = addTitle(window.sidebarLayout, locale.toolProperties)
window.currentToolLayout = window.sidebarLayout:addChild(GUI.layout(1, 1, window.sidebarLayout.width, 1, 1, 1))
window.currentToolLayout:setAlignment(1, 1, GUI.ALIGNMENT_HORIZONTAL_CENTER, GUI.ALIGNMENT_VERTICAL_TOP)
window.currentToolLayout:setFitting(1, 1, true, false, 2, 0)
local aboutToolTitle = addTitle(window.sidebarLayout, locale.aboutTool)
local aboutToolTextBox = window.sidebarLayout:addChild(GUI.textBox(1, 1, window.sidebarLayout.width - 2, 1, nil, 0x787878, {}, 1, 0, 0))
window.toolsList = window:addChild(GUI.list(1, 1, 7, 1, 3, 0, 0x2D2D2D, 0x787878, 0x2D2D2D, 0x787878, 0x3C3C3C, 0xE1E1E1))
window.toolsList:setMargin(0, 3)
local function onToolTouch(index)
tool = window.toolsList:getItem(index).tool
window.toolsList.selectedItem = index
window.currentToolOverlay:removeChildren()
window.currentToolLayout:removeChildren()
currentToolTitle.hidden = not tool.onSelection
window.currentToolLayout.hidden = currentToolTitle.hidden
window.sidebarLayout:setMargin(1, 1, 0, 0)
if tool.onSelection then
local result, reason = pcall(tool.onSelection)
if result then
window.currentToolLayout:update()
local lastChild = window.currentToolLayout.children[#window.currentToolLayout.children]
if lastChild then
window.currentToolLayout.height = lastChild.localY + lastChild.height - 1
end
else
GUI.alert(reason)
end
end
aboutToolTitle.hidden = not tool.about
aboutToolTextBox.hidden = aboutToolTitle.hidden
if tool.about then
aboutToolTextBox.lines = text.wrap({tool.about}, aboutToolTextBox.width)
aboutToolTextBox.height = #aboutToolTextBox.lines
end
end
local tools = filesystem.list(toolsPath)
for i = 1, #tools do
if filesystem.extension(tools[i]) == ".lua" then
local result, reason = loadfile(toolsPath .. tools[i])
if result then
result, reason = pcall(result, workspace, window, menu, locale)
if result then
local item = window.toolsList:addItem(reason.shortcut)
item.tool = reason
item.onTouch = function()
onToolTouch(i)
end
else
error("Failed to perform pcall() on tool " .. tools[i] .. ": " .. reason)
end
else
error("Failed to perform loadfile() on tool " .. tools[i] .. ": " .. reason)
end
end
end
window.image.draw = function(object)
GUI.drawShadow(object.x, object.y, object.width, object.height, nil, true)
local y, text = object.y + object.height + 1, locale.size .. object.width .. "x" .. object.height
screen.drawText(math.floor(object.x + object.width / 2 - unicode.len(text) / 2), y, 0x5A5A5A, text)
if savePath then
text = locale.path .. savePath
screen.drawText(math.floor(object.x + object.width / 2 - unicode.len(text) / 2), y + 1, 0x5A5A5A, text)
end
local x, y, step, notStep, background, foreground, symbol = object.x, object.y, false, window.image.width % 2
for i = 3, #window.image.data, 4 do
if window.image.data[i + 2] == 0 then
background = window.image.data[i]
foreground = window.image.data[i + 1]
symbol = window.image.data[i + 3]
elseif window.image.data[i + 2] < 1 then
background = color.blend(config.transparencyBackground, window.image.data[i], window.image.data[i + 2])
foreground = window.image.data[i + 1]
symbol = window.image.data[i + 3]
else
if window.image.data[i + 3] == " " then
background = config.transparencyBackground
foreground = config.transparencyForeground
symbol = step and "▒" or "░"
else
background = config.transparencyBackground
foreground = window.image.data[i + 1]
symbol = window.image.data[i + 3]
end
end
screen.set(x, y, background, foreground, symbol)
x, step = x + 1, not step
if x > object.x + object.width - 1 then
x, y = object.x, y + 1
if notStep == 0 then
step = not step
end
end
end
end
local function updateRecentColorsButtons()
for i = 1, #config.recentColors do
recentColorsContainer.children[i].colors.default.background = config.recentColors[i]
recentColorsContainer.children[i].colors.pressed.background = 0xFFFFFF - config.recentColors[i]
end
end
local function swapColors()
window.primaryColorSelector.color, window.secondaryColorSelector.color = window.secondaryColorSelector.color, window.primaryColorSelector.color
end
local function colorSelectorDraw(object)
screen.drawRectangle(object.x + 1, object.y, object.width - 2, object.height, object.color, 0x0, " ")
for y = object.y, object.y + object.height - 1 do
screen.drawText(object.x, y, object.color, "⢸")
screen.drawText(object.x + object.width - 1, y, object.color, "⡇")
end
end
window.secondaryColorSelector = window:addChild(GUI.colorSelector(3, 1, 5, 2, 0xFFFFFF, " "))
window.primaryColorSelector = window:addChild(GUI.colorSelector(2, 1, 5, 2, 0x000000, " "))
window.secondaryColorSelector.draw, window.primaryColorSelector.draw = colorSelectorDraw, colorSelectorDraw
window.swapColorsButton = window:addChild(GUI.button(1, 1, window.toolsList.width, 1, nil, 0x696969, nil, 0xA5A5A5, " ←→"))
window.swapColorsButton.onTouch = swapColors
local function setSavePath(path)
savePath, saveItem.disabled = path, path == nil
end
local function loadImage(path)
local result, reason
if filesystem.extension(path) == ".txt" then
result = image.fromString(filesystem.read(path))
else
result, reason = image.load(path)
end
if result then
setSavePath(path)
addRecentFile(path)
window.image.data = result
else
GUI.alert(reason)
end
end
local function save(path)
if filesystem.extension(path) == ".pic" then
local result, reason = image.save(path, window.image.data, 7)
if result then
setSavePath(path)
addRecentFile(path)
else
GUI.alert(reason)
end
else
setSavePath(path)
filesystem.write(path, image.toString(window.image.data))
end
computer.pushSignal("system", "updateFileList")
end
local function saveAs()
local filesystemDialog = GUI.addFilesystemDialog(workspace, true, 50, math.floor(window.height * 0.8), locale.save, locale.cancel, locale.fileName, "/")
filesystemDialog:setMode(GUI.IO_MODE_SAVE, GUI.IO_MODE_FILE)
filesystemDialog:addExtensionFilter(".pic")
filesystemDialog:addExtensionFilter(".txt")
filesystemDialog:expandPath(paths.user.desktop)
filesystemDialog.filesystemTree.selectedItem = paths.user.desktop
filesystemDialog:show()
filesystemDialog.onSubmit = function(path)
save(path)
end
end
local function newNoGUI(width, height, path)
setSavePath(path)
window.image.data = {width, height}
for i = 1, width * height do
table.insert(window.image.data, 0x0)
table.insert(window.image.data, 0x0)
table.insert(window.image.data, 1)
table.insert(window.image.data, " ")
end
end
local function new()
local container = GUI.addBackgroundContainer(workspace, true, true, locale.newPicture)
container.panel.eventHandler = nil
local layout = container.layout:addChild(GUI.layout(1, 1, 36, 3, 1, 1))
layout:setDirection(1, 1, GUI.DIRECTION_HORIZONTAL)
layout:setSpacing(1, 1, 0)
local function addInput(...)
return layout:addChild(GUI.input(1, 1, 36, 3, 0xE1E1E1, 0x696969, 0x969696, 0xE1E1E1, 0x2D2D2D, ...))
end
local widthInput = addInput("", locale.width)
layout:addChild(GUI.text(1, 1, 0x696969, " x "))
local heightInput = addInput("", locale.height)
widthInput.width, heightInput.width = 16, 17
container.layout:addChild(GUI.button(1, 1, 30, 3, 0xFFFFFF, 0x555555, 0x880000, 0xFFFFFF, locale.ok)).onTouch = function()
if
widthInput.text:match("%d+") and
heightInput.text:match("%d+")
then
newNoGUI(tonumber(widthInput.text), tonumber(heightInput.text), nil)
window.image.reposition()
end
container:remove()
end
container.layout:addChild(GUI.button(1, 1, 30, 3, 0xFFFFFF, 0x555555, 0x880000, 0xFFFFFF, locale.cancel)).onTouch = function()
container:remove()
end
end
local function open()
local filesystemDialog = GUI.addFilesystemDialog(workspace, true, 50, math.floor(window.height * 0.8), locale.open, locale.cancel, locale.fileName, "/")
filesystemDialog:setMode(GUI.IO_MODE_OPEN, GUI.IO_MODE_FILE)
filesystemDialog:addExtensionFilter(".pic")
filesystemDialog:addExtensionFilter(".txt")
filesystemDialog:expandPath(paths.user.desktop)
filesystemDialog:show()
filesystemDialog.onSubmit = function(path)
loadImage(path)
window.image.reposition()
end
end
window.image.eventHandler = function(workspace, object, e1, e2, e3, e4, ...)
if e1 == "key_down" then
-- D
if e4 == 32 then
window.primaryColorSelector.color, window.secondaryColorSelector.color = 0x0, 0xFFFFFF
workspace:draw()
-- X
elseif e4 == 45 then
swapColors()
elseif keyboard.isControlDown() or keyboard.isCommandDown() then
-- S
if e4 == 31 then
if keyboard.isShiftDown() then
saveAs()
elseif not saveItem.disabled then
save(savePath)
end
-- N
elseif e4 == 49 then
new()
-- O
elseif e4 == 24 then
open()
end
else
for i = 1, window.toolsList:count() do
if e4 == window.toolsList:getItem(i).tool.keyCode then
onToolTouch(i)
return
end
end
end
end
local result, reason = pcall(tool.eventHandler, workspace, object, e1, e2, e3, e4, ...)
if not result then
GUI.alert("Tool eventHandler() failed: " .. reason)
end
end
window.image.setPosition = function(x, y)
window.image.localX = x
window.image.localY = y
window.currentToolOverlay.localX = x
window.currentToolOverlay.localY = y
end
window.image.reposition = function()
window.image.width = window.image.data[1]
window.image.height = window.image.data[2]
window.currentToolOverlay.width = window.image.width
window.currentToolOverlay.height = window.image.height
if window.image.width < window.backgroundPanel.width then
window.image.setPosition(
math.floor(window.backgroundPanel.localX + window.backgroundPanel.width / 2 - window.image.width / 2),
math.floor(window.backgroundPanel.localY + window.backgroundPanel.height / 2 - window.image.height / 2)
)
else
window.image.setPosition(
window.backgroundPanel.localX,
window.backgroundPanel.localY
)
end
end
local fileItem = menu:addContextMenuItem(locale.file)
fileItem:addItem(locale.new, false, "^N").onTouch = new
fileItem:addSeparator()
fileItem:addItem(locale.open, false, "^O").onTouch = open
local fileItemSubMenu = fileItem:addSubMenuItem(locale.openRecent, #config.recentFiles == 0)
for i = 1, #config.recentFiles do
fileItemSubMenu:addItem(text.limit(config.recentFiles[i], 32, "left")).onTouch = function()
loadImage(config.recentFiles[i])
window.image.reposition()
end
end
fileItem:addItem(locale.openFromURL).onTouch = function()
local container = GUI.addBackgroundContainer(workspace, true, true, locale.openFromURL)
container.panel.eventHandler = nil
local input = container.layout:addChild(GUI.input(1, 1, 36, 3, 0xE1E1E1, 0x696969, 0x969696, 0xE1E1E1, 0x2D2D2D, "", "http://example.com/test.pic"))
local okBut = container.layout:addChild(GUI.button(1, 1, 30, 3, 0xFFFFFF, 0x555555, 0x880000, 0xFFFFFF, locale.ok))
local cancelBut = container.layout:addChild(GUI.button(1, 1, 30, 3, 0xFFFFFF, 0x555555, 0x880000, 0xFFFFFF, locale.cancel))
okBut.onTouch = function()
if #input.text > 0 then
input:remove()
okBut:remove()
cancelBut:remove()
container.layout:addChild(GUI.label(1, 1, container.width, 1, 0x969696, locale.downloading):setAlignment(GUI.ALIGNMENT_HORIZONTAL_CENTER, GUI.ALIGNMENT_VERTICAL_TOP))
workspace:draw()
local temporaryPath = system.getTemporaryPath() .. ".pic"
local result, reason = internet.download(input.text, temporaryPath)
container:remove()
if result then
loadImage(temporaryPath)
window.image.reposition()
filesystem.remove(temporaryPath)
setSavePath(nil)
else
GUI.alert(reason)
end
else
container:remove()
end
end
cancelBut.onTouch = function()
container:remove()
end
end
fileItem:addSeparator()
saveItem = fileItem:addItem(locale.save, false, "^S")
saveItem.onTouch = function()
save(savePath)
end
fileItem:addItem(locale.saveAs, false, "^⇧S").onTouch = saveAs
menu:addItem(locale.view).onTouch = function()
local container = GUI.addBackgroundContainer(workspace, true, true, locale.view)
container.panel.eventHandler = nil
local colorSelector1 = container.layout:addChild(GUI.colorSelector(1, 1, 36, 3, config.transparencyBackground, locale.transBack))
local colorSelector2 = container.layout:addChild(GUI.colorSelector(1, 1, 36, 3, config.transparencyForeground, locale.transFor))
container.layout:addChild(GUI.button(1, 1, 30, 3, 0xFFFFFF, 0x555555, 0x880000, 0xFFFFFF, locale.ok)).onTouch = function()
config.transparencyBackground, config.transparencyForeground = colorSelector1.color, colorSelector2.color
container:remove()
saveConfig()
end
container.layout:addChild(GUI.button(1, 1, 30, 3, 0xFFFFFF, 0x555555, 0x880000, 0xFFFFFF, locale.cancel)).onTouch = function()
container:remove()
end
end
local imageItem = menu:addContextMenuItem(locale.image)
imageItem:addItem(locale.flipVertical).onTouch = function()
window.image.data = image.flipVertically(window.image.data)
end
imageItem:addItem(locale.flipHorizontal).onTouch = function()
window.image.data = image.flipHorizontally(window.image.data)
end
imageItem:addSeparator()
imageItem:addItem(locale.rotate90).onTouch = function()
window.image.data = image.rotate(window.image.data, 90)
window.image.width = window.image.data[1]
window.image.height = window.image.data[2]
window.image.reposition()
end
imageItem:addItem(locale.rotate180).onTouch = function()
window.image.data = image.rotate(window.image.data, 180)
window.image.width = window.image.data[1]
window.image.height = window.image.data[2]
window.image.reposition()
end
imageItem:addItem(locale.rotate270).onTouch = function()
window.image.data = image.rotate(window.image.data, 270)
window.image.width = window.image.data[1]
window.image.height = window.image.data[2]
window.image.reposition()
end
local editItem = menu:addContextMenuItem(locale.edit)
editItem:addItem(locale.hueSaturation).onTouch = function()
local container = GUI.addBackgroundContainer(workspace, true, true, locale.hueSaturation)
container.layout:setSpacing(1, 1, 2)
container.panel.eventHandler = nil
local hue = container.layout:addChild(GUI.slider(1, 1, 50, 0x66DB80, 0x0, 0xFFFFFF, 0xAAAAAA, -360, 360, 0, true, locale.hue))
local satur = container.layout:addChild(GUI.slider(1, 1, 50, 0x66DB80, 0x0, 0xFFFFFF, 0xAAAAAA, -100, 100, 0, true, locale.saturation))
local bright = container.layout:addChild(GUI.slider(1, 1, 50, 0x66DB80, 0x0, 0xFFFFFF, 0xAAAAAA, -100, 100, 0, true, locale.brightness))
hue.roundValues = true
satur.roundValues = true
bright.roundValues = true
local buttonsLay = container.layout:addChild(GUI.layout(1, 1, 30, 7, 1, 1))
buttonsLay:addChild(GUI.button(1, 1, 30, 3, 0xFFFFFF, 0x555555, 0x880000, 0xFFFFFF, locale.ok)).onTouch = function()
window.image.data = image.hueSaturationBrightness(window.image.data, hue.value, satur.value/100, bright.value/100)
container:remove()
end
buttonsLay:addChild(GUI.button(1, 1, 30, 3, 0xFFFFFF, 0x555555, 0x880000, 0xFFFFFF, locale.cancel)).onTouch = function()
container:remove()
end
end
editItem:addItem(locale.colorBalance).onTouch = function()
local container = GUI.addBackgroundContainer(workspace, true, true, locale.colorBalance)
container.layout:setSpacing(1, 1, 2)
container.panel.eventHandler = nil
local r = container.layout:addChild(GUI.slider(1, 1, 50, 0x66DB80, 0x0, 0xFF0000, 0xAAAAAA, -255, 255, 0, true, "R: "))
local g = container.layout:addChild(GUI.slider(1, 1, 50, 0x66DB80, 0x0, 0x00FF00, 0xAAAAAA, -255, 255, 0, true, "G: "))
local b = container.layout:addChild(GUI.slider(1, 1, 50, 0x66DB80, 0x0, 0x0000FF, 0xAAAAAA, -255, 255, 0, true, "B: "))
r.roundValues = true
g.roundValues = true
b.roundValues = true
local buttonsLay = container.layout:addChild(GUI.layout(1, 1, 30, 7, 1, 1))
buttonsLay:addChild(GUI.button(1, 1, 30, 3, 0xFFFFFF, 0x555555, 0x880000, 0xFFFFFF, locale.ok)).onTouch = function()
window.image.data = image.colorBalance(window.image.data, math.floor(r.value), math.floor(g.value), math.floor(b.value))
container:remove()
end
buttonsLay:addChild(GUI.button(1, 1, 30, 3, 0xFFFFFF, 0x555555, 0x880000, 0xFFFFFF, locale.cancel)).onTouch = function()
container:remove()
end
end
editItem:addItem(locale.photoFilter).onTouch = function()
local container = GUI.addBackgroundContainer(workspace, true, true, locale.photoFilter)
container.layout:setSpacing(1, 1, 2)
container.panel.eventHandler = nil
local filterColor = container.layout:addChild(GUI.colorSelector(1, 1, 30, 3, 0x333333, locale.filterColor))
local transparency = container.layout:addChild(GUI.slider(1, 1, 50, 0x66DB80, 0x0, 0xFFFFFF, 0xAAAAAA, 0, 1, 0.5, true, locale.transparency))
local buttonsLay = container.layout:addChild(GUI.layout(1, 1, 30, 7, 1, 1))
buttonsLay:addChild(GUI.button(1, 1, 30, 3, 0xFFFFFF, 0x555555, 0x880000, 0xFFFFFF, locale.ok)).onTouch = function()
window.image.data = image.blend(window.image.data, filterColor.color, transparency.value)
container:remove()
end
buttonsLay:addChild(GUI.button(1, 1, 30, 3, 0xFFFFFF, 0x555555, 0x880000, 0xFFFFFF, locale.cancel)).onTouch = function()
container:remove()
end
end
editItem:addSeparator()
editItem:addItem(locale.invertColors).onTouch = function()
window.image.data = image.invert(window.image.data)
end
editItem:addItem(locale.blackWhite).onTouch = function()
window.image.data = image.blackAndWhite(window.image.data)
end
editItem:addSeparator()
editItem:addItem(locale.gaussianBlur).onTouch = function()
local container = GUI.addBackgroundContainer(workspace, true, true, locale.gaussianBlur)
container.panel.eventHandler = nil
local radius = container.layout:addChild(GUI.slider(1, 1, 50, 0x66DB80, 0x0, 0xFFFFFF, 0xAAAAAA, 1, 10, 2, true, locale.radius))
radius.height = 2
radius.roundValues = true
local force = container.layout:addChild(GUI.slider(1, 1, 50, 0x66DB80, 0x0, 0xFFFFFF, 0xAAAAAA, 0, 1, 0.5, true, locale.force))
force.height = 2
container.layout:addChild(GUI.button(1, 1, 30, 3, 0xFFFFFF, 0x555555, 0x880000, 0xFFFFFF, locale.ok)).onTouch = function()
window.image.data = image.convolve(window.image.data, image.getGaussianBlurKernel(math.floor(radius.value), force.value))
container:remove()
end
container.layout:addChild(GUI.button(1, 1, 30, 3, 0xFFFFFF, 0x555555, 0x880000, 0xFFFFFF, locale.cancel)).onTouch = function()
container:remove()
end
end
menu:addItem(locale.hotkeys).onTouch = function()
local container = GUI.addBackgroundContainer(workspace, true, true, locale.hotkeys)
container.layout:addChild(GUI.textBox(1, 1, 36, 1, nil, 0x969696, locale.hotkeysText, 1, 0, 0, true, true)).eventHandler = nil
end
window.currentToolOverlay = window:addChild(GUI.container(1, 1, 1, 1))
window.onResize = function(width, height)
window.backgroundPanel.localX = window.toolsList.width + 1
window.backgroundPanel.width = width - window.sidebarLayout.width - window.toolsList.width
window.backgroundPanel.height = height
window.sidebarPanel.localX = window.width - window.sidebarPanel.width + 1
window.sidebarPanel.height = height
window.sidebarLayout.localX = window.sidebarPanel.localX
window.sidebarLayout.height = height
window.toolsList.height = height
window.secondaryColorSelector.localY = height - 4
window.primaryColorSelector.localY = height - 5
window.swapColorsButton.localY = height - 1
window.image.reposition()
end
----------------------------------------------------------------
window.actionButtons:moveToFront()
updateRecentColorsButtons()
if (options.o or options.open) and args[1] then
if filesystem.exists(args[1]) then
loadImage(args[1])
elseif options.n and args[2] and args[3] then
newNoGUI(args[2], args[3], args[1])
else
newNoGUI(50, 20, nil)
end
else
newNoGUI(50, 20, nil)
end
window:resize(window.width, window.height)
onToolTouch(5)
|
local helpers = require "spec.helpers"
local cjson = require "cjson"
describe("Resolver", function()
local admin_client
setup(function()
assert(helpers.start_kong({
custom_plugins = "database-cache",
lua_package_path = "?/init.lua;./kong/?.lua;./spec/fixtures/?.lua"
}))
admin_client = helpers.admin_client()
assert(helpers.dao.apis:insert {
request_host = "mockbin.com",
upstream_url = "http://mockbin.com"
})
local res = assert(admin_client:send {
method = "POST",
path = "/apis/mockbin.com/plugins/",
body = {
name = "database-cache"
},
headers = {
["Content-Type"] = "application/json"
}
})
assert.res_status(201, res)
end)
teardown(function()
if admin_client then admin_client:close() end
helpers.stop_kong()
end)
it("avoids dog-pile effect", function()
local function make_request(premature, sleep_time)
local client = helpers.proxy_client()
assert(client:send {
method = "GET",
path = "/status/200?sleep="..sleep_time,
headers = {
["Host"] = "mockbin.com"
}
})
client:close()
end
assert(ngx.timer.at(0, make_request, 2))
assert(ngx.timer.at(0, make_request, 5))
assert(ngx.timer.at(0, make_request, 1))
helpers.wait_until(function()
local res = assert(admin_client:send {
method = "GET",
path = "/cache/invocations"
})
local body = assert.res_status(200, res)
return cjson.decode(body).message == 3
end, 10)
-- Invocation are 3, but lookups should be 1
local res = assert(admin_client:send {
method = "GET",
path = "/cache/lookups"
})
local body = assert.res_status(200, res)
assert.equal(1, cjson.decode(body).message)
ngx.sleep(1) -- block to allow timers requests to finish
end)
end)
|
--元灵的后续·Monosu
local m=37564052
local cm=_G["c"..m]
xpcall(function() require("expansions/script/c37564765") end,function() require("script/c37564765") end)
cm.Senya_name_with_elem=true
function cm.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,nil,4,2,nil,nil,63)
c:EnableReviveLimit()
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(m,0))
e1:SetCategory(CATEGORY_DRAW)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1,m)
e1:SetCost(cm.cost)
e1:SetTarget(cm.tg)
e1:SetOperation(cm.op)
c:RegisterEffect(e1)
end
function cm.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function cm.tg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(1)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function cm.op(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
if Duel.Draw(p,d,REASON_EFFECT)>0 then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetCountLimit(1)
e1:SetOperation(cm.rmop2)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
end
function cm.rmop2(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,Card.IsAbleToRemove,tp,LOCATION_HAND,0,1,1,nil)
Duel.Remove(g,POS_FACEUP,REASON_EFFECT)
end
|
return {'pentagon','pentateuch','pen','penaal','penaliseren','penaliteit','penalty','penaltystip','penant','penantkastje','penantspiegel','penanttafel','penarie','penaten','pendag','pendant','pendel','pendelaar','pendelbeweging','pendelbus','pendeldienst','pendeldiplomatie','pendelen','pendeloque','pendeltrein','pendelverkeer','pendule','pene','penetrant','penetratie','penetratiegraad','penetreren','pengat','penhouder','penhoudergreep','penibel','penicilline','penis','peniskoker','penisnijd','penitent','penitentiair','penitentie','pennen','pennenbak','pennendoos','pennenhouder','pennenkoker','pennenlikker','pennenmes','pennenproef','pennenschacht','pennenstreek','pennenstrijd','pennentrek','pennenvrucht','pennenzak','penner','penning','penningkabinet','penningkruid','penningkunde','penningkunst','penningmeester','penningmeesteresse','penningmeesterschap','penningsnijder','pennoen','penny','penologie','penopauze','penoze','pens','pensee','penseel','penseelstreek','penseeltrek','penseelvoering','penselen','pensenkermis','penserij','pensioen','pensioenaanspraak','pensioenaanvraag','pensioenaanvrage','pensioenaanvulling','pensioenbedrag','pensioenbeleid','pensioenberekening','pensioenbijdrage','pensioenbreuk','pensioendatum','pensioendeskundige','pensioendossier','pensioenfonds','pensioengat','pensioengebied','pensioengeld','pensioengerechtigd','pensioengerechtigde','pensioengrondslag','pensioenhervorming','pensioeninkomen','pensioeninstelling','pensioenkapitaal','pensioenkas','pensioenkorting','pensioenkosten','pensioenland','pensioenlast','pensioenleeftijd','pensioenmaatschappij','pensioenmarkt','pensioenopbouw','pensioenpijler','pensioenplan','pensioenplicht','pensioenpot','pensioenpremie','pensioenprobleem','pensioenproblematiek','pensioenrecht','pensioenregeling','pensioenreglement','pensioenreparatie','pensioenreserve','pensioensaanvraag','pensioensaanvrage','pensioensbijdrage','pensioensector','pensioensgrondslag','pensioenskorting','pensioenspaarfonds','pensioensparen','pensioensregeling','pensioenstelsel','pensioensverzekering','pensioensysteem','pensioentekort','pensioentoezegging','pensioentrekkenden','pensioentrekker','pensioenuitkering','pensioenuitvoerder','pensioenverlies','pensioenvermogen','pensioenverweer','pensioenverzekeraar','pensioenverzekering','pensioenverzekeringsovereenkomst','pensioenvoorziening','pensioenwereld','pensioenwet','pensioenwetgeving','pensioenzorgen','pension','pensionaat','pensionado','pensionair','pensionaire','pensionaris','pensionboerderij','pensioneren','pensionering','pensiongast','pensionhouder','pensionhoudster','pensionkosten','pensionnetje','pensionprijs','pensiontehuis','pensjager','penster','pensum','pentaan','pentagonaal','pentagram','pentameter','pentatlon','pentatonisch','pentaeder','pentekening','penter','penterhaak','penthouse','penultima','penurie','penvoerder','penwortel','penningske','pennenstok','pendrive','pennenvoerder','penseelvormig','pensioenverplichting','penisring','pensioenovereenkomst','penisplant','penisvergroting','pennenset','pensioenadvies','pensioenadviseur','pensioenbrief','pensioencontract','pensioencrisis','pensioendekking','pensioenfondsbestuur','pensioenrisico','pensioensituatie','pensioenspaarverzekering','pensioenstaat','pensioentijd','pensioenverevening','pensioenbeheer','pensioneringsleeftijd','pensioenbonus','pensioenschade','pensioenrekening','pensioenplanning','pensioenbewustzijn','pensioensfeer','penningkast','penseelaapje','penghueilanden','pennings','penelope','penny','penders','pennekamp','penners','pennock','penninga','penninx','penninkhof','pennewaard','penris','penale','penaltys','penanten','penantkastjes','penantspiegels','pendanten','pende','pendelde','pendelden','pendeloques','pendelt','penden','pendules','penduletje','penen','penetrante','penetranter','penetrantere','penetraties','penetreer','penetreerde','penetreerden','penetreert','penhouders','penibeler','penitenten','penitentiaire','penitenties','penitentien','pennenbakken','pennend','pennendozen','pennenkokers','penners','pennetje','pennetjes','penningen','penningkabinetten','penningmeesters','penninkje','penninkjes','pennoenen','pennys','penseelde','penseelden','penseelstreken','penseelt','penseeltje','penseeltjes','penseeltrekken','pensees','pensen','pensioenaanspraken','pensioenaanvragen','pensioenadviseurs','pensioenafspraken','pensioenbedragen','pensioenbesparingen','pensioenbetalingen','pensioenbijdragen','pensioenen','pensioenfondsen','pensioengerechtigden','pensioengrondslagen','pensioenhervormingen','pensioenjaren','pensioenkapitalen','pensioenkassen','pensioenkortingen','pensioenlasten','pensioenmaatschappijen','pensioenpremies','pensioenproducten','pensioenrechten','pensioenregelingen','pensioenreglementen','pensioensbijdragen','pensioensgrondslagen','pensioenspaarfondsen','pensioensregelingen','pensioenstelsels','pensioensverzekeringen','pensioensystemen','pensioentekorten','pensioentje','pensioentjes','pensioentoezeggingen','pensioenuitgaven','pensioenuitvoerders','pensioenverplichtingen','pensioenverzekeraars','pensioenverzekeringen','pensioenvoorzieningen','pensioenwetten','pensionados','pensionaires','pensionairs','pensionarissen','pensionaten','pensioneer','pensioneerde','pensioneerden','pensioneert','pensioneringen','pensiongasten','pensionhouders','pensionnetjes','pensionprijzen','pensions','pensjagers','pensums','pentameters','pentekeningen','penters','pentiti','penvoerende','penaliseerde','penanttafels','pendelaars','pendelbewegingen','pendelbussen','pendelende','pendeloquen','pendels','pendeltreinen','penetrerend','penetrerende','pengaten','peniskokers','penissen','pennenhouders','pennenlikkers','pennenmessen','pennenstreken','pennenvruchten','pennenzakken','pensenkermissen','pensioenbreuken','pensioengaten','pensioenplannen','pensioenskortingen','pensioentrekkers','pensioenuitkeringen','pensionairetje','pent','pentatonische','pentaeders','penthouses','penvoerders','penwortels','penibele','penseelvormige','pensioenreserves','pentagonale','pennoentje','penseetje','pensioensaanvragen','pensionairtje','pennentrekken','penthouseje','penhoudergrepen','penduultje','pentagrammen','penaltystippen','pendrives','pennenschachten','pennenstokken','pennenvoerders','penningskes','penopauzes','pensionhoudsters','penelopes','pennys','pensioengelden','pendelbusje','pendelbusjes','pensioencontracten','pensioenfondsbesturen','pensioeninstellingen','pennenbakje','pensioenproblemen','pensioeninkomens','pensioenrisicos','pensioenberekeningen','pensioenvermogens','pensioenpijlers','pensioenleeftijden','pensioenrekeningen','pensioenlanden','pensioendeskundigen','pennenmesje','penisringen','pennenzakje','pennenvruchtje','pennenbakjes','pendeltreintje','pensioenbijdrages'}
|
DefineClass.NetworkNode =
{
__parents = { "SpireBase", "ElectricityConsumer", "Workplace" },
properties = {
{ template = true, category = "Spire", name = T(679, "Performance boost"), id = "performance_boost", editor = "number", default = 20, help = "Performance boost (int percent) to all research buildings in the same dome (for 100% performance of this building)" }
},
modifier = false,
}
function NetworkNode:GameInit()
local boost = MulDivRound(self.performance_boost, self.performance, 100)
self.modifier = LabelModifier:new{
container = self.parent_dome,
label = "BaseResearchLab",
id = "NetworkNode",
prop = "performance",
amount = 0,
percent = boost,
display_text = T{7625, "<green>Network node <amount>%</color>", amount = boost},
}
self.parent_dome:SetLabelModifier("BaseResearchLab", "NetworkNode", self.modifier)
end
function NetworkNode:OnModifiableValueChanged(prop, old_value, new_valaue)
if prop == "performance" and self.modifier then
local boost = MulDivRound(self.performance_boost, new_valaue, 100)
self.modifier:Change(0,boost)
self.modifier.display_text = T{7625, "<green>Network node <amount>%</color>", amount = boost}
end
end
|
function onCreate()
-- background shit
makeLuaSprite('back2', 'back2', -500, -300);
setLuaSpriteScrollFactor('back2', 0.9, 0.9);
scaleObject('back2', 1, 1)
addLuaSprite('back2', false);
makeLuaSprite('back22', 'back2', -500, -300);
setLuaSpriteScrollFactor('back22', 0.9, 0.9);
scaleObject('back22', 1, 1)
addLuaSprite('back22', false);
close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage
end
|
local aabb = require 'aabb'
local boxgen = {}
local function cuts(n) -- helper function for generate
-- calculates how many levels of recursion are required
-- to split a space in n slices
-- (in practice this function is equal to the logarithm of n in base 4)
local sum = 1
local cnum = 0
while sum < n do
sum = sum * 4
cnum = cnum + 1
end
return cnum
end
function boxgen.generateSlices(n, radius) -- generates n non-overlapping random rectangles
-- this function takes the space between -radius and +radius in both axis,
-- and splits this square area recursively using 2 or 1 random cuts into cells.
-- the end result is a table containing n rectangles which can't overlap.
-- note: this function is experimental, there are uncovered cases like "what if I can't split a cell?".
-- use at your own risk!
local cnum = cuts(n)
local tree = aabb.new(-radius, -radius, radius*2, radius*2)
local traverse = { tree }
local clevel, nextlevel = 1, 0
local min_size = 40 -- for my box's sprite
local lost_splits = 0
local rects = 1
while rects < n do
local first = table.remove(traverse, 1)
clevel = clevel - 1
nextlevel = nextlevel + 4
if clevel == 0 then
clevel = nextlevel
nextlevel = 0
cnum = cnum - 1
end
local ahc, avc = math.floor(first.w / min_size), math.floor(first.h / min_size)
if ahc >= 2 and avc >= 2 then
local cutw, cuth = min_size * math.random(math.ceil(ahc * 0.4), math.floor(ahc * 0.6)), min_size * math.random(math.ceil(avc * 0.4), math.floor(avc * 0.6))
local c = n-rects >= 4 and 4 or (n-rects+1)
if c > 2 then
for i = 1, c do
table.insert(traverse, aabb.new(
(i == 1 or i == 3) and first.x or (first.x + cutw),
(i < 3) and first.y or (first.y + cuth),
(i == 1 or i == 3) and cutw or (first.w - cutw),
(i < 3) and cuth or (first.h - cuth)
))
end
else
for i = 1, c do
table.insert(traverse, aabb.new(
(i == 1) and first.x or (first.x + cutw),
first.y,
(i == 1) and cutw or (first.w - cutw),
first.h
))
end
end
rects = rects - 1 + c
else
lost_splits = lost_splits + 1
end
end
--print(lost_splits)
--print(#traverse)
return traverse
end
return boxgen
|
object_tangible_quest_skeleton_ithorian = object_tangible_quest_shared_skeleton_ithorian:new {
}
ObjectTemplates:addTemplate(object_tangible_quest_skeleton_ithorian, "object/tangible/quest/skeleton_ithorian.iff")
|
MazeState = Class{__includes = BaseState}
function MazeState:init()
-- initial data to prevent nil values
self.data = {level = 0,
row = math.random(GRID_LENGTH),
col = math.random(GRID_LENGTH),
tokens = 0}
-- tokens found on current level
self.tokensLevelCount = 0
-- maze generation
self.maze, self.maxTokens = GenerateGrid(self.data.row, self.data.col)
self.maze = carveMaze(self.maze)
-- dafault player
self.player = Player(ROW_OFFSET - WALL_LENGTH / 2, COL_OFFSET - WALL_LENGTH / 2)
end
function MazeState:enter(params)
if (params.playState ~= nil) then
self.playState = params.playState
print("Saved play state")
end
end
function MazeState:update(dt)
-- debugging keycombo
-- if love.keyboard.isDown("=") and love.keyboard.isDown("-") and not DEPLOYED then
-- DEBUGGING = not DEBUGGING
-- -- prevent double click
-- love.timer.sleep(.2)
-- end
-- if love.keyboard.isDown("[") and DEBUGGING then
-- self.data.tokens = self.data.tokens + 1
-- -- prevent double click
-- love.timer.sleep(.2)
-- end
-- updates
self.player:update(dt)
if love.keyboard.isDown("8") and not DEPLOYED then
self.playState:saveFloor()
print(#self.playState.floorChanger.floors)
stateMachine.current = self.playState
end
-- collisions
for i, row in pairs(self.maze) do
for j, col in pairs(self.maze[i]) do
-- next level progression
if self.maze[i][j].hasLadder and self.maze[i][j]:collided(self.player) then
self.playState:saveFloor()
print(#self.playState.floorChanger.floors)
stateMachine.current = self.playState
end
-- token collision and updates
if self.maze[i][j].hasToken and self.maze[i][j]:collided(self.player) then
self.maze[i][j].hasToken = false
self.tokensLevelCount = self.tokensLevelCount + 1
end
-- wall collision
for k, wall in pairs(self.maze[i][j].walls) do
self.player:collidesWithWall(wall, dt)
end
end
end
end
function MazeState:render()
love.graphics.clear(40, 45, 52, 255)
-- renders
self.player:render()
self.maze[ladderX][ladderY]:render()
-- maze sight
if not DEBUGGING then
love.graphics.stencil(function()
love.graphics.circle('fill', self.player.x, self.player.y, 20 * MAZE_SCALE_RATIO)
end, 'replace', 2)
love.graphics.setStencilTest('greater', 1)
end
-- maze render
for i, row in pairs(self.maze) do
for j, col in pairs(self.maze[i]) do
self.maze[i][j]:render()
end
end
love.graphics.setStencilTest()
-- border
love.graphics.rectangle("line", ROW_OFFSET - WALL_LENGTH, COL_OFFSET - WALL_LENGTH, (GRID_LENGTH + 1) * WALL_LENGTH, (GRID_LENGTH + 1) * WALL_LENGTH)
end
|
---@param str string
local function SubstituteString(str, ...)
local args = {...}
local result = str
for k, v in pairs(args) do
if type(v) == "number" and v == math.floor(v) then v = math.floor(v) end -- Formatting integers to not show .0
result = result:gsub("%["..tostring(k).."%]", v)
end
return result
end
---@param dynamicKey string
function GetDynamicTranslationString(dynamicKey, ...)
local args = {...}
local handle = dynamicTooltips[dynamicKey]
if handle == nil then return nil end
local str = Ext.GetTranslatedString(handle, "Handle Error!")
str = SubstituteString(str, table.unpack(args))
return str
end
---@param character EsvCharacter
---@param skill any
---@param tooltip TooltipData
local function TenebriumSkillDisplayRequirement(character, skill, tooltip)
skill = Ext.GetStat(skill)
-- Ext.Print(skill.Name)
if skill.Ability ~= "Source" then return end
local requirementMet = true
for i,element in pairs(tooltip:GetElements("SkillRequiredEquipment")) do
local _,_,amount = string.find(element.Label, "tag SRP_TE(%d+)")
if amount ~= nil then
-- Ext.Print("Requirement not met")
requirementMet = false
element.Label = SubstituteString(Ext.GetTranslatedStringFromKey("TE_Cost"), amount)
end
if skill.Name == "Summon_TEN_FoulWinds" then
for i,element in pairs(tooltip:GetElements("SkillProperties")) do
tooltip:RemoveElement(element)
end
end
end
-- Ext.Dump(tooltip)
-- Ext.Print(requirementMet)
if not requirementMet then return end
for i, requirement in pairs(skill.Requirements) do
if requirement.Requirement == "Tag" then
local _,_,amount = string.find(requirement.Param, "SRP_TE(%d+)") --Ty LaughingLeader
if amount ~= nil then
local element = {
Label = SubstituteString(Ext.GetTranslatedStringFromKey("TE_Cost"), amount),
RequirementMet = true,
Type = "SkillRequiredEquipment"
}
tooltip:AppendElementAfter(element, "SkillRequiredEquipment")
end
end
end
end
local function SRP_InitTenebriumClientListeners()
Game.Tooltip.RegisterListener("Skill", nil, TenebriumSkillDisplayRequirement)
end
Ext.RegisterListener("SessionLoaded", SRP_InitTenebriumClientListeners)
local isTenebriumInfusionTooltip
local isTenebriumEnergyTooltip
--Captures when the characterSheet Light Resistance tooltip is trying to be served to the client and serves the FireResistance tooltip instead.
---@param ui UIObject
---@param call string
---@param statId number
local function ShowTenebriumInfusionTooltip(ui, call, statId, arg, x, y, ...)
if statId == 101.0 then
isTenebriumEnergyTooltip = true
ui:ExternalInterfaceCall("showStatTooltip", 33.0, arg+30, 1500, 500, ...)
end
if statId == 102.0 then
isTenebriumInfusionTooltip = true
ui:ExternalInterfaceCall("showStatTooltip", 33.0, arg+30, 1500, 500, ...)
end
end
---@param character EclCharacter
---@param skill string
---@param tooltip TooltipData
local function OnStatTooltip(character, stat, tooltip)
-- Ext.Print("tooltip", isTenebriumInfusionTooltip)
if tooltip == nil then return end
-- Ext.Dump(tooltip:GetElement("StatName"))
local stat = tooltip:GetElement("StatName").Label
local statsDescription = tooltip:GetElement("StatsDescription")
if stat == "UNKNOWN STAT" and isTenebriumInfusionTooltip then
tooltip:GetElement("StatName").Label = "Tenebrium Infusion"
statsDescription.Label = "How tainted your Source is. The more tainted you are, the more side effects you will encounter."
local ti = CustomStatSystem:GetStatByID("TenebriumInfusion"):GetValue(character)
if ti > 0 then
tooltip:AppendElement({
Type = "StatsPercentageBoost",
Label = "Shadow damages are increased by "..math.floor(ti*Ext.ExtraData.TEN_ShadowDamagePerTi).."%"
})
end
local malus1 ={
Type = "StatsPercentageMalus",
Label = ""
}
local malus2 = {
Type = "StatsPercentageMalus",
Label = ""
}
local bonus1 = {
Type = "StatsPercentageBoost",
Label = ""
}
if ti >= 20 then
local dmg = tostring(math.floor(Game.Math.GetAverageLevelDamage(character.Stats.Level)*0.3))
malus1.Label = "During overcharge:<br> •(20) you receive <font color=#990099>"..dmg.." Shadow damage</font> at the end of your turn."
tooltip:AppendElement(malus1)
bonus1.Label = bonus1.Label.."During overcharge:<br> •(20) Movement speed +35%"
tooltip:AppendElement(bonus1)
malus2.Label = "(20) Sleeping rolls receive a penalty of 2"
tooltip:AppendElement(malus2)
end
if ti >= 40 then
malus1.Label = malus1.Label.."<br> •(40) 15% of damage and healings done are reflected back to you as Shadow damage."
bonus1.Label = bonus1.Label.."<br> •(40) Retribution +3"
malus2.Label = malus2.Label.."<br>(40) Obscura and Aurora +1"
end
if ti >= 60 then
malus1.Label = malus1.Label.."<br> •(60) You cannot recover Physical and Magic armours"
bonus1.Label = bonus1.Label.."<br> •(60) All your damages entirely go through armours and healings provide 20% more temporary health"
malus2.Label = malus2.Label.."<br>(60) You cannot use fortune points"
end
if ti >= 80 then
malus1.Label = malus1.Label.."<br> •(80) Healings are blocked and Death Resist break when reaching 1HP"
bonus1.Label = bonus1.Label.."<br> •(80) You are immune to all kind of crowd control"
malus2.Label = malus2.Label.."<br>(80) You sometimes lose control of your actions"
end
isTenebriumInfusionTooltip = false
elseif stat == "UNKNOWN STAT" and isTenebriumEnergyTooltip then
tooltip:GetElement("StatName").Label = "Tenebrium Energy"
statsDescription.Label = "How active is the Tenebrium Infusion. Increase with missed and resisted attacks, by receiving a critical hit or when being incapacitated. The stronger the infusion is, the more energy it will generate.<br>If the energy grow above the Infusion value you get overcharged, generating side effects. The overcharge can only be triggered during your turn.<br>Reaching the overcharge value, overcharging and starting a turn while being overcharged increase your chances of seeing your Infusion growing at the end of the battle. Spending energy reduces it."
isTenebriumEnergyTooltip = false
end
end
local function SRP_Tooltips_Init()
local charSheet = Ext.GetBuiltinUI("Public/Game/GUI/characterSheet.swf")
Ext.RegisterUICall(charSheet, "showStatTooltip", ShowTenebriumInfusionTooltip)
Game.Tooltip.RegisterListener("Stat", nil, OnStatTooltip)
end
Ext.RegisterListener("SessionLoaded", SRP_Tooltips_Init)
|
local uloop = require("uloop")
-- XXX: for uloop, it is global, so only one uloop_reactor instance
-- can be use.
local uloop_reactor = {}
local __events = {}
uloop.init()
uloop_reactor.register_fd_event = function (fd_event_cb, fd, event)
local new_ev_obj
local events = 0
-- TODO: support regiser both *read* and *write*.
if event == 'read' then
events = events + uloop.ULOOP_READ
elseif event == 'write' then
events = events + uloop.ULOOP_WRITE
else
error("unsupport event or nothing to do")
end
new_ev_obj = uloop.fd_add(fd, fd_event_cb, events)
__events[new_ev_obj] = true
return new_ev_obj
end
uloop_reactor.register_timeout_cb = function (timeout_cb, timeout_interval)
local new_ev_obj
local ti
-- the time unit of uloop is ms, so convert it to second.
ti = math.floor(timeout_interval * 1000)
new_ev_obj = uloop.timer(timeout_cb, ti)
__events[new_ev_obj] = true
return new_ev_obj
end
uloop_reactor.unregister_event = function (ev_obj)
if __events[ev_obj] ~= true then
error("try to unregister unknown event")
end
__events[ev_obj] = nil
-- for timer event, use cancel to unregister it
-- for fd event, use delete to unregister it
if ev_obj.cancel ~= nil then
ev_obj:cancel()
else
ev_obj:delete()
end
end
uloop_reactor.run = function ()
uloop.run()
end
uloop_reactor.cancel = function ()
uloop.cancel()
end
return uloop_reactor
|
--
-- Created by IntelliJ IDEA.
-- User: Kunkka
-- Date: 17/1/25
-- Time: 下午5:28
-- To change this template use File | Settings | File Templates.
--
local TableViewTest = class("TableViewTest", gk.Layer)
function TableViewTest:ctor()
TableViewTest.super.ctor(self)
-- let height fill screen
local height = gk.display:designSize().height / gk.display:minScale() * gk.display:yScale()
self.layerColor1:setContentSize(cc.size(self.layerColor1:getContentSize().width, height))
self.tableView1:setViewSize(cc.size(self.tableView1:getViewSize().width, height))
self:setData()
self.tableView1:reloadData()
end
function TableViewTest:cellNumForTable(table)
return #self:getData()
end
function TableViewTest:cellSizeForTable(table, idx)
local dt = self:getData()[idx + 1]
-- use size model to calculate cell height dynamically
if not dt.height then
self.cellModel = self.cellModel or gk.injector:inflateNode("gk.test.cell.TableCell1")
self.cellModel:setData(dt)
dt.height = self.cellModel.cellHeight
dt.width = self.cellModel:getContentSize().width
end
return dt.width, dt.height
end
function TableViewTest:cellAtIndex(table, idx)
local dt = self:getData()[idx + 1]
local cell = table:dequeueCell()
if nil == cell then
cell = gk.injector:inflateNode("gk.test.cell.TableCell1")
end
cell:setData(dt)
return cell
end
function TableViewTest:getData()
return self.data or {}
end
function TableViewTest:setData()
self.data = {
{ type = "Time", content = "00:00 AM" },
{ type = "Me", content = "Hello!" },
{ type = "Member", content = "Fell well" },
{ type = "Member", content = "Additive blending is the type of blending we do when we add different colors together and add the result." },
{ type = "Time", content = "11:30 AM" },
{ type = "Me", content = "This is the way that our vision works together with light and this is how we can perceive millions of different colors on our monitors." },
{ type = "Member", content = "Free" },
{ type = "Me", content = "Oops" },
{ type = "Member", content = "I say this as a former Secretary of State and as an American: the Russians are still coming. Our intelligence professionals are imploring Trump to act. Will he continue to ignore & surrender, or protect our country?" },
{ type = "Time", content = "1:30 PM" },
{ type = "Me", content = "OMG" },
{ type = "Member", content = "If schools are mandated to be gun free zones, violence and danger are given an open invitation to enter. Almost all school shootings are in gun free zones. Cowards will only go where there is no deterrent!" },
{ type = "Time", content = "13:12" },
{ type = "Me", content = "Will be making a decision soon on the appointment of new Chief Economic Advisor. Many people wanting the job - will choose wisely!" },
{ type = "Time", content = "11:30" },
{ type = "Member", content = "The United States has an $800 Billion Dollar Yearly Trade Deficit because of our “very stupid” trade deals and policies. Our jobs and wealth are being given to other countries that have taken advantage of us for years. They laugh at what fools our leaders have been. No more!" },
}
end
return TableViewTest
|
util.AddNetworkString( "EPS_RetrievePersonalRecords" )
local function GetJobNameForRecords( target )
local job_number = target:Team( )
local job_name = RPExtraTeams[ job_number ].name
local jobs_to_display = EggrollPoliceSystem.Config.JobsToDisplayInRecords
if jobs_to_display[ "all" ] then
return job_name
end
if jobs_to_display[ "CP" ] and target:isCP( ) then
return job_name
end
for k in pairs( jobs_to_display ) do
if _G[ k ] == job_number then -- _G[ "job_number" ] will convert it into a valid enumeration. It needs to be like this because DarkRP hasn't loaded by the time the configuration file has.
return job_name
end
end
return "Unknown"
end
net.Receive( "EPS_RetrievePersonalRecords", function( _, ply )
local computer = net.ReadEntity( )
if not IsValid( computer ) or computer:GetClass( ) ~= "eps_police_computer" or computer:GetActiveUser( ) ~= ply then
return
end
local target = net.ReadEntity( )
if not IsValid( target ) or not target:IsPlayer( ) then
return
end
local arrest_record_file = file.Read( "eggroll_police_system/arrests/" .. target:SteamID64( ) .. ".txt", "DATA" )
local arrests = { }
if arrest_record_file then
arrests = string.Explode( "|", arrest_record_file, false )
end
for k, v in pairs( arrests ) do
arrests[ k ] = string.Explode( "&", v, false )
end
local data = { }
data.name = target:Name( )
data.model = target:GetModel( )
data.job = GetJobNameForRecords( target )
if data.job == "Unknown" then
data.salary = "Unknown"
else
data.salary = DarkRP.formatMoney( DarkRP.retrieveSalary( target ) )
end
data.arrestrecord = arrests
net.Start( "EPS_RetrievePersonalRecords" )
net.WriteTable( data )
net.Send( ply )
end )
hook.Add( "playerArrested", "Register_EPS_Arrest", function( criminal, arrest_time )
if not IsValid( criminal ) then
return
end
local _, folder = file.Find( "eggroll_police_system", "DATA" )
if table.IsEmpty( folder ) then
file.CreateDir( "eggroll_police_system" )
end
_, folder = file.Find( "eggroll_police_system/arrests", "DATA" )
if table.IsEmpty( folder ) then
file.CreateDir( "eggroll_police_system/arrests" )
end
local filetowrite = "eggroll_police_system/arrests/" .. criminal:SteamID64( ) .. ".txt"
if table.IsEmpty( file.Find( filetowrite, "DATA" ) ) then
file.Write( filetowrite, os.date( "%m/%d/%Y %H:%M", os.time( ) ) .. "&" .. arrest_time )
else
file.Append( filetowrite, "|" .. os.date( "%m/%d/%Y %H:%M", os.time( ) ) .. "&" .. arrest_time )
end
end )
|
--
-- @@LIB_NAME@@, Version: @@Version@@
--
-- This file is a part of @@LIB_NAME@@.
--
-- Author:
-- Xiaofeng Yang 2015
--
-- Provide simple annotation support for Lua.
local M = {}
-- annotationChain[generated function] == { ... }
local annotationChain = setmetatable({},{ __mode = 'k' })
local create = function (fn)
local obj1 = newproxy()
debug.setmetatable(obj1, {
-- support for the quoted part: #"annot()" .. fn
__call = function (_, ...)
local arguments = arg
local Narg = arg.n
local obj2 = newproxy()
debug.setmetatable(obj2, {
__metatable = false,
-- support for the quoted part: "#annot()" .. fn
__len = function (op)
return setmetatable({}, {
-- support for the quoted part: "#annot() .. fn"
__concat = function (op1, op2)
local origFn = op2
local generatedFn = fn(op2, unpack(arguments, 1, Narg))
-- recording
annotationChain[generatedFn] = {
annot = obj1,
orig = origFn
}
return generatedFn
end
})
end,
})
return obj2
end,
__metatable = false,
-- support for the quoted part: "#annot" .. fn
__len = function (op)
return setmetatable({}, {
__metatable = false,
-- support for the quoted part: "#annot .. fn"
__concat = function (op1, op2)
local origFn = op2
local generatedFn = fn(op2)
-- recording
annotationChain[generatedFn] = {
annot = obj1,
orig = origFn
}
return generatedFn
end
})
end
})
return obj1
end
---
-- 返回一个annotation对象,该对象使用`fn'对输入的函数进行处理.
--
-- 使用时注意:
--
-- * fn(x)和x之间不要形成循环引用,否则都不会被gc。
-- * 一个fn(x)只能对应一个x。
-- * 除非所有的fn(x)都被gc,否则fn不会被gc。
--
-- @usage local annotatedObject = #annotation .. fn
--
M.annotation = create(create)
---
--
-- 对已注解的对象,在注解过程中每次返回的对象,应用函数fn.
--
-- 具体如下。
--
-- 若已知
--
-- a1 == #annot1 .. a2 -- 每个annot可能带参数也可能不带参数
-- a2 == #annot2 .. a3
-- a3 == #annot3 .. a4
-- ...
-- an == #annotN .. orig
--
-- 则
--
-- applyOnAnnotated(a1, fn) ==
-- fn(a2, annot1)
-- fn(a3, annot2)
-- fn(a4, annot3)
-- ...
-- fn(orig, annotN)
--
-- @param annotated 要处理的对象(通常是函数)。
-- @param #function fn 用于处理的函数。
--
-- @usage
--
-- -- 这个小例子展示了函数的用法。
--
-- local t = {}
--
-- local annot1 =
-- #Annotation.annotation ..
-- function (fn)
-- local result = function (...)
-- fn(...)
-- end
-- t[result] = '(by annot2)'
-- return result
-- end
--
--
-- local annot2 =
-- #Annotation.annotation ..
-- function (fn)
-- local result = function (...)
-- fn(...)
-- end
-- t[result] = '(by annot2)'
-- return result
-- end
--
--
-- local annot3 =
-- #Annotation.annotation ..
-- function (fn)
-- local result = function (...)
-- fn(...)
-- end
-- t[result] = '(by annot3)'
-- return result
-- end
--
-- local f = function () end
-- local anf =
-- #annot1 ..
-- #annot2 ..
-- #annot3 ..
-- f
--
-- local alist = { [ annot1 ] = 'annot1' , [annot2] = 'annot2', [annot3] = 'annot3' }
--
-- t[f] = 'orig'
--
-- Annotation.applyOnAnnotated(anf,function (fn, annotfn)
-- print(t[fn], alist[annotfn])
-- end)
--
-- -- Output:
-- --
-- -- (by annot2) annot1
-- -- (by annot3) annot2
-- -- orig annot3
M.applyOnAnnotated = function (annotated, fn)
-- TODO 也许需要更好的版本,提供annotation时的参数。
local ax = annotationChain[annotated]
if ax then
fn(ax.orig, ax.annot)
return M.applyOnAnnotated(ax.orig, fn)
end
end
---
-- 对已注解的对象,在注解过程中第一个应用注解的对象(原始对象),应用函数fn.
--
-- 若已知
--
-- a1 == #annot1 .. a2 -- 每个annot可能带参数也可能不带参数
-- a2 == #annot2 .. a3
-- a3 == #annot3 .. a4
-- ...
-- an == #annotN .. orig
--
-- 则
--
-- applyOnAnnotated(a1, fn) ==
-- fn(orig)
--
-- @param annotated 要处理的对象(通常是函数)。
-- @param #function fn 用于处理的函数。
--
-- @usage
--
-- -- 这个小例子展示了函数的用法。
--
-- local t = {}
--
-- local annot1 =
-- #Annotation.annotation ..
-- function (fn)
-- local result = function (...)
-- fn(...)
-- end
-- t[result] = '(by annot2)'
-- return result
-- end
--
--
-- local annot2 =
-- #Annotation.annotation ..
-- function (fn)
-- local result = function (...)
-- fn(...)
-- end
-- t[result] = '(by annot2)'
-- return result
-- end
--
--
-- local annot3 =
-- #Annotation.annotation ..
-- function (fn)
-- local result = function (...)
-- fn(...)
-- end
-- t[result] = '(by annot3)'
-- return result
-- end
--
-- local f = function () end
-- local anf =
-- #annot1 ..
-- #annot2 ..
-- #annot3 ..
-- f
--
-- local alist = { [ annot1 ] = 'annot1' , [annot2] = 'annot2', [annot3] = 'annot3' }
--
-- t[f] = 'orig'
--
-- Annotation.applyOnUnAnnotated(anf,function (fn)
-- print(t[fn])
-- end)
--
-- -- Output:
-- --
-- -- orig
M.applyOnUnAnnotated = function (annotated, fn)
local t = {}
M.applyOnAnnotated(annotated,function (x)
table.insert(t,x)
end)
if #t > 0 then
local orig = t[#t]
fn(orig)
end
end
return M
|
return {
"icons/weapon/weapon_blade_turkishflag",
"icons/weapon/wp_blade-m017_algeria-flag",
"icons/weapon/wp_blade-m017_argentina-flag",
"icons/weapon/wp_blade-m017_australia-flag",
"icons/weapon/wp_blade-m017_bahrain-flag",
"icons/weapon/wp_blade-m017_belize-flag",
"icons/weapon/wp_blade-m017_black-white",
"icons/weapon/wp_blade-m017_bolivia-flag",
"icons/weapon/wp_blade-m017_brazil-flag",
"icons/weapon/wp_blade-m017_cameroons-flag",
"icons/weapon/wp_blade-m017_chile-flag",
"icons/weapon/wp_blade-m017_colombia-flag",
"icons/weapon/wp_blade-m017_costa rica-flag",
"icons/weapon/wp_blade-m017_denmark-flag",
"icons/weapon/wp_blade-m017_ecuador-flag",
"icons/weapon/wp_blade-m017_egypt-flag",
"icons/weapon/wp_blade-m017_el salvador-flag",
"icons/weapon/wp_blade-m017_england-flag",
"icons/weapon/wp_blade-m017_france-flag",
"icons/weapon/wp_blade-m017_germany-flag",
"icons/weapon/wp_blade-m017_ghana-flag",
"icons/weapon/wp_blade-m017_greece-flag",
"icons/weapon/wp_blade-m017_green-white",
"icons/weapon/wp_blade-m017_guatemala-flag",
"icons/weapon/wp_blade-m017_honduran-flag",
"icons/weapon/wp_blade-m017_iran-flag",
"icons/weapon/wp_blade-m017_iraq-flag",
"icons/weapon/wp_blade-m017_italy-flag",
"icons/weapon/wp_blade-m017_ivory coast-flag",
"icons/weapon/wp_blade-m017_japan-flag",
"icons/weapon/wp_blade-m017_jordan-flag",
"icons/weapon/wp_blade-m017_kuwait-flag",
"icons/weapon/wp_blade-m017_lebanon-flag",
"icons/weapon/wp_blade-m017_libya-2-flag",
"icons/weapon/wp_blade-m017_libya-flag",
"icons/weapon/wp_blade-m017_mexico-flag",
"icons/weapon/wp_blade-m017_morocco-flag",
"icons/weapon/wp_blade-m017_netherlands-flag",
"icons/weapon/wp_blade-m017_new zealand-flag",
"icons/weapon/wp_blade-m017_nicaragua-flag",
"icons/weapon/wp_blade-m017_nigeria-flag",
"icons/weapon/wp_blade-m017_north korea-flag",
"icons/weapon/wp_blade-m017_oman-flag",
"icons/weapon/wp_blade-m017_palestine-flag",
"icons/weapon/wp_blade-m017_panama-flag",
"icons/weapon/wp_blade-m017_paraguay-flag",
"icons/weapon/wp_blade-m017_peru-flag",
"icons/weapon/wp_blade-m017_philippines-flag",
"icons/weapon/wp_blade-m017_poland-flag",
"icons/weapon/wp_blade-m017_portugal-flag",
"icons/weapon/wp_blade-m017_qatar-flag",
"icons/weapon/wp_blade-m017_red-white",
"icons/weapon/wp_blade-m017_russia-flag",
"icons/weapon/wp_blade-m017_saudi arabia-flag",
"icons/weapon/wp_blade-m017_scarlet-blue",
"icons/weapon/wp_blade-m017_serbia-flag",
"icons/weapon/wp_blade-m017_slovakia-flag",
"icons/weapon/wp_blade-m017_slovenia-flag",
"icons/weapon/wp_blade-m017_south africa-flag",
"icons/weapon/wp_blade-m017_south korea-flag",
"icons/weapon/wp_blade-m017_spain-flag",
"icons/weapon/wp_blade-m017_sudan-flag",
"icons/weapon/wp_blade-m017_switzerland-flag",
"icons/weapon/wp_blade-m017_syria-flag",
"icons/weapon/wp_blade-m017_taiwan-flag",
"icons/weapon/wp_blade-m017_thailand-flag",
"icons/weapon/wp_blade-m017_the_united_arab_emirates-flag",
"icons/weapon/wp_blade-m017_tunisia-flag",
"icons/weapon/wp_blade-m017_uruguay-flag",
"icons/weapon/wp_blade-m017_usa-flag",
"icons/weapon/wp_blade-m017_venezuela-flag",
"icons/weapon/wp_blade-m017_yellow-navyblue",
"icons/weapon/wp_blade-m017_yellow-red",
"icons/weapon/eq_blade-m017_belgium-flag",
"icons/weapon/eq_blade-m017_croatia-flag",
"icons/weapon/eq_blade-m017_herzegovina-flag",
}
|
local _M = {}
function _M.register_rbac_resources(dao)
local utils = require "kong.tools.utils"
local bit = require "bit"
local rbac = require "kong.rbac"
local bxor = bit.bxor
-- action int for all
local action_bits_all = 0x0
for k, v in pairs(rbac.actions_bitfields) do
action_bits_all = bxor(action_bits_all, rbac.actions_bitfields[k])
end
local roles = {}
-- now, create the roles and assign endpoint permissions to them
-- first, a read-only role across everything
roles.read_only = dao.rbac_roles:insert({
id = utils.uuid(),
name = "read-only",
comment = "Read-only access across all initial RBAC resources",
})
-- this role only has the 'read-only' permissions
dao.rbac_role_endpoints:insert({
role_id = roles.read_only.id,
workspace = "*",
endpoint = "*",
actions = rbac.actions_bitfields.read,
})
-- admin role with CRUD access to all resources except RBAC resource
roles.admin = dao.rbac_roles:insert({
id = utils.uuid(),
name = "admin",
comment = "CRUD access to most initial resources (no RBAC)",
})
-- the 'admin' role has 'full-access' + 'no-rbac' permissions
dao.rbac_role_endpoints:insert({
role_id = roles.admin.id,
workspace = "*",
endpoint = "*",
actions = action_bits_all, -- all actions
})
dao.rbac_role_endpoints:insert({
role_id = roles.admin.id,
workspace = "*",
endpoint = "/rbac",
negative = true,
actions = action_bits_all, -- all actions
})
-- finally, a super user role who has access to all initial resources
roles.super_admin = dao.rbac_roles:insert({
id = utils.uuid(),
name = "super-admin",
comment = "Full CRUD access to all initial resources, including RBAC entities",
})
dao.rbac_role_endpoints:insert({
role_id = roles.super_admin.id,
workspace = "*",
endpoint = "*",
actions = action_bits_all, -- all actions
})
local super_admin, err = dao.rbac_users:insert({
id = utils.uuid(),
name = "super_gruce",
user_token = "letmein",
enabled = true,
comment = "Test - Initial RBAC Super Admin User"
})
if err then
return err
end
local super_user_role, err = dao.rbac_user_roles:insert({
user_id = super_admin.id,
role_id = roles.super_admin.id
})
if err then
return err
end
return super_admin, super_user_role
end
return _M
|
local combat = Combat()
combat:setParameter(COMBAT_PARAM_TYPE, COMBAT_DEATHDAMAGE)
combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_MORTAREA)
combat:setParameter(COMBAT_PARAM_DISTANCEEFFECT, CONST_ANI_DEATH)
local condition = Condition(CONDITION_CURSED)
condition:setParameter(CONDITION_PARAM_DELAYED, true)
condition:addDamage(1, 4000, -45)
condition:addDamage(1, 4000, -40)
condition:addDamage(1, 4000, -35)
condition:addDamage(1, 4000, -34)
condition:addDamage(2, 4000, -33)
condition:addDamage(2, 4000, -32)
condition:addDamage(2, 4000, -31)
condition:addDamage(2, 4000, -30)
condition:addDamage(3, 4000, -29)
condition:addDamage(3, 4000, -25)
condition:addDamage(3, 4000, -24)
condition:addDamage(4, 4000, -23)
condition:addDamage(4, 4000, -20)
condition:addDamage(5, 4000, -19)
condition:addDamage(5, 4000, -15)
condition:addDamage(6, 4000, -10)
condition:addDamage(10, 4000, -5)
combat:setCondition(condition)
function onCastSpell(creature, variant)
return combat:execute(creature, variant)
end
|
return {
Core = require(script.Core);
new = require(script.Core).new;
useChaining = require(script.Chaining);
useQuery = require(script.Query);
useReplication = require(script.Replication);
useTags = require(script.Tags);
}
|
local mod = {}
local dpdkc = require "dpdkc"
local ffi = require "ffi"
mod.rte_i40e_pmd = require "driver.i40e"
mod.rte_ixgbe_pmd = require "driver.ixgbe"
mod.rte_igb_pmd = require "driver.igb"
mod.rte_virtio_pmd = require "driver.virtio"
mod.rte_vmxnet3_pmd = require "driver.vmxnet3"
function mod.initDriver(dev)
local device = require "device"
local driver = mod[dev:getDriverName()]
if driver then
if not getmetatable(driver) then
driver.__index = driver
driver.__eq = device.__devicePrototype.__eq
driver.__tostring = device.__devicePrototype.__tostring
setmetatable(driver, device.__devicePrototype)
end
setmetatable(dev, driver)
end
dev.driverInfo = dev.driverInfo or {}
end
-- retrieve driver-specific information
-- required for driver-specific configuration variables
function mod.getDriverInfo(driverName)
return (mod[driverName] or {}).driverInfo or {}
end
return mod
|
local socket = require 'skynet.socket'
local base = require 'client.base'
local client = base:subclass("LOGGER_CLIENT_UDP")
---
function client:initialize(logger, fmt, host, port)
base.initialize(self, logger, fmt)
self._host = host
self._port = tonumber(port) or 1514
end
--- Timeout: ms
function client:send(raw_data)
return socket.write(self._socket, raw_data)
end
function client:start()
if self._socket then
return nil, "Already started"
end
self._socket = socket.udp(function(str, from)
print(from, str)
end, '0.0.0.0', math.random(6100, 6100 + 100))
socket.udp_connect(self._socket, self._host, self._port)
return self._socket
end
function client:stop()
if not self._socket then
return
end
socket.close(self._socket)
self._socket = nil
end
return client
|
-- TODO: Add support for MAC OS and Linux
workspace "Nova" -- "Solution name"
architecture "x64" -- Only support x64
configurations
{
"Debug", -- Development
"Release", -- "Faster development", still logging etc
"Dist" -- For release to "other people", stripped version
}
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
IncludeDir = {}
IncludeDir["GLFW"] = "Nova/vendor/GLFW/include"
-- Adding GLFW submodule (and others) premake to this premake script
include "Nova/vendor/GLFW"
-- Nova {Engine} Project
project "Nova"
location "Nova"
kind "SharedLib" -- == "DLL" in Windows
language "C++"
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
-- Precompiled header for Nova project
pchheader "novapch.h"
pchsource "Nova/src/novapch.cpp" -- Only needed for Visual Studio (MSVC Compiler) (needs full path)
files
{
-- Add more files if needed, other file extensions etc
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp"
}
includedirs
{
-- Add more include folders if needed, other 3rd party etc
"%{prj.name}/src",
"%{prj.name}/vendor/spdlog/include",
"%{IncludeDir.GLFW}"
}
-- Add links to Nova project to GLFW and opengl32
links
{
"GLFW",
"opengl32.lib"
}
-- WINDOWS
filter "system:windows" -- Everything below here, until next "filter" or "project" is Windows-only
cppdialect "C++17" -- "Only works" for Win, for other OS, flags etc might be needed
staticruntime "On" -- Link statically
systemversion "latest" -- You could use "latest" as well (Windows SDK)
defines
{
-- Windows specific DEFINES, add/remove as needed
"NOVA_PLATFORM_WINDOWS",
"NOVA_BUILD_DLL"
}
postbuildcommands
{
-- TODO: Move this to Nebulas project instead, wierd that Nova project should know about Nebula
("{COPY} %{cfg.buildtarget.relpath} ../bin/" .. outputdir .. "/Nebula")
}
filter "configurations:Debug"
defines "NOVA_DEBUG"
symbols "On"
filter "configurations:Release"
defines "NOVA_RELEASE"
optimize "On"
filter "configurations:Dist"
defines "NOVA_DIST"
optimize "On"
-- Nebula {Sandbox} Project
project "Nebula"
location "Nebula"
kind "ConsoleApp" -- Executable (.exe on Windows)
language "C++"
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
files
{
-- Add more files if needed, other file extensions etc
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp"
}
includedirs
{
-- Add more include folders if needed, other 3rd party etc
"Nova/vendor/spdlog/include",
"Nova/src"
}
links
{
"Nova"
}
-- WINDOWS
filter "system:windows" -- Everything below here, until next "filter" or "project" is Windows-only
cppdialect "C++17" -- "Only works" for Win, for other OS, flags etc might be needed
staticruntime "On" -- Link statically
systemversion "latest" -- You could use "latest" as well (Windows SDK)
defines
{
-- Windows specific DEFINES, add/remove as needed
"NOVA_PLATFORM_WINDOWS"
}
filter "configurations:Debug"
defines "NOVA_DEBUG"
symbols "On"
filter "configurations:Release"
defines "NOVA_RELEASE"
optimize "On"
filter "configurations:Dist"
defines "NOVA_DIST"
optimize "On"
|
local inserted = false
local tinsert = table.insert
local music = {
{
text = "Bride of Dawn",
value = "Interface\\AddOns\\DBM-TURUL-MusicPack\\Music\\Bride_of_Dawn.ogg"
},
{
text = "End Effect",
value = "Interface\\AddOns\\DBM-TURUL-MusicPack\\Music\\End_Effect.ogg"
},
{
text = "Fall of the Dark Lady",
value = "Interface\\AddOns\\DBM-TURUL-MusicPack\\Music\\Fall_of_the_Dark_Lady.ogg"
},
{
text = "Guardian of the Mortals",
value = "Interface\\AddOns\\DBM-TURUL-MusicPack\\Music\\Guardian_of_the_Mortals.ogg"
},
{
text = "Hidden History",
value = "Interface\\AddOns\\DBM-TURUL-MusicPack\\Music\\Hidden_History.ogg"
},
{
text = "Horn of the Necrolord",
value = "Interface\\AddOns\\DBM-TURUL-MusicPack\\Music\\Hord_of_the_Necrolord.ogg"
},
{
text = "Inception of the Chain",
value = "Interface\\AddOns\\DBM-TURUL-MusicPack\\Music\\Inception_of_the_Chain.ogg"
},
{
text = "Infernum",
value = "Interface\\AddOns\\DBM-TURUL-MusicPack\\Music\\Infernum.ogg"
},
{
text = "Vision of the Gods",
value = "Interface\\AddOns\\DBM-TURUL-MusicPack\\Music\\Vision_of_the_Gods.ogg"
},
{
text = "Voice of the Eden",
value = "Interface\\AddOns\\DBM-TURUL-MusicPack\\Music\\Voice_of_the_Eden.ogg"
},
{
text = "Volcano",
value = "Interface\\AddOns\\DBM-TURUL-MusicPack\\Music\\Volcano.ogg"
}
}
function DBMMTURULPack() -- Register Music
if inserted then
return
end
local dbmAddMusic = DBM.AddMusic
for _, v in pairs(music) do
if dbmAddMusic then
dbmAddMusic(v.text, v.value)
else
tinsert(DBM.Music, v)
end
end
inserted = true
end
|
local mod = ...
local M =
{
Msg = nil,
SC = nil,
TM="--:--:--",
UpT=''
}
_G[mod] = M
-- 128 x 64 with top 16 lines in different color
local WC={ "\208", "\211", "\209", "\210" }
local WCNT=1
local NWT=0 -- how many waiters
local IC_X=119
local IC_Y=0
local M_X = 51
local M_Y = 5
local T_X=0
local T_Y=2
local PREPCB=nil
local DRAWCB=nil
local SLEEP =false
function M.startWait()
NWT=NWT + 1
end
function M.endWait()
if NWT > 0 then
NWT=NWT-1
end
end
-- print 6x10 font
function M.set6x10()
end
-- print 6x13 font
function M.set6x13()
end
-- print 18x25 digit
function M.setLargeDigit()
end
-- print 9x15 symbol
function M.setSymbol()
end
function M.setSleepMode(sleepOn)
SLEEP = sleepOn
end
function M.setBrightness(bright)
if bright < 0 then bright = 0
elseif bright > 255 then bright = 255
end
end
function M.ToYMDHMS(tk)
local t=rtctime.epoch2cal(tk + 28800) -- convert to GMT+8
return string.format("%4d/%d/%d %02d:%02d:%02d", t["year"], t["mon"], t["day"], t["hour"], t["min"], t["sec"])
end
function M.ToHMS(tk)
local t=rtctime.epoch2cal(tk + 28800) -- convert to GMT+8
return string.format("%02d:%02d:%02d", t["hour"],t["min"],t["sec"])
end
function M.HMSToS(hms)
if not hms or hms:len() ~= 8 then return -1 end
local h = hms:sub(1,2)
if not h:match("%d") then return -1 end
return h*3600 + hms:sub(4,5)*60 + hms:sub(7,8)
end
local function Display()
local up = tmr.time()
M.UpT=string.format("%d.%02d:%02d", up/86400, up%86400/3600, up%3600/60)
local tick=rtctime.get()
if tick > 1483228800 then -- 2017/1/1
M.TM=M.ToHMS(tick)
end
local icon=M.SC
if NWT > 0 then
icon=WC[(WCNT % 4) + 1]
WCNT=WCNT + 1
end
local msg=M.Msg
M.Msg=nil
if PREPCB then PREPCB() end
if SLEEP then
return
end
if bit.band(up, 2) == 0 and not msg then
msg = "H:"..node.heap()
end
if DRAWCB then DRAWCB() end
end
function M.setCallback(prepCall, drawCall)
PREPCB = prepCall
DRAWCB = drawCall
end
function M.init(drawInterval)
tmr.create():alarm(drawInterval, tmr.ALARM_AUTO, Display)
end
return M
|
local button = {}
local buttons = {}
function button.clear()
for k, v in pairs(buttons) do
if v.label ~= HELP_BUTTON_STR then
buttons[k] = nil
end
end
end
function button.add( newX, newY, newWidth, newHeight, newLabel, functionOff, functionHover, newEvent, newArgument )
local newButton = {}
newButton.x = newX
newButton.y = newY
newButton.label = newLabel
newButton.centered = isCentered
newButton.w = newWidth
newButton.h = newHeight
newButton.drawNormal = functionOff
newButton.drawHover = functionHover
newButton.event = newEvent
newButton.argument = newArgument -- passed to event
table.insert( buttons, newButton )
end
function button.debug()
print("debugging buttons: ")
for key, button in pairs( buttons ) do
print(button)
print(button.label)
print(button.x)
print(button.y)
end
end
local function mouseOver( theButton ) --check if the mouse is over the (rectangular) button
local x, y = love.mouse.getPosition()
if x > theButton.x and x < theButton.x + theButton.w and y > theButton.y and y < theButton.y + theButton.h then
return true
end
return false
end
function button.show()
love.graphics.setFont( buttonFont )
love.graphics.setLineWidth( 3 )
love.graphics.setLineStyle( "smooth" )
helpButton = nil
for key, button in pairs( buttons ) do
if mouseOver( button ) and button.drawHover then
if button.label == HELP_BUTTON_STR then -- draw Help button above everything else.
helpButton = button
else
button.drawHover( button )
end
elseif button.drawNormal then
button.drawNormal( button )
end
end
if helpButton then helpButton.drawHover( helpButton ) end
end
function button.handleClick()
for key, button in pairs( buttons ) do
if mouseOver( button ) then
if button.event then
button.event( button.argument )
end
return
end
end
end
return button
|
function initNPCHLC()
all_npcs = {}
unsynced_npcs = {}
last_update = {}
initNPCControl()
end
addEventHandler("onResourceStart",resourceRoot,initNPCHLC)
function addNPCToUnsyncedListOnStopSync()
addNPCToUnsyncedList(source)
end
function removeNPCFromUnsyncedListOnStartSync()
removeNPCFromUnSyncedList(source)
end
function addNPCToUnsyncedList(npc)
unsynced_npcs[npc] = true
updateNPCLastUpdateTime(npc)
end
function removeNPCFromUnsyncedList(npc)
unsynced_npcs[npc] = nil
clearNPCLastUpdateTime(npc)
end
function destroyNPCInformationOnDestroy()
destroyNPCInformation(source)
end
function destroyNPCInformation(npc)
removeNPCFromUnsyncedList(npc)
all_npcs[npc] = nil
end
--------------------------------
function updateNPCLastUpdateTime(npc,newtime)
last_update[npc] = newtime or getTickCount()
end
function clearNPCLastUpdateTime(npc)
last_update[npc] = nil
end
function getNPCLastUpdateTime(npc)
return last_update[npc]
end
|
-- A job object.
job = {
-- If the job has been completed
done = false
}
function job:new( o )
o = o or {}
setmetatable( o, self )
self.__index = self
return o
end
function job:start_work()
end
return job
|
---
-- @module Path
--
-- ------------------------------------------------
-- Required Modules
-- ------------------------------------------------
local Class = require( 'lib.Middleclass' )
local Walk = require( 'src.characters.actions.Walk' )
local Open = require( 'src.characters.actions.Open' )
local OpenInventory = require( 'src.characters.actions.OpenInventory' )
local ClimbOver = require( 'src.characters.actions.ClimbOver' )
-- ------------------------------------------------
-- Module
-- ------------------------------------------------
local Path = Class( 'Path' )
-- ------------------------------------------------
-- Private Methods
-- ------------------------------------------------
---
-- Generate smart actions for openable objects. These are a special case,
-- because usually the player will want to move a character onto the tile
-- after the object is openend.
-- @tparam WorldObject worldObject The worldobject to interact with.
-- @tparam Character character The character that interacts with the object.
-- @tparam Tile tile The tile containing the worldobject.
-- @tparam number index The tile's position in the path.
--
local function handleOpenableObjects( worldObject, character, tile, index )
if not worldObject:isPassable() then
local success = character:enqueueAction( Open( character, tile ))
-- Don't create a walk action if the tile is the last one in the path.
if success and index ~= 1 then
success = character:enqueueAction( Walk( character, tile ))
end
return success
end
return character:enqueueAction( Walk( character, tile ))
end
-- ------------------------------------------------
-- Public Methods
-- ------------------------------------------------
---
-- Initializes a new Path object.
--
function Path:initialize()
self.path = {}
self.cost = 0
end
---
-- Iterates over the path. The target tile will be processed at last.
-- @tparam function callback A function to call on every tile.
--
function Path:iterate( callback )
for i = #self.path, 1, -1 do
callback( self.path[i], i )
end
end
---
-- Adds a new tile to this path.
-- @tparam Tile tile A tile to add to this path.
-- @tparam number cost The cost to traverse this tile.
--
function Path:addNode( tile, cost )
self.path[#self.path + 1] = tile
self.cost = self.cost + cost
end
---
-- Automagically generates appropriate Actions for each tile in the path.
-- For example if the character moves through a tile with a door object this
-- function will generate an action to open the door and an action to walk
-- onto the tile itself.
-- @tparam Character character The character to create the actions for.
-- @treturn boolean Wether actions have been created or not.
--
function Path:generateActions( character )
local generatedAction = false
for index = #self.path, 1, -1 do
local tile = self.path[index]
local success
if tile:hasWorldObject() then
local worldObject = tile:getWorldObject()
if worldObject:isOpenable() then
success = handleOpenableObjects( worldObject, character, tile, index )
end
if worldObject:isClimbable() then
success = character:enqueueAction( ClimbOver( character, tile ))
end
if worldObject:isContainer() then
character:enqueueAction( OpenInventory( character, tile ))
end
else
success = character:enqueueAction( Walk( character, tile ))
end
-- Stop adding actions if the previous one wasn't added correctly.
if not success then
break
else
generatedAction = true
end
end
return generatedAction
end
-- ------------------------------------------------
-- Getters
-- ------------------------------------------------
---
-- Returns the length of the path.
-- @treturn number The length of the path.
--
function Path:getLength()
return #self.path
end
---
-- Returns the target tile of the path.
-- @treturn Tile The target of the path.
--
function Path:getTarget()
return self.path[1]
end
---
-- Returns the cost for the path.
-- @treturn number The cost.
--
function Path:getCost()
return self.cost
end
return Path
|
--local Model = require( 'models/base' )
local MySQLDatabase = class( 'MySQLDatabase' )--, Model )
function MySQLDatabase.static:connect( connection_settings )
local object = MySQLDatabase:new()
object.host = connection_settings.host
object.database = connection_settings.database
object.username = connection_settings.username
local password = connection_settings.password
if not ngx.ctx.mysql then
ngx.ctx.mysql = {}
end
if not ngx.ctx.mysql[ object.host..object.database..object.username ] then
local mysql = require( 'resty.mysql' )
local db = mysql:new()
local ok, err, errno, sqlstate = db:connect{
host = object.host,
port = 3306,
database = object.database,
user = object.username,
password = password,
max_packet_size = 1024 * 1024
}
if not ok then
error( 'failed to connect: ' .. err .. ': ' .. (errno or '') .. ' ' .. (sqlstate or '') )
end
ngx.ctx.mysql[ object.host..object.database..object.username ] = db
end
return object
end
function MySQLDatabase:query( sql_statement, substitutions )
-- additional substitution types:
-- %(variable_name)Q - auto single-quote string with internal single-quotes doubled
-- %(variable_name)t - convert to 'YYYY-MM-DD HH:MM:SS' format
-- %(variable_name)n - validate as identifier
-- invalid substitution types:
-- %(variable_name)s - plain string substitutions are ripe for SQL-injection
-- %(variable_name)q - this context does not lend itself to requiring auto double-quoting of strings
if substitutions then
local _format = function( key, fmt )
local value = substitutions[ key ]
if fmt == 'Q' then
if type( value ) ~= 'string' then
error( "input:2: bad argument #2 to 'format' (string expected, got " .. type( value ) .. ")" )
end
value = value:gsub( "'", "''" )
value = "'" .. value .. "'"
substitutions[ key ] = value
fmt = 's'
elseif fmt == 'n' then
if type( value ) ~= 'string' or value:match( '[^%w_%.]+' ) then
error( "input:2: bad argument #2 to 'format' (valid SQL identifier expected, got " .. type( value ) .. ")" )
end
fmt = 's'
elseif fmt == 't' then
error( 'please implement :)' )
end
return substitutions[ key ] and ( '%' .. fmt ):format( substitutions[ key ] ) or '%(' .. key .. ')'.. fmt
end
sql_statement = sql_statement:gsub( '%%%((%a[%w_]*)%)([-0-9%.]*[cdeEfgGiouxXQtn])', _format )
end
ngx.log( ngx.DEBUG, "\n"..sql_statement )
ngx.ctx.sql = sql_statement:gsub( '\n ', ' ' ):gsub( '\n', ' ' )
local db = ngx.ctx.mysql[ self.host..self.database..self.username ]
if not db then
error( 'failed to access object\'s db connection' )
end
local res, err, errorcode, sqlstate = db:query( sql_statement )
if err then
error( { err, sql_statement } )
end
return res, err, errorcode, sqlstate
end
function MySQLDatabase:value( sql_statement, substitutions )
local result = self:result( sql_statement, substitutions )
if result then
local key = next( result )
local value = result[key]
if type( value ) == 'string' and value:match( '^-?%d+%.?%d*$' ) then
return tonumber( value )
else
return value
end
--return result[key]
end
end
function MySQLDatabase:result( sql_statement, substitutions )
local res = self:resultset( sql_statement, substitutions )
--ngx.say( inspect( res ) )
if res and #res > 0 then
return res[1]
else
return nil
end
end
function MySQLDatabase:resultset( sql_statement, substitutions )
local res, err, errno, sqlstate = self:query( sql_statement, substitutions )
if res then
for _, row in ipairs( res ) do
-- handle JSON by checking names of columns for those ending in _details
for name, value in pairs( row ) do
if name:match( 'details$' ) or name:match( 'json$' ) then
if type( value ) == 'string' and value:trim() ~= '' then
row[name] = cjson.decode( value )
-- handle NULL and empty string
elseif type( value ) == 'userdata' or type( value == 'string' and value:trim() == '' ) then
row[name] = {}
end
end
end
--[[
if row.details ~= nil then
if type( row.details ) == 'string' and row.details:trim() ~= '' then
row.details = cjson.decode( row.details )
-- handle NULL and empty string
elseif type( row.details ) == 'userdata' or type( row.details == 'string' and row.details:trim() == '' ) then
row.details = {}
end
end -- if details column present
--]]
end -- for loop
end -- if res
return res
end
function MySQLDatabase:indexedresultset( indexby, sql_statement, substitutions )
local results = self:resultset( sql_statement, substitutions )
local indexedresults = {}
for _, row in ipairs( results ) do
indexedresults[ tostring( row[indexby] ) ] = row
end
return indexedresults
end
-- only supports simple PRIMARY KEY
function MySQLDatabase:update( table_name, id, changes )
local primary_key_column = 'id'
-- if no changes table then assume that id of row to update and changes are merged together in second parameter
if not changes then
changes = table.copy( id )
id = changes[primary_key_column]
changes[primary_key_column] = nil
else
if type( id ) == 'table' then
for key, value in pairs( id ) do
primary_key_column = key
id = value
break
end
end
end
local values = {}
local i = 1
for key, value in pairs( changes ) do
--ngx.say( key, ' ', type(value), ' ', inspect(value) )
if type( value ) == 'string' then
values[i] = key.." = '"..value:gsub( "'", "%\\'" ).."'"
i = i + 1
elseif type( value ) == 'number' then
values[i] = key.." = "..value
i = i + 1
elseif value == ngx.null then
values[i] = key.." = NULL"
i = i + 1
elseif type( value ) == 'table' and key == 'details' then
-- details gets encoded as JSON as it enters the database
local cleaned = cjson.encode( value )
-- remove quotes
cleaned = cleaned:gsub( "'", "%\\'" )
-- handle escapes
cleaned = cleaned:gsub( "\\([^'])", '\\\\%1' )
values[i] = key.." = '"..cleaned.."'"
i = i + 1
end
end
-- add quotes if primary key is a string
if type( id ) == 'string' then
id = "'"..id.."'"
end
local set_clause = table.concat( values, ',\n ' )
local query = string.interpolate( [[
UPDATE
%(tablename)s
SET
%(setclause)s
WHERE
%(primarykeycolumn)s = %(primarykey)s
]], { tablename = table_name, setclause = set_clause, primarykeycolumn = primary_key_column, primarykey = id } )
return self:query( query )
end
function MySQLDatabase:insert( table_name, row )
local values = {}
local i = 1
--ngx.say( table_name, inspect( row ) )
for key, value in pairs( row ) do
--ngx.say( key, ' ', type(value), ' ', inspect(value) )
if type( value ) == 'string' then
values[i] = key.." = '"..value:gsub( "'", "%\\'" ).."'"
i = i + 1
elseif type( value ) == 'number' then
values[i] = key.." = "..value
i = i + 1
elseif type( value ) == 'table' and key == 'details' then
if next( value ) == nil then
values[i] = key.." = NULL"
else
-- details gets encoded as JSON as it enters the database
local cleaned = cjson.encode( value )
-- remove quotes
cleaned = cleaned:gsub( "'", "%\\'" )
-- handle escapes
cleaned = cleaned:gsub( "\\([^'])", '\\\\%1' )
values[i] = key.." = '"..cleaned.."'"
end
i = i + 1
end
end
local set_clause = table.concat( values, ',\n ' )
local query = string.interpolate( [[
INSERT INTO
%(tablename)s
SET
%(setclause)s
]], { tablename = table_name, setclause = set_clause } )
return self:query( query )
end
function MySQLDatabase:delete( table_name, id )
local query = string.interpolate( [[
DELETE FROM
%(tablename)s
WHERE
id = %(id)s
]], { tablename = table_name, id = id } )
return self:query( query )
end
return MySQLDatabase
|
help(
[[
This module loads xz 5.2.2 into the environment. XZ Utils is free
general-purpose data compression software with a high compression ratio. XZ
Utils were written for POSIX-like systems, but also work on some not-so-POSIX
systems. XZ Utils are the successor to LZMA Utils.
]])
whatis("Loads the xz compression software")
local version = "5.2.2"
local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/xz/"..version
prepend_path("PATH", pathJoin(base, "bin"))
prepend_path("CPATH", pathJoin(base, "include"))
prepend_path("LD_LIBRARY_PATH", pathJoin(base, "lib"))
prepend_path("LIBRARY_PATH", pathJoin(base, "lib"))
family('xz')
|
local lspconfig = require('lspconfig')
local lspconfigs = require('lspconfig.configs')
local lspkind = require('lspkind')
local lsp_installer = require("nvim-lsp-installer")
local coq = require("coq")
local M = {}
-- add some emoji decorations to the completion menu's suggestions
lspkind.init({
with_text = true,
symbol_map = {
Text = '📜',
Method = '🧶',
Function = '🧵',
Constructor = '🚧',
Variable = '🔻',
Class = '📦',
Interface = '🧩',
Module = '🚛',
Property = '💊',
Unit = '🗳 ',
Value = '🧪',
Enum = '🧫',
Keyword = '🔑',
Snippet = '🌱',
Color = '🎨',
File = '🗄 ',
Folder = '📁',
EnumMember = '🦠',
Constant = '🧊',
Struct = '🧱',
Operator = '❎',
Buffer = '🪐'
},
})
-- keymaps
function M.on_attach(client, bufnr)
local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end
local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end
buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc')
-- Mappings.
local opts = { noremap=true, silent=true }
buf_set_keymap('n', 'gD', '<Cmd>lua vim.lsp.buf.declaration()<CR>', opts)
buf_set_keymap('n', 'gd', '<Cmd>lua vim.lsp.buf.definition()<CR>', opts)
buf_set_keymap('n', '<C-]>', '<Cmd>lua vim.lsp.buf.definition()<CR>', opts)
buf_set_keymap('n', 'K', '<Cmd>lua vim.lsp.buf.hover()<CR>', opts)
buf_set_keymap('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts)
buf_set_keymap('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts)
buf_set_keymap('n', '<leader>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts)
buf_set_keymap('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts)
-- Not all LSPs implement every bit of functionality; check the particular
-- LSP server we've attached to for these
if (client.resolved_capabilities.document_formatting or client.resolved_capabilities.document_range_formatting) then
buf_set_option('formatexpr', 'v:lua.vim.lsp.formatexpr(#{timeout_ms:250})')
end
end
lsp_installer.on_server_ready(function(server)
local opts = {
-- map buffer local keybindings when the language server attaches
on_attach = M.on_attach,
}
local has_lsp_config, custom_lsp_config = pcall(require, "me.lsp.configs." .. server.name)
if has_lsp_config then
opts = vim.tbl_deep_extend("force", opts, custom_lsp_config)
end
-- This setup() function is exactly the same as lspconfig's setup function.
-- Refer to https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md
server:setup(coq.lsp_ensure_capabilities(opts))
end)
return M
|
-- Copyright (c) 2021 Trevor Redfern
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
local Selectors = {}
function Selectors.get(state, perspective, position)
if not state.fogOfWar then return nil end
local view = state.fogOfWar[perspective]
if not view then return nil end
return view[position.hashKey]
end
return Selectors
|
local lpugl = require"lpugl_cairo"
local oocairo = require"oocairo"
local floor = math.floor
local ceil = math.ceil
local abs = math.abs
local sqrt = math.sqrt
local unpack = table.unpack or unpack -- for Lua 5.1
math.randomseed(os.time())
local world = lpugl.newWorld("example03.lua")
local scale = world:getScreenScale()
local fillCache
local drawBall
do
local function drawBallImpl(cairo, x, y, r,
r1, g1, b1,
r2, g2, b2)
local alpha = 0.7
local d = r*0.75
local pattern = oocairo.pattern_create_radial(x - d, y - d, r - d,
x - d, y - d, 2*r)
pattern:add_color_stop_rgba(0, r1, g1, b1, alpha)
pattern:add_color_stop_rgba(1, r2, g2, b2, alpha)
cairo:set_source(pattern)
cairo:arc(x, y, r, 0, math.pi * 2)
cairo:fill();
end
local gradientTable = {
{ 1.0, 0.8, 0.8,
1.0, 0.0, 0.0 },
{ 0.7, 1.0, 0.7,
0.0, 1.0, 0.0 },
{ 0.7, 0.7, 1.0,
0.0, 0.0, 1.0 },
}
local cache = {}
local use_cache = true
local padding = 10
fillCache = function(gradientIndex, r)
local c2 = cache[gradientIndex]; if not c2 then c2 = {}; cache[gradientIndex] = c2 end
if not c2[r] then
local layoutTarget = world:getDefaultBackend():getLayoutContext():get_target()
local surface = oocairo.surface_create_similar(layoutTarget, "color-alpha", 2*(r+padding), 2*(r+padding))
local cairo = oocairo.context_create(surface)
drawBallImpl(cairo, r + padding, r + padding, r,
unpack(gradientTable[gradientIndex]))
c2[r] = surface
end
end
local bug_workaround = true -- enlarge surface and clip to prevent strange border artefacts when
-- painting the surface on non integer coordinates (bug in cairo?)
drawBall = function(cairo, x, y, r, gradientIndex)
if use_cache then
local cached = cache[gradientIndex][r]
if bug_workaround then
cairo:save()
cairo:rectangle(floor(x - r - padding/2), floor(y - r - padding/2), ceil(2*r+padding), ceil(2*r+padding))
cairo:clip()
end
cairo:set_source(cached, x - r - padding, y - r - padding)
cairo:paint()
if bug_workaround then
cairo:restore()
end
else
drawBallImpl(cairo, x, y, r,
unpack(gradientTable[gradientIndex]))
end
end
end
local initialWidth, initialHeight = 640*scale, 480*scale
local objects_draw
local objects_push
local objects_process
do
local objects = {}
for i = 1, 500 do
local obj = {}
objects[i] = obj
obj.r = math.random(floor(10*scale), floor(30*scale))
obj.x = math.random(obj.r, floor(initialWidth - 2 * obj.r))
obj.y = math.random(obj.r, floor(initialHeight - 2 * obj.r))
obj.g = math.random(1, 3)
obj.dx = 5 * math.random() / 20 * scale
obj.dy = 5 * math.random() / 20 * scale
fillCache(obj.g, obj.r)
end
objects_draw = function(cairo, w, h)
for i = 1, #objects do
local obj = objects[i]
drawBall(cairo, obj.x, obj.y, obj.r, obj.g)
end
end
objects_push = function(bx, by)
for i = 1, #objects do
local obj = objects[i]
local x, y = obj.x, obj.y
local bdx, bdy = x - bx, y - by
local bd = sqrt(bdx^2 + bdy^2)/scale
local a = (bd + 0.01)^-1.5
obj.dx = obj.dx + a * bdx
obj.dy = obj.dy + a * bdy
end
end
local lastT = world:getTime()
objects_process = function(w, h)
local currT = world:getTime()
local dt = (currT - lastT) * 1000
for i = 1, #objects do
local obj = objects[i]
local x, y = obj.x, obj.y
x = x + obj.dx * dt
if x + obj.r > w then
x = w - obj.r
obj.dx = -obj.dx
elseif x - obj.r < 0 then
x = obj.r
obj.dx = -obj.dx
end
y = y + obj.dy * dt
if y + obj.r > h then
y = h - obj.r
obj.dy = -obj.dy
elseif y - obj.r < 0 then
y = obj.r
obj.dy = -obj.dy
end
obj.x, obj.y = x, y
obj.dx = obj.dx * (1 - dt * 0.0001)
obj.dy = obj.dy * (1 - dt * 0.0001)
end
lastT = currT
end
end
local lastDisplayTime = 0
local renderStartTime = nil
local renderTime = 0
local renderCount = 0
local lastRender = 0
local frameTime = 0
local frameCount = 0
local processTime = 0
local processCount = 0
local view = world:newView
{
title = "example03",
size = {initialWidth, initialHeight},
resizable = true,
eventFunc = function(view, event, ...)
if event == "EXPOSE" then
local startTime = world:getTime()
frameTime = frameTime + startTime - lastRender
frameCount = frameCount + 1
lastRender = startTime
local cairo = view:getDrawContext()
local w, h = view:getSize()
cairo:set_source_rgb(1.0, 1.0, 1.0)
cairo:rectangle(0, 0, w, h)
cairo:fill()
objects_draw(cairo, w, h)
renderStartTime = startTime
world:setNextProcessTime(0)
elseif event == "BUTTON_PRESS" then
local bx, by, bn = ...
if bn == 1 then
objects_push(bx, by)
end
elseif event == "CLOSE" then
view:close()
end
end
}
view:show()
local lastP = world:getTime()
local REFRESH_PERIOD = 0.015
world:setProcessFunc(function()
if not view:isClosed() then
local startTime = world:getTime()
if renderStartTime then
renderTime = renderTime + (startTime - renderStartTime)
renderCount = renderCount + 1
lastDisplayTime = renderStartTime
renderStartTime = nil
end
local now = world:getTime()
if now >= lastDisplayTime + REFRESH_PERIOD then
objects_process(view:getSize())
processTime = processTime + world:getTime() - startTime
processCount = processCount + 1
view:postRedisplay()
world:setNextProcessTime(REFRESH_PERIOD)
else
world:setNextProcessTime(lastDisplayTime + REFRESH_PERIOD - now)
end
if startTime > lastP + 2 and renderCount > 0 and processCount > 0 then
print(string.format("render: %5.1fms, process: %5.1fms, period: %5.1fms",
renderTime/renderCount * 1000,
processTime/processCount * 1000,
frameTime/frameCount * 1000))
renderTime = 0
renderCount = 0
processTime = 0
processCount = 0
frameTime = 0
frameCount = 0
lastP = startTime
end
end
end)
world:setNextProcessTime(0)
while world:hasViews() do
world:update()
end
|
-- local MQ = require "MQ.stomp"
local MQ = require "MQ.redis"
-- local MQ = require "MQ.mqtt"
local cf = require "cf"
require "utils"
local mq = MQ:new {
host = 'localhost',
-- port = 61613,
-- port = 1883,
port = 6379,
-- vhost = '/exchange',
-- auth = "admin",
-- username = "guest",
-- password = "guest",
}
mq:on('/test', function (msg)
print("收到来自/test的消息.")
var_dump(msg)
end)
mq:on('/admin', function (msg)
print("收到来自/admin的消息.")
var_dump(msg)
end)
cf.at(0.1, function (args)
print(mq:emit('/test', '{"code":'..math.random(1, 100)..',"from":"/test"}'))
print(mq:emit('/admin', '{"code":'..math.random(1, 100)..',"from":"/admin"}'))
end)
mq:start()
|
--[[
Made by Fenrier.
]]
Player=game:GetService("Players").LocalPlayer
Character=Player.Character
PlayerGui=Player.PlayerGui
Backpack=Player.Backpack
Torso=Character.Torso
Head=Character.Head
Humanoid=Character.Humanoid
LeftArm=Character["Left Arm"]
LeftLeg=Character["Left Leg"]
RightArm=Character["Right Arm"]
RightLeg=Character["Right Leg"]
LS=Torso["Left Shoulder"]
LH=Torso["Left Hip"]
RS=Torso["Right Shoulder"]
RH=Torso["Right Hip"]
Neck=Torso.Neck
it=Instance.new
vt=Vector3.new
cf=CFrame.new
euler=CFrame.fromEulerAnglesXYZ
angles=CFrame.Angles
necko=cf(0, 1, 0, -1, -0, -0, 0, 0, 1, 0, 1, 0)
necko2=cf(0, -0.5, 0, -1, -0, -0, 0, 0, 1, 0, 1, 0)
LHC0=cf(-1,-1,0,-0,-0,-1,0,1,0,1,0,0)
LHC1=cf(-0.5,1,0,-0,-0,-1,0,1,0,1,0,0)
RHC0=cf(1,-1,0,0,0,1,0,1,0,-1,-0,-0)
RHC1=cf(0.5,1,0,0,0,1,0,1,0,-1,-0,-0)
RootPart=Character.HumanoidRootPart
RootJoint=RootPart.RootJoint
RootCF=euler(-1.57,0,3.14)
attack = false
attackdebounce = false
MMouse=nil
combo=0
mana=0
local idle=0
local Anim="Idle"
local Effects={}
local guard=false
--player
player=nil
--save shoulders
RSH, LSH=nil, nil
--welds
RW, LW=Instance.new("Weld"), Instance.new("Weld")
RW.Name="Right Shoulder" LW.Name="Left Shoulder"
LH=Torso["Left Hip"]
RH=Torso["Right Hip"]
TorsoColor=Torso.BrickColor
function swait(num)
if num==0 or num==nil then
--if Stagger.Value==false or Stun.Value<=100 then
game:service'RunService'.Stepped:wait(0)
--end
else
for i=0,num do
game:service'RunService'.Stepped:wait(0)
--[[if Stagger.Value==true or Stun.Value>=100 then
break
end]]
end
end
end
if Character:findFirstChild("Glaciem",true) ~= nil then
Character:findFirstChild("Glaciem",true).Parent = nil
end
if Player.PlayerGui:findFirstChild("WeaponGUI",true) ~= nil then
Player.PlayerGui:findFirstChild("WeaponGUI",true).Parent = nil
end
if Character:findFirstChild("Stats",true) ~= nil then
Character:findFirstChild("Stats",true).Parent = nil
end
local Stats=Instance.new("BoolValue")
Stats.Name="Stats"
Stats.Parent=Character
local Atk=Instance.new("NumberValue")
Atk.Name="Damage"
Atk.Parent=Stats
Atk.Value=1
local Def=Instance.new("NumberValue")
Def.Name="Defense"
Def.Parent=Stats
Def.Value=1
local Speed=Instance.new("NumberValue")
Speed.Name="Speed"
Speed.Parent=Stats
Speed.Value=1
local Mvmt=Instance.new("NumberValue")
Mvmt.Name="Movement"
Mvmt.Parent=Stats
Mvmt.Value=1
local Block=Instance.new("BoolValue")
Block.Name="Block"
Block.Parent=Stats
Block.Value=false
local Stun=Instance.new("NumberValue")
Stun.Name="Stun"
Stun.Parent=Stats
Stun.Value=0
local Stunned=Instance.new("BoolValue")
Stunned.Name="Stunned"
Stunned.Parent=Stats
Stunned.Value=false
local Stagger=Instance.new("BoolValue")
Stagger.Name="Stagger"
Stagger.Parent=Stats
Stagger.Value=false
local StaggerHit=Instance.new("BoolValue")
StaggerHit.Name="StaggerHit"
StaggerHit.Parent=Stats
StaggerHit.Value=false
local RecentEnemy=Instance.new("ObjectValue")
RecentEnemy.Name="RecentEnemy"
RecentEnemy.Parent=Stats
RecentEnemy.Value=nil
function NoOutline(Part)
Part.TopSurface,Part.BottomSurface,Part.LeftSurface,Part.RightSurface,Part.FrontSurface,Part.BackSurface = 10,10,10,10,10,10
end
function part(formfactor,parent,reflectance,transparency,brickcolor,name,size)
local fp=it("Part")
fp.formFactor=formfactor
fp.Parent=parent
fp.Reflectance=reflectance
fp.Transparency=transparency
fp.CanCollide=false
fp.Locked=true
fp.BrickColor=brickcolor
fp.Name=name
fp.Size=size
fp.Position=Torso.Position
NoOutline(fp)
fp.Material="SmoothPlastic"
fp:BreakJoints()
return fp
end
function mesh(Mesh,part,meshtype,meshid,offset,scale)
local mesh=it(Mesh)
mesh.Parent=part
if Mesh=="SpecialMesh" then
mesh.MeshType=meshtype
if meshid~="nil" then
mesh.MeshId="http://www.roblox.com/asset/?id="..meshid
end
end
mesh.Offset=offset
mesh.Scale=scale
return mesh
end
function weld(parent,part0,part1,c0)
local weld=it("Weld")
weld.Parent=parent
weld.Part0=part0
weld.Part1=part1
weld.C0=c0
return weld
end
local Color1=Torso.BrickColor
local fengui=it("GuiMain")
fengui.Parent=Player.PlayerGui
fengui.Name="WeaponGUI"
local fenframe=it("Frame")
fenframe.Parent=fengui
fenframe.BackgroundColor3=Color3.new(255,255,255)
fenframe.BackgroundTransparency=1
fenframe.BorderColor3=Color3.new(17,17,17)
fenframe.Size=UDim2.new(0.0500000007, 0, 0.100000001, 0)
fenframe.Position=UDim2.new(0.4,0,0.1,0)
local fenbarmana1=it("TextLabel")
fenbarmana1.Parent=fenframe
fenbarmana1.Text=" "
fenbarmana1.BackgroundTransparency=0
fenbarmana1.BackgroundColor3=Color3.new(0,0,0)
fenbarmana1.SizeConstraint="RelativeXY"
fenbarmana1.TextXAlignment="Center"
fenbarmana1.TextYAlignment="Center"
fenbarmana1.Position=UDim2.new(0,0,0,0)
fenbarmana1.Size=UDim2.new(4,0,0.2,0)
local fenbarmana2=it("TextLabel")
fenbarmana2.Parent=fenframe
fenbarmana2.Text=" "
fenbarmana2.BackgroundTransparency=0
fenbarmana2.BackgroundColor3=Torso.Color
fenbarmana2.SizeConstraint="RelativeXY"
fenbarmana2.TextXAlignment="Center"
fenbarmana2.TextYAlignment="Center"
fenbarmana2.Position=UDim2.new(0,0,0,0)
fenbarmana2.Size=UDim2.new(4*mana/100,0,0.2,0)
local fenbarmana3=it("TextLabel")
fenbarmana3.Parent=fenframe
fenbarmana3.Text=" "
fenbarmana3.BackgroundTransparency=0
fenbarmana3.BackgroundColor3=Color3.new(Col1,Col2,Col3)
fenbarmana3.SizeConstraint="RelativeXY"
fenbarmana3.TextXAlignment="Center"
fenbarmana3.TextYAlignment="Center"
fenbarmana3.Position=UDim2.new(0,0,0,0)
fenbarmana3.Size=UDim2.new(0,0,0.2,0)
local fenbarmana4=it("TextLabel")
fenbarmana4.Parent=fenframe
fenbarmana4.Text="Mana("..mana..")"
fenbarmana4.BackgroundTransparency=1
fenbarmana4.BackgroundColor3=Color3.new(0,0,0)
fenbarmana4.SizeConstraint="RelativeXY"
fenbarmana4.TextXAlignment="Center"
fenbarmana4.TextYAlignment="Center"
fenbarmana4.Position=UDim2.new(0,0,-0.3,0)
fenbarmana4.Size=UDim2.new(4,0,0.2,0)
fenbarmana4.FontSize="Size9"
fenbarmana4.TextStrokeTransparency=0
fenbarmana4.TextColor=BrickColor.new("White")
local modelzorz=Instance.new("Model")
modelzorz.Parent=Character
modelzorz.Name="Glaciem"
local prt1=part(3,modelzorz,0,0,TorsoColor,"Part01",vt())
local prt2=part(3,modelzorz,0,0,BrickColor.new("Black"),"Part02",vt())
local prt3=part(3,modelzorz,0,0,BrickColor.new("Bright blue"),"Part03",vt())
local prt4=part(3,modelzorz,0,0,BrickColor.new("Bright blue"),"Part04",vt())
local prt5=part(3,modelzorz,0,0,BrickColor.new("Cyan"),"Part05",vt())
local prt6=part(3,modelzorz,0,0,BrickColor.new("Cyan"),"Part06",vt())
local prt7=part(3,modelzorz,0,0,BrickColor.new("Cyan"),"Part07",vt())
local prtt=part(3,modelzorz,0.8,0,BrickColor.new("Medium blue"),"Part09",vt())
local sprt1=part(3,modelzorz,0,0,BrickColor.new("Black"),"Shield Part01",vt())
local sprt2=part(3,modelzorz,0.5,0,BrickColor.new("Cyan"),"Shield Part02",vt())
local sprt3=part(3,modelzorz,0.5,0,BrickColor.new("Cyan"),"Shield Part03",vt())
local sprt4=part(3,modelzorz,0.5,0,BrickColor.new("Cyan"),"Shield Part04",vt())
local sprt5=part(3,modelzorz,0.5,0,BrickColor.new("Cyan"),"Shield Part05",vt())
local sprt6=part(3,modelzorz,0,0,BrickColor.new("Bright blue"),"Shield Part06",vt())
local sprt7=part(3,modelzorz,0,0,BrickColor.new("Bright blue"),"Shield Part07",vt())
local sprt8=part(3,modelzorz,0,0,BrickColor.new("Bright blue"),"Shield Part08",vt())
local sprt9=part(3,modelzorz,0,0,BrickColor.new("Bright blue"),"Shield Part09",vt())
local sprt10=part(3,modelzorz,0,0,BrickColor.new("Medium blue"),"Shield Part10",vt())
local msh1=mesh("SpecialMesh",prt1,"Head","nil",vt(0,0,0),vt(2,6,2))
local msh2=mesh("CylinderMesh",prt2,"","",vt(0,0,0),vt(1.5,8,1.5))
local msh3=mesh("SpecialMesh",prt3,"FileMesh","9756362",vt(0,0,0),vt(.6,.5,.6))
local msh4=mesh("SpecialMesh",prt4,"FileMesh","9756362",vt(0,0,0),vt(1.35,.35,.7))
local msh5=mesh("BlockMesh",prt5,"","",vt(0,0,0),vt(10,1,3))
local msh6=mesh("BlockMesh",prt6,"","",vt(0,0,0),vt(3,1.2,3.1))
local msh7=mesh("BlockMesh",prt7,"","",vt(0,0,0),vt(3,1.2,3.1))
local msht=mesh("SpecialMesh",prtt,"FileMesh","9756362",vt(0,0,0),vt(0.8,1.4,0.31))
local smsh1=mesh("BlockMesh",sprt1,"","",vt(0,0,0),vt(1,1,1))
local smsh2=mesh("SpecialMesh",sprt2,"Wedge","nil",vt(0,0,0),vt(1.5,6,10))
local smsh3=mesh("SpecialMesh",sprt3,"Wedge","nil",vt(0,0,0),vt(1.5,6,10))
local smsh4=mesh("SpecialMesh",sprt4,"Wedge","nil",vt(0,0,0),vt(1.5,6,5))
local smsh5=mesh("SpecialMesh",sprt5,"Wedge","nil",vt(0,0,0),vt(1.5,6,5))
local smsh6=mesh("SpecialMesh",sprt6,"Wedge","nil",vt(0,0,0),vt(1.2,8,12))
local smsh7=mesh("SpecialMesh",sprt7,"Wedge","nil",vt(0,0,0),vt(1.2,8,12))
local smsh8=mesh("SpecialMesh",sprt8,"Wedge","nil",vt(0,0,0),vt(1.2,8,7))
local smsh9=mesh("SpecialMesh",sprt9,"Wedge","nil",vt(0,0,0),vt(1.2,8,7))
local smsh10=mesh("SpecialMesh",sprt10,"FileMesh","187687193",vt(0,0,0),vt(3,1,3))
--Meshes = {187687161, 187687175, 187687193}
local wld1=weld(prt1,prt1,sprt1,euler(0,0,0)*cf(0,2.5,0))
--local wld1=weld(prt1,prt1,RightArm,euler(1.57,0,0)*cf(0,1,0))
local wld2=weld(prt2,prt2,prt1,euler(0,0,0)*cf(0,0,0))
local wld3=weld(prt3,prt3,prt2,euler(0,0,0)*cf(0,.8,0))
local wld4=weld(prt4,prt4,prt2,euler(0,1.57,0)*cf(0,-.9,0))
local wld5=weld(prt5,prt5,prt4,euler(0,0,0)*cf(0,-.05,0))
local wld6=weld(prt6,prt6,prt5,euler(0,0,-1.4)*cf(-1,-.2,0))
local wld7=weld(prt7,prt7,prt5,euler(0,0,1.4)*cf(1,-.2,0))
local wldt=weld(prtt,prtt,prt4,euler(0,0,0)*cf(0,-3.45,0))
local swld1=weld(sprt1,sprt1,LeftArm,euler(-1.57,0,0)*cf(.5,.5,0))
local swld2=weld(sprt2,sprt2,sprt1,euler(-1.57,0,0)*cf(.1,-.8,-.6))
local swld3=weld(sprt3,sprt3,sprt1,euler(-1.57,3.14,0)*cf(.1,-.8,.6))
local swld4=weld(sprt4,sprt4,sprt1,euler(-1.57,0,3.14)*cf(.1,.7,-.6))
local swld5=weld(sprt5,sprt5,sprt1,euler(-1.57,3.14,3.14)*cf(.1,.7,.6))
local swld6=weld(sprt6,sprt6,sprt1,euler(-1.57,0,0)*cf(.1,-1,-.8))
local swld7=weld(sprt7,sprt7,sprt1,euler(-1.57,3.14,0)*cf(.1,-1,.8))
local swld8=weld(sprt8,sprt8,sprt1,euler(-1.57,0,3.14)*cf(.1,.9,-.8))
local swld9=weld(sprt9,sprt9,sprt1,euler(-1.57,3.14,3.14)*cf(.1,.9,.8))
local swld10=weld(sprt10,sprt10,sprt1,euler(0,0,1.57)*cf(.25,0,0))
for i=0,180,180 do
for x=-20,20,40 do
local lol=i-90
local lol2=math.abs(lol/480)
local lol3=x/90
local prt8=part(3,modelzorz,0.8,0,BrickColor.new("Medium blue"),"Part08",vt())
local msh8=mesh("BlockMesh",prt8,"","",vt(0,0,0),vt(0.2,17.5,2.97))
--local wld8=weld(prt8,prt4,prt8,euler(0,0,0)*cf(.2,-1.7,0)*euler(0,-0.3-0.785,0))
local wld8=weld(prt8,prt4,prt8,cf(0,1.7,0)*euler(0,math.rad(i+x)+1.57,0))
wld8.C1=cf(lol2,0,-lol3)*euler(0,0,0)
end
end
local hitbox=part(3,nil,0,1,BrickColor.new("Black"),"Hitbox",vt(1,1,1))
hitbox.Anchored=false
local hitbox2=part(3,nil,0,1,BrickColor.new("Black"),"Hitbox",vt(1,1,1))
hitbox2.Anchored=true
if (script.Parent.className~="HopperBin") then
Tool=Instance.new("HopperBin")
Tool.Parent=Backpack
Tool.Name="Glaciem"
script.Parent=Tool
end
Bin=script.Parent
local bodvel=Instance.new("BodyVelocity")
local bg=Instance.new("BodyGyro")
so = function(id,par,vol,pit)
coroutine.resume(coroutine.create(function()
local sou = Instance.new("Sound",par or workspace)
sou.Volume=vol
sou.Pitch=pit or 1
sou.SoundId=id
swait()
sou:play()
game:GetService("Debris"):AddItem(sou,6)
end))
end
function clerp(a,b,t)
local qa = {QuaternionFromCFrame(a)}
local qb = {QuaternionFromCFrame(b)}
local ax, ay, az = a.x, a.y, a.z
local bx, by, bz = b.x, b.y, b.z
local _t = 1-t
return QuaternionToCFrame(_t*ax + t*bx, _t*ay + t*by, _t*az + t*bz,QuaternionSlerp(qa, qb, t))
end
function QuaternionFromCFrame(cf)
local mx, my, mz, m00, m01, m02, m10, m11, m12, m20, m21, m22 = cf:components()
local trace = m00 + m11 + m22
if trace > 0 then
local s = math.sqrt(1 + trace)
local recip = 0.5/s
return (m21-m12)*recip, (m02-m20)*recip, (m10-m01)*recip, s*0.5
else
local i = 0
if m11 > m00 then
i = 1
end
if m22 > (i == 0 and m00 or m11) then
i = 2
end
if i == 0 then
local s = math.sqrt(m00-m11-m22+1)
local recip = 0.5/s
return 0.5*s, (m10+m01)*recip, (m20+m02)*recip, (m21-m12)*recip
elseif i == 1 then
local s = math.sqrt(m11-m22-m00+1)
local recip = 0.5/s
return (m01+m10)*recip, 0.5*s, (m21+m12)*recip, (m02-m20)*recip
elseif i == 2 then
local s = math.sqrt(m22-m00-m11+1)
local recip = 0.5/s return (m02+m20)*recip, (m12+m21)*recip, 0.5*s, (m10-m01)*recip
end
end
end
function QuaternionToCFrame(px, py, pz, x, y, z, w)
local xs, ys, zs = x + x, y + y, z + z
local wx, wy, wz = w*xs, w*ys, w*zs
local xx = x*xs
local xy = x*ys
local xz = x*zs
local yy = y*ys
local yz = y*zs
local zz = z*zs
return CFrame.new(px, py, pz,1-(yy+zz), xy - wz, xz + wy,xy + wz, 1-(xx+zz), yz - wx, xz - wy, yz + wx, 1-(xx+yy))
end
function QuaternionSlerp(a, b, t)
local cosTheta = a[1]*b[1] + a[2]*b[2] + a[3]*b[3] + a[4]*b[4]
local startInterp, finishInterp;
if cosTheta >= 0.0001 then
if (1 - cosTheta) > 0.0001 then
local theta = math.acos(cosTheta)
local invSinTheta = 1/math.sin(theta)
startInterp = math.sin((1-t)*theta)*invSinTheta
finishInterp = math.sin(t*theta)*invSinTheta
else
startInterp = 1-t
finishInterp = t
end
else
if (1+cosTheta) > 0.0001 then
local theta = math.acos(-cosTheta)
local invSinTheta = 1/math.sin(theta)
startInterp = math.sin((t-1)*theta)*invSinTheta
finishInterp = math.sin(t*theta)*invSinTheta
else
startInterp = t-1
finishInterp = t
end
end
return a[1]*startInterp + b[1]*finishInterp, a[2]*startInterp + b[2]*finishInterp, a[3]*startInterp + b[3]*finishInterp, a[4]*startInterp + b[4]*finishInterp
end
function hideanim()
equipped=false
for i=0,1,0.2 do
swait()
wld1.C0=clerp(wld1.C0,euler(1.7,-.2,.5)*cf(0,1,0),.4)
Neck.C0=clerp(Neck.C0,necko*euler(.2,0,.4),.4)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,0),.4)
RW.C0=clerp(RW.C0,cf(1,0.5,-.5)*euler(1.5,0,-.5)*euler(0,1.57,0),.4)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.4)
LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(.3,-1.2,-.5),.4)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.4)
RH.C0=clerp(RH.C0,RHC0,.4)
RH.C1=clerp(RH.C1,RHC1,.4)
LH.C0=clerp(LH.C0,LHC0,.4)
LH.C1=clerp(LH.C1,LHC1,.4)
end
Mvmt.Value=Mvmt.Value+.1
wld1.Part1=sprt1
wld1.C0=euler(0,0,0)*cf(0,2.5,0)
for i=0,1,0.3 do
swait()
Neck.C0=clerp(Neck.C0,necko*euler(0,0,0),.4)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,0),.4)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(0,0,0),.4)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.4)
LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(0,0,0),.4)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.4)
end
end
function equipanim()
equipped=true
for i=0,1,0.2 do
swait()
Neck.C0=clerp(Neck.C0,necko*euler(.2,0,.4),.4)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,0),.4)
RW.C0=clerp(RW.C0,cf(1,0.5,-.5)*euler(1.5,0,-.5)*euler(0,1.57,0),.4)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.4)
LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(.3,-1.2,-.5),.4)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.4)
end
Mvmt.Value=Mvmt.Value-.1
wld1.Part1=RightArm
wld1.C0=euler(1.7,-.2,.5)*cf(0,1,0)
local hit,pos=rayCast(RootPart.Position,(CFrame.new(RootPart.Position,RootPart.Position - Vector3.new(0,1,0))).lookVector,200,Character)
if hit~=nil then
local ref=part(3,workspace,0,1,BrickColor.new("Black"),"Effect",vt())
ref.Anchored=true
ref.CFrame=cf(pos)
game:GetService("Debris"):AddItem(ref,1)
MagicWave(BrickColor.new("Medium blue"),cf(ref.Position),1,1,1,1,.5,1,.1)
end
for i=0,1,0.1 do
swait()
wld1.C0=clerp(wld1.C0,euler(1.57,0,0)*cf(0,1,0),.3)
Neck.C0=clerp(Neck.C0,necko*euler(.1,0,-.2),.3)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,0),.3)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(1,0,1)*euler(0,1,0),.3)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(.1,0,-1.4)*euler(0,-.2,0),.3)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
end
end
function StaggerAnim()
attack=true
for i=1,math.random(2,4) do
ClangEffect(BrickColor.new("New Yeller"),cf(hitbox.Position)*euler(math.random(-50,50)/100,math.random(-50,50),math.random(-50,50)/100),0,.1,.2,math.random(150,300)/1000)
end
for i=0,1,0.35 do
swait()
Torso.Velocity=RootPart.CFrame.lookVector*-40
wld1.C0=clerp(wld1.C0,euler(1.57,0,0)*cf(0,1,0),.3)
Neck.C0=clerp(Neck.C0,necko*euler(0,0,.5)*euler(.1,0,0),.3)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(-.2,0,-.4),.3)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-.2,0,.7)*euler(0,-.7,0),.3)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(-.2,0,-.4)*euler(0,.4,0),.3)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
RH.C0=clerp(RH.C0,cf(1,-.8,0)*euler(0,1.57,0)*euler(-.5,0,.6),.3)
LH.C0=clerp(LH.C0,cf(-1,-1,0)*euler(0,-1.57,0)*euler(0,.2,.2),.3)
end
for i=0,1,0.2 do
swait()
Torso.Velocity=RootPart.CFrame.lookVector*-40
wld1.C0=clerp(wld1.C0,euler(1.57,0,0)*cf(0,1,0),.4)
Neck.C0=clerp(Neck.C0,necko*euler(0,0,.5)*euler(.1,0,0),.4)
RootJoint.C0=clerp(RootJoint.C0,RootCF*cf(0,0,-.2)*euler(-.5,0,-.4),.4)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-.2,0,.7)*euler(0,-.7,0),.4)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.4)
LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(-.2,0,-.4)*euler(0,.4,0),.4)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.4)
RH.C0=clerp(RH.C0,cf(1,-.8,0)*euler(0,1.57,0)*euler(-.5,0,.6),.4)
LH.C0=clerp(LH.C0,cf(-1,-1,0)*euler(0,-1.57,0)*euler(0,.2,.5),.4)
end
for i=0,1,0.1 do
swait()
wld1.C0=clerp(wld1.C0,euler(1.57,0,0)*cf(0,1,0),.3)
Neck.C0=clerp(Neck.C0,necko*euler(0,0,.4)*euler(.5,0,0),.3)
RootJoint.C0=clerp(RootJoint.C0,RootCF*cf(0,0,-1.8)*euler(-.2,0,-.4),.3)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-.3,0,.4)*euler(0,-.4,0),.3)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(-.3,0,-.2)*euler(0,.4,0),.3)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
RH.C0=clerp(RH.C0,cf(1,-.8,0)*euler(0,1.57,0)*euler(-.5,0,1.2),.3)
LH.C0=clerp(LH.C0,cf(-1,0,-1)*euler(0,-1.57,0)*euler(0,.2,.2),.3)
end
swait(15)
combo=0
attack=false
end
function StaggerHitt()
attack=true
for i=1,math.random(2,4) do
ClangEffect(BrickColor.new("New Yeller"),cf(hitbox.Position)*euler(math.random(-50,50)/100,math.random(-50,50),math.random(-50,50)/100),0,.1,.2,math.random(150,300)/1000)
end
for i=0,1,0.1 do
swait()
wld1.C0=clerp(wld1.C0,euler(1.57,0,0)*cf(0,1,0),.3)
Neck.C0=clerp(Neck.C0,necko*euler(0,0,.7)*euler(.1,0,0),.3)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(-.2,0,-.6),.3)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-.4,0,.9)*euler(0,-.7,0),.3)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(-.2,0,-.4)*euler(0,.4,0),.3)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
RH.C0=clerp(RH.C0,cf(1,-.8,0)*euler(0,1.57,0)*euler(-.2,0,-.4),.3)
LH.C0=clerp(LH.C0,cf(-1,-1,0)*euler(0,-1.57,0)*euler(0,.2,.2),.3)
end
attack=false
end
function StunAnim()
attack=true
Stunned.Value=true
for i=0,1,0.3 do
swait()
Humanoid.WalkSpeed=0
wld1.C0=clerp(wld1.C0,euler(1.57,0,0)*cf(0,1,0),.2)
Neck.C0=clerp(Neck.C0,necko*euler(-.2,0,-.5),.2)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(.2,0,-3),.2)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-.2,0,1.3),.2)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.2)
LW.C0=clerp(LW.C0,cf(-1.2,0.5,-.4)*euler(1,0,.4)*euler(0,-.1,0),.2)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.2)
RH.C0=clerp(RH.C0,cf(1,-.6,0)*euler(0,1.57,0)*euler(-.5,0,.3),.25)
LH.C0=clerp(LH.C0,cf(-1,-.8,0)*euler(0,-1.57,0)*euler(-.2,0,0),.25)
end
for i=0,1,0.3 do
swait()
Humanoid.WalkSpeed=0
wld1.C0=clerp(wld1.C0,euler(1.57,0,0)*cf(0,1,0),.2)
Neck.C0=clerp(Neck.C0,necko*euler(-.3,0,-.5),.2)
RootJoint.C0=clerp(RootJoint.C0,RootCF*cf(0,0,-.5)*euler(.8,0,-3),.2)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-.8,0,1.3),.2)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.2)
LW.C0=clerp(LW.C0,cf(-1.2,0.5,-.4)*euler(1.2,0,.8)*euler(0,-.1,0),.2)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.2)
RH.C0=clerp(RH.C0,cf(1,-.6,0)*euler(0,1.57,0)*euler(-.5,0,.6),.25)
LH.C0=clerp(LH.C0,cf(-1,-.8,0)*euler(0,-1.57,0)*euler(.1,0,.7),.25)
end
for i=0,1,0.3 do
swait()
Humanoid.WalkSpeed=0
wld1.C0=clerp(wld1.C0,euler(1.57,0,0)*cf(0,1,0),.2)
Neck.C0=clerp(Neck.C0,necko*euler(-.3,0,-1),.2)
RootJoint.C0=clerp(RootJoint.C0,RootCF*cf(0,0,-2)*euler(1.57,0,-3),.2)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-.8,0,1.3),.2)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.2)
LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(1.2,0,-.8)*euler(0,-.1,0),.2)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.2)
RH.C0=clerp(RH.C0,cf(1,-.6,0)*euler(0,1.57,0)*euler(-.2,0,.6),.25)
LH.C0=clerp(LH.C0,cf(-1,-.8,0)*euler(0,-1.57,0)*euler(-.1,0,.3),.25)
end
gairo=Instance.new("BodyGyro")
gairo.Parent=RootPart
gairo.maxTorque=Vector3.new(4e+005,4e+005,4e+005)*math.huge
gairo.P=20e+003
gairo.cframe=RootPart.CFrame
v=Instance.new("BodyVelocity",RootPart)
v.Name="BodVel"
v.P=2000
v.maxForce=Vector3.new(500000000,50000000,500000000)
v.velocity=vt(0,-50,0)
for i=0,1,0.1 do
swait()
Humanoid.WalkSpeed=0
v.velocity=vt(0,-50,0)
wld1.C0=clerp(wld1.C0,euler(1.57,0,0)*cf(0,1,0),.3)
Neck.C0=clerp(Neck.C0,necko*euler(0,0,-1.57),.3)
RootJoint.C0=clerp(RootJoint.C0,RootCF*cf(0,0,-2.5)*euler(1.57,0,-3.14),.3)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-1.57,0,1.5)*euler(.2,0,0),.3)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(1.5,0,-1.57)*euler(0,0,0),.3)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
RH.C0=clerp(RH.C0,cf(1,-1,0)*euler(0,1.57,0)*euler(-.3,.5,0),.3)
LH.C0=clerp(LH.C0,cf(-1,-1,0)*euler(0,-1.57,0)*euler(-.1,.2,0),.3)
end
for i=1,70 do
swait()
Humanoid.WalkSpeed=0
v.velocity=vt(0,-50,0)
end
v.velocity=vt(0,0,0)
for i=0,1,0.2 do
swait()
wld1.C0=clerp(wld1.C0,euler(1.57,0,0)*cf(0,1,0),.3)
Neck.C0=clerp(Neck.C0,necko*euler(.2,0,0),.3)
RootJoint.C0=clerp(RootJoint.C0,RootCF*cf(0,0,-2)*euler(1,0,-4),.3)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-1.57,0,1)*euler(.2,-1,0),.3)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(1.2,0,.2)*euler(0,0,0),.3)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
RH.C0=clerp(RH.C0,cf(1,-1,0)*euler(0,1.57,0)*euler(-.3,.5,.4),.3)
LH.C0=clerp(LH.C0,cf(-1,-1,-1)*euler(0,-1.57,0)*euler(-.1,.2,1),.3)
end
gairo.Parent=nil
v.Parent=nil
combo=0
Stunned.Value=false
attack=false
end
function attackone()
attack=true
for i=0,1,0.2 do
swait()
Neck.C0=clerp(Neck.C0,necko*euler(0,0,.2),.4)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,-.3),.4)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(1,0,1.2)*euler(0,-2,0),.4)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.4)
LW.C0=clerp(LW.C0,cf(-1.4,0.5,-.2)*euler(.7,0,.1)*euler(0,-.4,0),.4)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.4)
RH.C0=clerp(RH.C0,cf(1,-1,0)*euler(0,1.57,0)*euler(0,.3,0),.4)
LH.C0=clerp(LH.C0,cf(-1,-1,0)*euler(0,-1.57,0)*euler(0,.3,0),.4)
if Stagger.Value==true or Stun.Value>=100 or StaggerHit.Value==true then
break
end
end
hitbox.Parent=modelzorz
hitbox.Size=vt(1.1,4,.5)
hitbox.Transparency=1
hitbox.CFrame=prtt.CFrame*cf(0,-1.2,0)
con1=hitbox.Touched:connect(function(hit) Damagefunc(hit,10,15,math.random(5,10),"Normal",RootPart,.5,1,math.random(2,8),nil,true) end)
blcf=nil
scfr=nil
for i=0,1,0.1 do
swait()
local blcf = prtt.CFrame*cf(0,-1.2,0)
if scfr and (prtt.Position-scfr.p).magnitude > .1 then
local h = 4.3
local a,b = Triangle((scfr*CFrame.new(0,h/2,0)).p,(scfr*CFrame.new(0,-h/2,0)).p,(blcf*CFrame.new(0,h/2,0)).p)
if a then game.Debris:AddItem(a,1) end if b then game.Debris:AddItem(b,1) end
local a,b = Triangle((blcf*CFrame.new(0,h/2,0)).p,(blcf*CFrame.new(0,-h/2,0)).p,(scfr*CFrame.new(0,-h/2,0)).p)
if a then game.Debris:AddItem(a,1) end if b then game.Debris:AddItem(b,1) end
scfr = blcf
elseif not scfr then
scfr = blcf
end
hitbox.CFrame=prtt.CFrame*cf(0,-1.2,0)
wld1.C0=clerp(wld1.C0,euler(2.9,0,0)*cf(0,.8,-.2),.25)
Neck.C0=clerp(Neck.C0,necko*euler(.2,0,-.3),.25)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,.3),.25)
RW.C0=clerp(RW.C0,cf(1,0.5,-0.5)*euler(1.2,0,-1)*euler(0,-1,0),.25)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.25)
LW.C0=clerp(LW.C0,cf(-1.4,0.5,-.2)*euler(.7,0,-.7)*euler(0,0,0),.25)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.25)
RH.C0=clerp(RH.C0,cf(1,-1,0)*euler(0,1.57,0)*euler(0,-.3,0),.25)
LH.C0=clerp(LH.C0,cf(-1,-1,0)*euler(0,-1.57,0)*euler(0,-.3,0),.25)
if Stagger.Value==true or Stun.Value>=100 or StaggerHit.Value==true then
break
end
end
con1:disconnect()
hitbox.Parent=nil
attack=false
end
function attacktwo()
attack=true
for i=0,1,0.2 do
swait()
wld1.C0=clerp(wld1.C0,euler(1.57,0,0)*cf(0,1,0),.4)
Neck.C0=clerp(Neck.C0,necko*euler(0,0,-.2)*euler(-.2,0,0),.4)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,.2),.4)
RW.C0=clerp(RW.C0,cf(1,0.5,-0.5)*euler(2.2,0,-.8)*euler(0,1,0),.4)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.4)
LW.C0=clerp(LW.C0,cf(-1.4,0.5,-.2)*euler(.5,0,-.5),.4)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.4)
RH.C0=clerp(RH.C0,cf(1,-1,0)*euler(0,1.57,0)*euler(0,-.2,0),.4)
LH.C0=clerp(LH.C0,cf(-1,-1,0)*euler(0,-1.57,0)*euler(0,-.2,0),.4)
if Stagger.Value==true or Stun.Value>=100 or StaggerHit.Value==true then
break
end
end
hitbox.Parent=modelzorz
hitbox.Size=vt(1.1,4,.5)
hitbox.Transparency=1
hitbox.CFrame=prtt.CFrame*cf(0,-1.2,0)
con1=hitbox.Touched:connect(function(hit) Damagefunc(hit,10,15,math.random(5,10),"Normal",RootPart,.5,1,math.random(2,8),nil,true) end)
blcf=nil
scfr=nil
for i=0,1,0.15 do
swait()
local blcf = prtt.CFrame*cf(0,-1.2,0)
if scfr and (prtt.Position-scfr.p).magnitude > .1 then
local h = 4.3
local a,b = Triangle((scfr*CFrame.new(0,h/2,0)).p,(scfr*CFrame.new(0,-h/2,0)).p,(blcf*CFrame.new(0,h/2,0)).p)
if a then game.Debris:AddItem(a,1) end if b then game.Debris:AddItem(b,1) end
local a,b = Triangle((blcf*CFrame.new(0,h/2,0)).p,(blcf*CFrame.new(0,-h/2,0)).p,(scfr*CFrame.new(0,-h/2,0)).p)
if a then game.Debris:AddItem(a,1) end if b then game.Debris:AddItem(b,1) end
scfr = blcf
elseif not scfr then
scfr = blcf
end
hitbox.CFrame=prtt.CFrame*cf(0,-1.2,0)
wld1.C0=clerp(wld1.C0,euler(2.2,0,0)*cf(0,.8,0),.4)
Neck.C0=clerp(Neck.C0,necko*euler(0,0,-.2)*euler(.4,0,0),.4)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,-.5),.4)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(.2,0,.3)*euler(0,.2,0),.4)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.4)
LW.C0=clerp(LW.C0,cf(-1.4,0.5,-.2)*euler(-.5,0,-.2),.4)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.4)
RH.C0=clerp(RH.C0,cf(1,-1,0)*euler(0,1.57,0)*euler(0,.5,0),.4)
LH.C0=clerp(LH.C0,cf(-1,-1,0)*euler(0,-1.57,0)*euler(0,.5,0),.4)
if Stagger.Value==true or Stun.Value>=100 or StaggerHit.Value==true then
break
end
end
con1:disconnect()
hitbox.Parent=nil
attack=false
end
function attackthree()
attack=true
for i=0,1,0.2 do
swait()
wld1.C0=clerp(wld1.C0,euler(2,0,0)*cf(0,.8,0),.4)
Neck.C0=clerp(Neck.C0,necko*euler(0,0,-.4)*euler(-.4,0,0),.4)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,.4),.4)
RW.C0=clerp(RW.C0,cf(1,0.5,-.5)*euler(2.9,0,-.6)*euler(0,.2,0),.4)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.4)
LW.C0=clerp(LW.C0,cf(-1,0.5,-.4)*euler(3,0,.8)*euler(0,0,0),.4)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.4)
RH.C0=clerp(RH.C0,cf(1,-1,0)*euler(0,1.57,0)*euler(0,-.4,0),.4)
LH.C0=clerp(LH.C0,cf(-1,-1,0)*euler(0,-1.57,0)*euler(0,-.4,0),.4)
if Stagger.Value==true or Stun.Value>=100 or StaggerHit.Value==true then
break
end
end
hitbox.Parent=modelzorz
hitbox.Size=vt(1.1,4,.5)
hitbox.Transparency=1
hitbox.CFrame=prtt.CFrame*cf(0,-1.2,0)
con1=hitbox.Touched:connect(function(hit) Damagefunc(hit,15,20,math.random(5,10),"Normal",RootPart,.5,1,math.random(4,10),nil,true) end)
blcf=nil
scfr=nil
for i=0,1,0.1 do
swait()
local blcf = prtt.CFrame*cf(0,-1.2,0)
if scfr and (prtt.Position-scfr.p).magnitude > .1 then
local h = 4.3
local a,b = Triangle((scfr*CFrame.new(0,h/2,0)).p,(scfr*CFrame.new(0,-h/2,0)).p,(blcf*CFrame.new(0,h/2,0)).p)
if a then game.Debris:AddItem(a,1) end if b then game.Debris:AddItem(b,1) end
local a,b = Triangle((blcf*CFrame.new(0,h/2,0)).p,(blcf*CFrame.new(0,-h/2,0)).p,(scfr*CFrame.new(0,-h/2,0)).p)
if a then game.Debris:AddItem(a,1) end if b then game.Debris:AddItem(b,1) end
scfr = blcf
elseif not scfr then
scfr = blcf
end
hitbox.CFrame=prtt.CFrame*cf(0,-1.2,0)
wld1.C0=clerp(wld1.C0,euler(2.4,0,0)*cf(0,.8,0),.3)
Neck.C0=clerp(Neck.C0,necko*euler(0,0,-.6)*euler(.4,0,0),.3)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,.6),.3)
RW.C0=clerp(RW.C0,cf(1,0.5,-.5)*euler(.5,0,0)*euler(0,-1,0),.3)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
LW.C0=clerp(LW.C0,cf(-.6,0.5,-.5)*euler(.2,0,.6)*euler(0,-1,0),.3)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
RH.C0=clerp(RH.C0,cf(1,-1,0)*euler(0,1.57,0)*euler(0,-.6,0),.3)
LH.C0=clerp(LH.C0,cf(-1,-1,0)*euler(0,-1.57,0)*euler(0,-.6,0),.3)
if Stagger.Value==true or Stun.Value>=100 or StaggerHit.Value==true then
break
end
end
con1:disconnect()
hitbox.Parent=nil
attack=false
end
function attackfour()
attack=true
for i=0,1,0.2 do
swait()
wld1.C0=clerp(wld1.C0,euler(1.57,0,0)*cf(0,1,0),.3)
Neck.C0=clerp(Neck.C0,necko*euler(.2,0,.5),.3)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,-.5),.3)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-.2,0,.4),.3)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
LW.C0=clerp(LW.C0,cf(-.8,0.5,-.5)*euler(1.57,0,1.2)*euler(0,.2,0),.3)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
RH.C0=clerp(RH.C0,cf(1,-1,0)*euler(0,1.57,0)*euler(0,.5,0),.25)
LH.C0=clerp(LH.C0,cf(-1,-1,0)*euler(0,-1.57,0)*euler(0,.5,0),.25)
if Stagger.Value==true or Stun.Value>=100 or StaggerHit.Value==true then
break
end
end
Torso.Velocity=RootPart.CFrame.lookVector*100
hitbox.Parent=modelzorz
hitbox.Size=vt(1,3.5,3)
hitbox.Transparency=1
hitbox.CFrame=sprt1.CFrame*cf(0,.3,0)
con1=hitbox.Touched:connect(function(hit) Damagefunc(hit,10,15,math.random(20,30),"Knockdown2",RootPart,.5,1,math.random(5,15),nil,false) end)
for i=0,1,0.1 do
swait()
hitbox.CFrame=sprt1.CFrame*cf(0,.3,0)
wld1.C0=clerp(wld1.C0,euler(1.57,0,0)*cf(0,1,0),.3)
Neck.C0=clerp(Neck.C0,necko*euler(0,0,.3),.3)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,-.3),.3)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-.4,0,.6),.3)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
LW.C0=clerp(LW.C0,cf(-1,0.5,-.5)*euler(1.57,0,1),.3)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
if Stagger.Value==true or Stun.Value>=100 or StaggerHit.Value==true then
break
end
end
con1:disconnect()
hitbox.Parent=nil
--swait(10)
for i=1,5 do
swait()
if Stagger.Value==true or Stun.Value>=100 or StaggerHit.Value==true then
break
end
end
attack=false
end
function Guard()
attack=true
guard=true
Mvmt.Value=Mvmt.Value-.4
Block.Value=true
for i=0,1,0.15 do
swait()
wld1.C0=clerp(wld1.C0,euler(1.57,0,0)*cf(0,1,0),.3)
Neck.C0=clerp(Neck.C0,necko*euler(0,0,.3),.3)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,-.3),.3)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-.4,0,.2),.3)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
LW.C0=clerp(LW.C0,cf(-1,0.5,-.5)*euler(1.57,0,1.27),.3)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
RH.C0=clerp(RH.C0,cf(1,-1,0)*euler(0,1.57,0)*euler(0,.3,0),.3)
LH.C0=clerp(LH.C0,cf(-1,-1,0)*euler(0,-1.57,0)*euler(0,.3,0),.3)
end
while guard==true and Block.Value==true do
swait()
end
Block.Value=false
Mvmt.Value=Mvmt.Value+.4
attack=false
end
function ShieldSlam()
attack=true
local ref=part(3,workspace,0,1,BrickColor.new("Black"),"Effect",vt())
ref.Anchored=true
ref.CFrame=RootPart.CFrame*cf(0,0,-2)
game:GetService("Debris"):AddItem(ref,1)
for _,c in pairs(workspace:children()) do
local hum=c:findFirstChild("Humanoid")
if hum~=nil then
local head=c:findFirstChild("HumanoidRootPart")
if head~=nil then
if GetDist(head,ref,3)==true then
if head.Parent:findFirstChild("Stats")~=nil then
if head.Parent.Stats.Stunned.Value==true then
Humanoid.WalkSpeed=0
for i=0,1,0.2 do
swait()
wld1.C0=clerp(wld1.C0,euler(1.57,0,0)*cf(0,1,0),.3)
Neck.C0=clerp(Neck.C0,necko*euler(-.2,0,0),.3)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,0),.3)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-.2,0,.4),.3)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
LW.C0=clerp(LW.C0,cf(-1,1,-.5)*euler(2.5,0,1.3)*euler(0,0,0),.3)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
end
hitbox.Parent=modelzorz
hitbox.Size=vt(1,3.5,3)
hitbox.Transparency=1
hitbox.CFrame=sprt1.CFrame*cf(0,.3,0)
con1=hitbox.Touched:connect(function(hit) Damagefunc(hit,20,25,math.random(5,10),"Normal",RootPart,1,1,math.random(5,15),nil,false) end)
for i=0,1,0.15 do
swait()
hitbox.CFrame=sprt1.CFrame*cf(0,.3,0)
wld1.C0=clerp(wld1.C0,euler(1.57,0,0)*cf(0,1,0),.3)
Neck.C0=clerp(Neck.C0,necko*euler(.4,0,.6),.3)
RootJoint.C0=clerp(RootJoint.C0,RootCF*cf(0,0,-1.8)*euler(0,0,-.6),.3)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-.2,0,.4),.3)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
LW.C0=clerp(LW.C0,cf(-1.3,.2,-.5)*euler(1.3,0,1)*euler(0,0,0),.3)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.3)
RH.C0=clerp(RH.C0,cf(1.1,-1,0)*euler(0,1.57,0)*euler(0,0,-1),.3)
LH.C0=clerp(LH.C0,cf(-1,.2,-.4)*euler(0,-1.57,0)*euler(-.2,0,.2),.3)
end
con1:disconnect()
hitbox.Parent=nil
Humanoid.WalkSpeed=16
end
end
end
end
end
end
attack=false
end
function GetDist(Part1,Part2,magni)
local targ=Part1.Position-Part2.Position
local mag=targ.magnitude
if mag<=magni then
return true
else
return false
end
end
function MagniDamage(Part,magni,mindam,maxdam,knock,Type)
for _,c in pairs(workspace:children()) do
local hum=c:findFirstChild("Humanoid")
if hum~=nil then
local head=c:findFirstChild("Torso")
if head~=nil then
local targ=head.Position-Part.Position
local mag=targ.magnitude
if mag<=magni and c.Name~=Player.Name then
Damagefunc(head,mindam,maxdam,knock,Type,RootPart,.2,1,3)
end
end
end
end
end
function rayCast(Pos, Dir, Max, Ignore) -- Origin Position , Direction, MaxDistance , IgnoreDescendants
return game:service("Workspace"):FindPartOnRay(Ray.new(Pos, Dir.unit * (Max or 999.999)), Ignore)
end
local Point=Torso.CFrame*cf(0,Torso.Size.Y,0)
LastPoint=Point
function effect(Color,Ref,LP,P1,returnn)
if LP==nil or P1==nil then return end
local effectsmsh=Instance.new("CylinderMesh")
effectsmsh.Scale=Vector3.new(0.2,1,0.2)
effectsmsh.Name="Mesh"
local effectsg=Instance.new("Part")
NoOutline(effectsg)
effectsg.formFactor=3
effectsg.CanCollide=false
effectsg.Name="Eff"
effectsg.Locked=true
effectsg.Anchored=true
effectsg.Size=Vector3.new(0.5,1,0.5)
effectsg.Parent=workspace
effectsmsh.Parent=effectsg
effectsg.BrickColor=BrickColor.new(Color)
effectsg.Reflectance=Ref
local point1=P1
local mg=(LP.p - point1.p).magnitude
effectsg.Size=Vector3.new(0.5,mg,0.5)
effectsg.CFrame=cf((LP.p+point1.p)/2,point1.p) * CFrame.Angles(math.rad(90),0,0)
effectsmsh.Scale=Vector3.new(0.2,1,0.2)
game:GetService("Debris"):AddItem(effectsg,2)
if returnn then return effectsg end
if not returnn then
table.insert(Effects,{effectsg,"Cylinder",0.2,0.01,0,0.01,effectsmsh})
end
end
local function CFrameFromTopBack(at, top, back)
local right = top:Cross(back)
return CFrame.new(at.x, at.y, at.z,
right.x, top.x, back.x,
right.y, top.y, back.y,
right.z, top.z, back.z)
end
function Triangle(a, b, c)
local edg1 = (c-a):Dot((b-a).unit)
local edg2 = (a-b):Dot((c-b).unit)
local edg3 = (b-c):Dot((a-c).unit)
if edg1 <= (b-a).magnitude and edg1 >= 0 then
a, b, c = a, b, c
elseif edg2 <= (c-b).magnitude and edg2 >= 0 then
a, b, c = b, c, a
elseif edg3 <= (a-c).magnitude and edg3 >= 0 then
a, b, c = c, a, b
else
assert(false, "unreachable")
end
local len1 = (c-a):Dot((b-a).unit)
local len2 = (b-a).magnitude - len1
local width = (a + (b-a).unit*len1 - c).magnitude
local maincf = CFrameFromTopBack(a, (b-a):Cross(c-b).unit, -(b-a).unit)
local list = {}
if len1 > 0.01 then
local w1 = Instance.new('WedgePart', m)
game:GetService("Debris"):AddItem(w1,5)
w1.Material = "SmoothPlastic"
w1.FormFactor = 'Custom'
w1.BrickColor = BrickColor.new("Medium blue")
w1.Transparency = 0
w1.Reflectance = 0
w1.Material = "SmoothPlastic"
w1.CanCollide = false
NoOutline(w1)
local sz = Vector3.new(0.2, width, len1)
w1.Size = sz
local sp = Instance.new("SpecialMesh",w1)
sp.MeshType = "Wedge"
sp.Scale = Vector3.new(0,1,1) * sz/w1.Size
w1:BreakJoints()
w1.Anchored = true
w1.Parent = workspace
w1.Transparency = 0.7
table.insert(Effects,{w1,"Disappear",.05})
w1.CFrame = maincf*CFrame.Angles(math.pi,0,math.pi/2)*CFrame.new(0,width/2,len1/2)
table.insert(list,w1)
end
if len2 > 0.01 then
local w2 = Instance.new('WedgePart', m)
game:GetService("Debris"):AddItem(w2,5)
w2.Material = "SmoothPlastic"
w2.FormFactor = 'Custom'
w2.BrickColor = BrickColor.new("Medium blue")
w2.Transparency = 0
w2.Reflectance = 0
w2.Material = "SmoothPlastic"
w2.CanCollide = false
NoOutline(w2)
local sz = Vector3.new(0.2, width, len2)
w2.Size = sz
local sp = Instance.new("SpecialMesh",w2)
sp.MeshType = "Wedge"
sp.Scale = Vector3.new(0,1,1) * sz/w2.Size
w2:BreakJoints()
w2.Anchored = true
w2.Parent = workspace
w2.Transparency = 0.7
table.insert(Effects,{w2,"Disappear",.05})
w2.CFrame = maincf*CFrame.Angles(math.pi,math.pi,-math.pi/2)*CFrame.new(0,width/2,-len1 - len2/2)
table.insert(list,w2)
end
return unpack(list)
end
function MagicBlock(brickcolor,cframe,x1,y1,z1,x3,y3,z3,delay,Type,parent)
local prt=part(3,workspace,0,0,brickcolor,"Effect",vt())
prt.Anchored=true
prt.CFrame=cframe
msh=mesh("BlockMesh",prt,"","",vt(0,0,0),vt(x1,y1,z1))
game:GetService("Debris"):AddItem(prt,5)
if Type==1 or Type==nil then
table.insert(Effects,{prt,"Block1",delay,x3,y3,z3,msh})
elseif Type==2 then
table.insert(Effects,{prt,"Block2",delay,x3,y3,z3,msh})
end
end
function MagicCircle(brickcolor,cframe,x1,y1,z1,x3,y3,z3,delay)
local prt=part(3,workspace,0,0,brickcolor,"Effect",vt())
prt.Anchored=true
prt.CFrame=cframe
local msh=mesh("SpecialMesh",prt,"Sphere","nil",vt(0,0,0),vt(x1,y1,z1))
game:GetService("Debris"):AddItem(prt,2)
table.insert(Effects,{prt,"Cylinder",delay,x3,y3,z3,msh})
end
function MagicCylinder(brickcolor,cframe,x1,y1,z1,x3,y3,z3,delay)
local prt=part(3,workspace,0,0,brickcolor,"Effect",vt())
prt.Anchored=true
prt.CFrame=cframe
local msh=mesh("CylinderMesh",prt,"","",vt(0,0,0),vt(x1,y1,z1))
game:GetService("Debris"):AddItem(prt,2)
table.insert(Effects,{prt,"Cylinder",delay,x3,y3,z3,msh})
end
function ClangEffect(brickcolor,cframe,duration,decrease,size,power)
local prt=part(3,workspace,0,1,brickcolor,"Effect",vt())
prt.Anchored=true
prt.CFrame=cframe
local msh=mesh("BlockMesh",prt,"","",vt(0,0,0),vt(5,5,5))
game:GetService("Debris"):AddItem(prt,2)
table.insert(Effects,{prt,"CylinderClang",duration,decrease,size,power,prt.CFrame,nil})
end
function MagicWave(brickcolor,cframe,x1,y1,z1,x3,y3,z3,delay)
local prt=part(3,workspace,0,0,brickcolor,"Effect",vt())
prt.Anchored=true
prt.CFrame=cframe
local msh=mesh("SpecialMesh",prt,"FileMesh","http://www.roblox.com/asset/?id=20329976",vt(0,0,0),vt(x1,y1,z1))
game:GetService("Debris"):AddItem(prt,5)
table.insert(Effects,{prt,"Cylinder",delay,x3,y3,z3,msh})
end
Damagefunc=function(hit,minim,maxim,knockback,Type,Property,Delay,KnockbackType,incstun,stagger,staghit)
if hit.Parent==nil then
return
end
if hit.Name=="Hitbox" and hit.Parent~=modelzorz then
StaggerHit.Value=true
end
h=hit.Parent:FindFirstChild("Humanoid")
for _,v in pairs(hit.Parent:children()) do
if v:IsA("Humanoid") then
h=v
end
end
if hit.Parent.Parent:FindFirstChild("Torso")~=nil then
h=hit.Parent.Parent:FindFirstChild("Humanoid")
end
if hit.Parent.className=="Hat" then
hit=hit.Parent.Parent:findFirstChild("Head")
end
if h~=nil and hit.Parent.Name~=Character.Name and hit.Parent:FindFirstChild("Torso")~=nil then
if hit.Parent:findFirstChild("DebounceHit")~=nil then if hit.Parent.DebounceHit.Value==true then return end end
c=Instance.new("ObjectValue")
c.Name="creator"
c.Value=game:service("Players").LocalPlayer
c.Parent=h
RecentEnemy.Value=hit.Parent
game:GetService("Debris"):AddItem(c,.5)
minim=minim*Atk.Value
maxim=maxim*Atk.Value
Damage=math.random(minim,maxim)
blocked=false
enblock=nil
Stats=hit.Parent:findFirstChild("Stats")
if Stats~=nil then
enblock=Stats:findFirstChild("Block")
if Stats:findFirstChild("Defense")~=nil then
Damage=Damage/Stats.Defense.Value
if Damage<=3 and staghit==true then
StaggerHit.Value=true
end
end
if Stats:findFirstChild("Stun")~=nil then
Stats.Stun.Value=Stats.Stun.Value+incstun
end
if Stats:findFirstChild("Stagger")~=nil then
if stagger==true then
Stats.Stagger.Value=true
end
end
end
if enblock~=nil then
if enblock.Value==true then
blocked=true
end
end
if blocked==true then
showDamage(hit.Parent,"Block",.5,BrickColor.new("Bright blue"))
enblock.Value=false
Stagger.Value=true
else
Damage=math.floor(Damage)
h.Health=h.Health-Damage
showDamage(hit.Parent,Damage,.5,BrickColor:Red())
if Type=="Knockdown" then
hum=hit.Parent.Humanoid
hum.PlatformStand=true
coroutine.resume(coroutine.create(function(HHumanoid)
swait(1)
HHumanoid.PlatformStand=false
end),hum)
local angle=(hit.Position-(Property.Position+Vector3.new(0,0,0))).unit
--hit.CFrame=cf(hit.Position,Vector3.new(angle.x,hit.Position.y,angle.z))*CFrame.fromEulerAnglesXYZ(math.pi/4,0,0)
local bodvol=Instance.new("BodyVelocity")
bodvol.velocity=angle*knockback
bodvol.P=5000
bodvol.maxForce=Vector3.new(8e+003, 8e+003, 8e+003)
bodvol.Parent=hit
rl=Instance.new("BodyAngularVelocity")
rl.P=3000
rl.maxTorque=Vector3.new(500000,500000,500000)*50000000000000
rl.angularvelocity=Vector3.new(math.random(-10,10),math.random(-10,10),math.random(-10,10))
rl.Parent=hit
game:GetService("Debris"):AddItem(bodvol,.5)
game:GetService("Debris"):AddItem(rl,.5)
elseif Type=="Knockdown2" then
hum=hit.Parent.Humanoid
local angle=(hit.Position-(Property.Position+Vector3.new(0,0,0))).unit
local bodvol=Instance.new("BodyVelocity")
bodvol.velocity=angle*knockback
bodvol.P=5000
bodvol.maxForce=Vector3.new(8e+003, 8e+003, 8e+003)
bodvol.Parent=hit
game:GetService("Debris"):AddItem(bodvol,.5)
elseif Type=="Normal" then
vp=Instance.new("BodyVelocity")
vp.P=500
vp.maxForce=Vector3.new(math.huge,0,math.huge)
if KnockbackType==1 then
vp.velocity=Property.CFrame.lookVector*knockback+Property.Velocity/1.05
elseif KnockbackType==2 then
vp.velocity=Property.CFrame.lookVector*knockback
end
game:GetService("Debris"):AddItem(vp,.5)
if knockback>0 then
vp.Parent=hit.Parent.Torso
end
end
end
debounce=Instance.new("BoolValue")
debounce.Name="DebounceHit"
debounce.Parent=hit.Parent
debounce.Value=true
game:GetService("Debris"):AddItem(debounce,Delay)
c=Instance.new("ObjectValue")
c.Name="creator"
c.Value=Player
c.Parent=h
game:GetService("Debris"):AddItem(c,.5)
CRIT=false
end
end
showDamage=function(Char,Dealt,du,Color)
m=Instance.new("Model")
m.Name=tostring(Dealt)
h=Instance.new("Humanoid")
h.Health=0
h.MaxHealth=0
h.Parent=m
c=Instance.new("Part")
c.Transparency=0
c.BrickColor=Color
c.Name="Head"
c.TopSurface=0
c.BottomSurface=0
c.formFactor="Plate"
c.Size=Vector3.new(1,.4,1)
ms=Instance.new("CylinderMesh")
ms.Scale=Vector3.new(.8,.8,.8)
if CRIT==true then
ms.Scale=Vector3.new(1,1.25,1)
end
ms.Parent=c
c.Reflectance=0
Instance.new("BodyGyro").Parent=c
c.Parent=m
if Char:findFirstChild("Head")~=nil then
c.CFrame=cf(Char["Head"].CFrame.p+Vector3.new(0,1.5,0))
elseif Char.Parent:findFirstChild("Head")~=nil then
c.CFrame=cf(Char.Parent["Head"].CFrame.p+Vector3.new(0,1.5,0))
end
f=Instance.new("BodyPosition")
f.P=2000
f.D=100
f.maxForce=Vector3.new(math.huge,math.huge,math.huge)
f.position=c.Position+Vector3.new(0,3,0)
f.Parent=c
game:GetService("Debris"):AddItem(m,.5+du)
c.CanCollide=false
m.Parent=workspace
c.CanCollide=false
end
combo=0
function ob1d(mouse)
if attack==true or equipped==false then return end
hold=true
if combo==0 then
combo=1
attackone()
elseif combo==1 then
combo=2
attacktwo()
elseif combo==2 then
combo=3
attackthree()
elseif combo==3 then
combo=0
attackfour()
end
coroutine.resume(coroutine.create(function()
for i=1,50 do
if attack==false then
swait()
end
end
if attack==false then
combo=0
end
end))
end
function ob1u(mouse)
hold = false
end
buttonhold = false
eul=0
equipped=false
function key(key)
if key=="g" then
if guard==true then
guard=false
end
end
if attack==true then return end
if key=="f" then
attack=true
if equipped==false then
equipped=true
RSH=ch.Torso["Right Shoulder"]
LSH=ch.Torso["Left Shoulder"]
--
RSH.Parent=nil
LSH.Parent=nil
--
RW.Name="Right Shoulder"
RW.Part0=ch.Torso
RW.C0=cf(1.5, 0.5, 0) --* CFrame.fromEulerAnglesXYZ(1.3, 0, -0.5)
RW.C1=cf(0, 0.5, 0)
RW.Part1=ch["Right Arm"]
RW.Parent=ch.Torso
--
LW.Name="Left Shoulder"
LW.Part0=ch.Torso
LW.C0=cf(-1.5, 0.5, 0) --* CFrame.fromEulerAnglesXYZ(1.7, 0, 0.8)
LW.C1=cf(0, 0.5, 0)
LW.Part1=ch["Left Arm"]
LW.Parent=ch.Torso
--
equipanim()
else
equipped=false
hideanim()
swait(0)
RW.Parent=nil
LW.Parent=nil
RSH.Parent=player.Character.Torso
LSH.Parent=player.Character.Torso
end
attack=false
end
if equipped==false then return end
if key=="g" then
if guard==false then
Guard()
end
end
if key=="q" then
ShieldSlam()
end
if key=="h" then
mana=100
end
if attack==false then
RecentEnemy.Value=nil
end
end
function key2(key)
end
function s(mouse)
mouse.Button1Down:connect(function() ob1d(mouse) end)
mouse.Button1Up:connect(function() ob1u(mouse) end)
mouse.KeyDown:connect(key)
mouse.KeyUp:connect(key2)
player=Player
ch=Character
MMouse=mouse
end
function ds(mouse)
end
Bin.Selected:connect(s)
Bin.Deselected:connect(ds)
print("Frigost loaded.")
local mananum=0
local donum=0
local stunnum=0
local staggeranim=false
local stunanim=false
local Point=nil
local LastPoint=nil
while true do
game:service'RunService'.RenderStepped:wait(0)
hitbox2.Parent=hitbox.Parent
hitbox2.Size=hitbox.Size
hitbox2.CFrame=hitbox.CFrame
if Stagger.Value==true and staggeranim==false then
coroutine.resume(coroutine.create(function()
staggeranim=true
while attack==true do
swait()
end
StaggerAnim()
StaggerHit.Value=false
Stagger.Value=false
staggeranim=false
end))
end
if StaggerHit.Value==true and staggeranim==false then
coroutine.resume(coroutine.create(function()
staggeranim=true
while attack==true do
swait()
end
StaggerHitt()
StaggerHit.Value=false
Stagger.Value=false
staggeranim=false
end))
end
if Mvmt.Value<0 or Stagger.Value==true or Stun.Value>=100 or StaggerHit.Value==true then
Humanoid.WalkSpeed=0
else
Humanoid.WalkSpeed=16*Mvmt.Value
end
if Stun.Value>=100 and stunanim==false then
coroutine.resume(coroutine.create(function()
stunanim=true
while attack==true do
swait()
end
StunAnim()
Stun.Value=0
stunanim=false
end))
end
if stunnum>=10 then
if Stun.Value>0 then
Stun.Value=Stun.Value-1
end
stunnum=0
end
stunnum=stunnum+1
if donum>=.5 then
handidle=true
elseif donum<=0 then
handidle=false
end
if handidle==false then
donum=donum+0.003
else
donum=donum-0.003
end
local torvel=(RootPart.Velocity*Vector3.new(1,0,1)).magnitude
local velderp=RootPart.Velocity.y
hitfloor,posfloor=rayCast(RootPart.Position,(CFrame.new(RootPart.Position,RootPart.Position - Vector3.new(0,1,0))).lookVector,4,Character)
if equipped==true then
if attack==false then
idle=idle+1
else
idle=0
end
if idle>=500 then
if attack==false then
--Sheath()
end
end
if RootPart.Velocity.y > 1 and hitfloor==nil then
Anim="Jump"
if attack==false then
Neck.C0=clerp(Neck.C0,necko*euler(-0.2,0,0),.2)
Neck.C1=clerp(Neck.C1,necko2*euler(0,0,0),.2)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,0),.2)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-.5,0,0.5),.2)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.2)
LW.C0=clerp(LW.C0,cf(-1.2,0.5,-.4)*euler(1,0,.8)*euler(0,-.7,0),.2)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.2)
RH.C0=clerp(RH.C0,cf(1,-1,-.3)*euler(-0.5,1.57,0)*euler(-.2,0,0),.2)
LH.C0=clerp(LH.C0,cf(-1,-1,-.3)*euler(-0.5,-1.57,0)*euler(-.2,0,0),.2)
end
elseif RootPart.Velocity.y < -1 and hitfloor==nil then
Anim="Fall"
if attack==false then
Neck.C0=clerp(Neck.C0,necko*euler(0.4,0,0),.2)
Neck.C1=clerp(Neck.C1,necko2*euler(0,0,0),.2)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,0),.2)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-0.3,0,0.2),.2)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.2)
LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(-0.3,0,-0.2),.2)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.2)
RH.C0=clerp(RH.C0,cf(1,-1,0)*euler(0.4,1.57,0),.2)
LH.C0=clerp(LH.C0,cf(-1,-1,0)*euler(-0.2,-1.57,0),.2)
end
elseif torvel<1 and hitfloor~=nil then
Anim="Idle"
if attack==false then
wld1.C0=clerp(wld1.C0,euler(1.57,0,0)*cf(0,1,0),.15)
Neck.C0=clerp(Neck.C0,necko*euler(0,0,0),.15)
Neck.C1=clerp(Neck.C1,necko2*euler(0,0,0),.15)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,0),.15)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-.2+(donum/5),0,.4-(donum/3)),.15)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.15)
LW.C0=clerp(LW.C0,cf(-1.2,0.5,-.4)*euler(.7+(donum/3),0,.4+(donum/3))*euler(0,-.4,0),.15)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.15)
RH.C0=clerp(RH.C0,RHC0,.2)
RH.C1=clerp(RH.C1,RHC1,.2)
LH.C0=clerp(LH.C0,LHC0,.2)
LH.C1=clerp(LH.C1,LHC1,.2)
end
elseif torvel>2 and torvel<22 and hitfloor~=nil then
Anim="Walk"
if attack==false then
wld1.C0=clerp(wld1.C0,euler(1.57,0,0)*cf(0,1,0),.2)
Neck.C0=clerp(Neck.C0,necko*euler(0,0,.5),.2)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0.1,0,-.5),.2)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-.4+(donum/2),0,.6-(donum/1)),.2)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.2)
LW.C0=clerp(LW.C0,cf(-1.2,0.5,-.4)*euler(.5+(donum/3),0,.8+(donum/3))*euler(0,-.7,0),.2)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.2)
RH.C0=clerp(RH.C0,cf(1,-1,0)*euler(0,1.57,0)*euler(0,.6,0),.2)
LH.C0=clerp(LH.C0,cf(-1,-1,0)*euler(0,-1.57,0)*euler(0,.5,0),.2)
end
elseif torvel>=22 and hitfloor~=nil then
Anim="Run"
if attack==false then
Neck.C0=clerp(Neck.C0,necko*euler(0,0,.5),.2)
RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0.1,0,-.5),.2)
RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-.4+(donum/5),0,.6-(donum/3)),.2)
RW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.2)
LW.C0=clerp(LW.C0,cf(-1.2,0.5,-.4)*euler(.5+(donum/3),0,.8+(donum/3))*euler(0,-.7,0),.2)
LW.C1=clerp(LW.C1,cf(0,0.5,0)*euler(0,0,0),.2)
RH.C0=clerp(RH.C0,cf(1,-1,0)*euler(0,1.57,0)*euler(0,.6,0),.2)
LH.C0=clerp(LH.C0,cf(-1,-1,0)*euler(0,-1.57,0)*euler(0,.5,0),.2)
end
end
end
if #Effects>0 then
--table.insert(Effects,{prt,"Block1",delay})
for e=1,#Effects do
if Effects[e]~=nil then
--for j=1,#Effects[e] do
local Thing=Effects[e]
if Thing~=nil then
local Part=Thing[1]
local Mode=Thing[2]
local Delay=Thing[3]
local IncX=Thing[4]
local IncY=Thing[5]
local IncZ=Thing[6]
if Thing[2]=="CylinderClang" then
if Thing[3]<=1 then
Thing[1].CFrame=Thing[1].CFrame*CFrame.new(0,2.5*Thing[5],0)*CFrame.fromEulerAnglesXYZ(Thing[6],0,0)
Thing[7]=Thing[1].CFrame
effect("New Yeller",0,Thing[8],Thing[7])
Thing[8]=Thing[7]
Thing[3]=Thing[3]+Thing[4]
else
Part.Parent=nil
table.remove(Effects,e)
end
--[[Mesh=Thing[7]
Mesh.Scale=Mesh.Scale+vt(Thing[4],Thing[5],Thing[6])
Thing[1].Transparency=Thing[1].Transparency+Thing[3]]
end
if Thing[1].Transparency<=1 then
if Thing[2]=="Block1" then
Thing[1].CFrame=Thing[1].CFrame*euler(math.random(-50,50),math.random(-50,50),math.random(-50,50))
Mesh=Thing[7]
Mesh.Scale=Mesh.Scale+vt(Thing[4],Thing[5],Thing[6])
Thing[1].Transparency=Thing[1].Transparency+Thing[3]
elseif Thing[2]=="Block2" then
Thing[1].CFrame=Thing[1].CFrame
Mesh=Thing[7]
Mesh.Scale=Mesh.Scale+vt(Thing[4],Thing[5],Thing[6])
Thing[1].Transparency=Thing[1].Transparency+Thing[3]
elseif Thing[2]=="Cylinder" then
Mesh=Thing[7]
Mesh.Scale=Mesh.Scale+vt(Thing[4],Thing[5],Thing[6])
Thing[1].Transparency=Thing[1].Transparency+Thing[3]
elseif Thing[2]=="Blood" then
Mesh=Thing[7]
Thing[1].CFrame=Thing[1].CFrame*cf(0,.5,0)
Mesh.Scale=Mesh.Scale+vt(Thing[4],Thing[5],Thing[6])
Thing[1].Transparency=Thing[1].Transparency+Thing[3]
elseif Thing[2]=="Elec" then
Mesh=Thing[7]
Mesh.Scale=Mesh.Scale+vt(Thing[7],Thing[8],Thing[9])
Thing[1].Transparency=Thing[1].Transparency+Thing[3]
elseif Thing[2]=="Disappear" then
Thing[1].Transparency=Thing[1].Transparency+Thing[3]
end
else
Part.Parent=nil
table.remove(Effects,e)
end
end
--end
end
end
end
fenbarmana2:TweenSize(UDim2.new(4*mana/100,0,0.2,0),nil,1,0.4,true)
fenbarmana4.Text="Mana("..mana..")"
if mana>=100 then
mana=100
else
if mananum<=8 then
mananum=mananum+1
else
mananum=0
mana=mana+1
end
end
end
--[[
Copyrighted (C) Fenrier 2014
]]
|
local lush = require("lush")
local c = require("gruvboy.colors")
local theme = lush(function()
return {
NvimTreeFolderIcon({ fg = c.yellow }),
NvimTreeIndentMarker({ fg = c.bg4 }),
NvimTreeEndOfBuffer({ fg = c.bg0 }),
NvimTreeRootFolder({ fg = c.bg4, gui = "bold" }),
}
end)
return theme
-- vi:nowrap
|
local BaseGui = require 'src.gui.BaseGui'
local Grid = require 'src.gui.Grid'
local ClassLookup = require 'src.class.ClassLookup'
return function(spriteData, nickname, selectedClass, key, colour)
local characterSelect = BaseGui()
characterSelect.spriteData = spriteData
if key and colour then
characterSelect.spriteData[key] = colour
end
characterSelect.nickname = nickname or 'default'
characterSelect.selectedClass = selectedClass
local selectedClassReference = {'No class selected'}
if characterSelect.selectedClass ~= nil then
selectedClassReference[1] = ClassLookup[characterSelect.selectedClass].name
end
characterSelect.menu = Grid()
characterSelect.menu:addComponent(
'textInput',
{value = 2, weight = 2},
{value = 1, weight = 1},
{{tbl = characterSelect, key = 'nickname'}, {r = 0.3, g = 0.3, b = 0.3}}
)
characterSelect.menu:addComponent(
'button',
{value = 1, weight = 1},
{value = 2, weight = 4},
{
'Eye Colour',
function()
return {
setScene = {
name = 'colourPicker',
args = {
characterSelect.spriteData,
characterSelect.nickname,
characterSelect.selectedClass,
'eyes',
'Eye Colour',
characterSelect.spriteData.eyes
}
}
}
end,
{r = 0, g = 0.7, b = 0}
}
)
characterSelect.menu:addComponent('characterDisplay', {value = 2}, {value = 2}, {characterSelect.spriteData})
characterSelect.menu:addComponent(
'button',
{value = 3, weight = 1},
{value = 2},
{
'Hair Colour',
function()
return {
setScene = {
name = 'colourPicker',
args = {
characterSelect.spriteData,
characterSelect.nickname,
characterSelect.selectedClass,
'hair',
'Hair Colour',
characterSelect.spriteData.hair
}
}
}
end,
{r = 0, g = 0.7, b = 0}
}
)
characterSelect.menu:addComponent(
'button',
{value = 1, weight = 1},
{value = 3, weight = 1},
{
'<',
function()
if characterSelect.selectedClass == nil then
characterSelect.selectedClass = #ClassLookup
else
characterSelect.selectedClass = (characterSelect.selectedClass - 2) % #ClassLookup + 1
end
selectedClassReference[1] = ClassLookup[characterSelect.selectedClass].name
end,
{r = 0, g = 0.7, b = 0}
}
)
characterSelect.menu:addComponent('label', {value = 2}, {value = 3}, {selectedClassReference})
characterSelect.menu:addComponent(
'button',
{value = 3, weight = 1},
{value = 3},
{
'>',
function()
if characterSelect.selectedClass == nil then
characterSelect.selectedClass = 1
else
characterSelect.selectedClass = characterSelect.selectedClass % #ClassLookup + 1
end
selectedClassReference[1] = ClassLookup[characterSelect.selectedClass].name
end,
{r = 0, g = 0.7, b = 0}
}
)
characterSelect.menu:addComponent(
'button',
{value = 2, weight = 2},
{value = 4, weight = 1},
{
'Back',
function()
return {
setScene = {
name = 'mainMenu',
args = {characterSelect.spriteData, characterSelect.nickname, characterSelect.selectedClass}
}
}
end,
{r = 0, g = 0.7, b = 0}
}
)
function characterSelect:resize(width, height)
local minDim = math.min(width, height)
self.menu:setPadding(minDim / 40, minDim / 60)
local border = {
x = width / 4,
y = height / 5
}
self.menu:bakeComponents(border.x, border.y, width - border.x * 2, height - border.y * 2)
end
function characterSelect:update()
return self:updateMenu(self.menu, {spriteData = self.spriteData, nickname = self.nickname})
end
function characterSelect:draw(dt)
self:drawMenu(self.menu, dt)
end
characterSelect:resize(love.graphics.getDimensions())
return characterSelect
end
|
Locales ['cs'] = {
['buy_license'] = 'zakoupit zbrojni prukaz?',
['yes'] = '%s',
['no'] = 'ne',
['weapon_bought'] = 'zakoupeno za $%s',
['not_enough_black'] = 'nemas dostatek spinavych penez',
['not_enough'] = 'nemas dostatek penez',
['already_owned'] = 'tuhle zbran jiz vlastnis!',
['shop_menu_title'] = 'ammu-Nation',
['shop_menu_prompt'] = 'stiskni ~INPUT_CONTEXT~ pro pristup do ~y~Ammu-Nationu~s~.',
['shop_menu_item'] = '$%s',
['map_blip'] = 'ammu-Nation',
}
|
--- GUI structuring tools and event handling.
-- **NOTICE: This module will be deprecated when Factorio 1.2 releases. Use the @{gui-beta} module instead.**
-- @module gui
-- @alias flib_gui
-- @usage local gui = require("__flib__.gui")
-- @see gui.lua
local flib_gui = {}
local table = require("__flib__.table")
local string_gmatch = string.gmatch
local string_gsub = string.gsub
local string_sub = string.sub
local handlers = {}
local templates = {}
local template_lookup = {}
local handler_lookup = {}
local handler_groups = {}
local function generate_template_lookup(t, template_string)
for k, v in pairs(t) do
if type(v) == "table" then
local new_string = template_string..k
if v.type or v.template then
template_lookup[new_string] = v
else
generate_template_lookup(v, new_string..".")
end
end
end
end
local function generate_handler_lookup(t, event_string, groups)
groups[#groups+1] = event_string
for k, v in pairs(t) do
if k ~= "extend" then
local new_string = event_string.."."..k
-- shortcut syntax: key is a defines.events or a custom-input name, value is just the handler
if type(v) == "function" then
v = {
id = defines.events[k] or k,
handler = v
}
end
if v.handler then
v.id = v.id or defines.events[k] or k
v.filters = {}
v.groups = table.deep_copy(groups)
handler_lookup[new_string] = v
-- assign handler to groups
for i=1,#groups do
local group = handler_groups[groups[i]]
if group then
group[#group+1] = new_string
else
handler_groups[groups[i]] = {new_string}
end
end
else
generate_handler_lookup(v, new_string, groups)
end
end
end
groups[#groups] = nil
end
local function generate_filter_lookup()
-- add filter lookup to each handler
for _, players in pairs(global.__flib.gui) do
for player_index, filters in pairs(players) do
if player_index ~= "__size" then
for filter, handler_name in pairs(filters) do
if filter ~= "__size" then
local handler_table = handler_lookup[handler_name]
if handler_table then
local handler_filters = handler_table.filters
local player_filters = handler_filters[player_index]
if player_filters then
player_filters[filter] = filter
player_filters.__size = player_filters.__size + 1
else
handler_filters[player_index] = {__size=1, [filter]=filter}
end
end
end
end
end
end
end
end
--- Setup functions
-- @section
--- Initial setup.
-- Must be called during `on_init` **before** any structures are built.
--
-- If adding the module to an existing mod, this must be called in `on_configuration_changed` for that version as well.
--
-- This function can also be used to wipe all GUI filters for all players.
function flib_gui.init()
if not global.__flib then
global.__flib = {gui={}}
else
global.__flib.gui = {}
for _, data in pairs(handler_lookup) do
data.filters = {}
end
end
end
--- Generate template and handler lookup tables.
-- Must be called during `on_init` **after** @{gui.init}, and during `on_init` and `on_load` **after** all templates and
-- handlers have been added, but **before** any structures are built.
function flib_gui.build_lookup_tables()
generate_template_lookup(templates, "")
-- go one level deep before calling the function, to avoid adding an unnecessary prefix to all group names
for k, v in pairs(handlers) do
generate_handler_lookup(v, k, {})
end
if global.__flib and global.__flib.gui then
generate_filter_lookup()
end
end
--- Purge all filters tied to non-existent handlers from `global`.
-- Must be called during `on_configuration_changed`.
-- This function is necessary in order to prevent crashes when a handler was removed between mod versions, but still has
-- filters assigned to it stored in `global`.
function flib_gui.check_filter_validity()
local filters_table = global.__flib.gui
for event_name, event_filters in pairs(filters_table) do
for player_index, player_filters in pairs(event_filters) do
if player_index ~= "__size" then
for filter, handler_name in pairs(player_filters) do
if filter ~= "__size" then
local handler_data = handler_lookup[handler_name]
if not handler_data then
player_filters[filter] = nil
player_filters.__size = player_filters.__size - 1
end
end
end
if player_filters.__size == 0 then
event_filters[player_index] = nil
event_filters.__size = event_filters.__size - 1
if event_filters.__size == 0 then
filters_table[event_name] = nil
end
end
end
end
end
end
--- Register handlers for all GUI events to pass through the module.
-- This will loop through all GUI-related `defines.events` events and register them to @{gui.dispatch_handlers}.
--
-- This function should be called in the root scope.
-- @usage
-- -- register handlers for all GUI events
-- gui.register_handlers()
--
-- -- overwrite a handler to add custom logic
-- event.on_gui_opened(function(e)
-- -- pass through the GUI module
-- if not gui.dispatch_handlers(e) then
-- -- run our custom logic if no handlers were dispatched
-- inventory.on_gui_opened(e)
-- end
-- end)
function flib_gui.register_handlers()
for name, id in pairs(defines.events) do
if string_sub(name, 1, 6) == "on_gui" then
script.on_event(id, flib_gui.dispatch_handlers)
end
end
end
--- Add content to the @{gui.templates} table.
-- The table you provide will be merged with the current contents of the table.
--
-- This table must be complete **before** @{gui.build_lookup_tables} is run, and must not be changed afterwards.
--
-- **NOTE:** In order to be detected properly, a template must include either a `type` key or another `template` key.
-- If both of these are omitted, the template will not be added to the lookup table and will be unusable.
-- @tparam table input
-- @see gui.templates
function flib_gui.add_templates(input)
templates = table.deep_merge{templates, input}
-- because the reference is lost...
flib_gui.templates = templates
end
--- Add content to the @{gui.handlers} table.
-- The table you provide will be merged with the current contents of the table.
--
-- This table must be complete **before** @{gui.build_lookup_tables} is run, and must not be changed afterwards.
-- @tparam table input
-- @see gui.handlers
function flib_gui.add_handlers(input)
handlers = table.deep_merge{handlers, input}
-- because the reference is lost...
flib_gui.handlers = handlers
end
--- Functions
-- @section
-- navigate a structure to build a GUI
local function recursive_build(parent, structure, output, filters, player_index)
-- load template
local structure_template = structure.template
if structure_template then
local loaded_template_names = {}
-- recursively apply templates until there are none left
while structure_template do
if loaded_template_names[structure_template] then
error("Template loop detected in ["..structure_template.."]")
end
loaded_template_names[structure_template] = true
structure.template = nil
for k,v in pairs(template_lookup[structure_template]) do
structure[k] = structure[k] or v
end
structure_template = structure.template
end
end
-- process structure
local elem
local structure_type = structure.type
if structure_type == "condition" then
if structure.condition then
-- add children
local children = structure.children
if children then
for i=1,#children do
output, filters = recursive_build(parent, children[i], output, filters, player_index)
end
end
end
elseif structure_type == "tab-and-content" then
local tab, content
output, filters, tab = recursive_build(parent, structure.tab, output, filters, player_index)
output, filters, content = recursive_build(parent, structure.content, output, filters, player_index)
parent.add_tab(tab, content)
else
-- create element
elem = parent.add(structure)
-- apply style modifications
if structure.style_mods then
for k, v in pairs(structure.style_mods) do
elem.style[k] = v
end
end
-- apply modifications
if structure.elem_mods then
for k, v in pairs(structure.elem_mods) do
elem[k] = v
end
end
-- register handlers
if structure.handlers then
local elem_index = elem.index
local group = handler_groups[structure.handlers]
if not group then error("Invalid GUI handler name ["..structure.handlers.."]") end
for i=1,#group do
local name = group[i]
local saved_filters = filters[name]
if not saved_filters then
filters[name] = {elem_index}
else
saved_filters[#saved_filters+1] = elem_index
end
end
end
-- add to output table
if structure.save_as then
-- recursively create tables as needed
local prev = output
local prev_key
local nav
for key in string_gmatch(structure.save_as, "([^%.]+)") do
prev = prev_key and prev[prev_key] or prev
nav = prev[key]
if nav then
prev = nav
else
prev[key] = {}
prev_key = key
end
end
prev[prev_key] = elem
end
-- add children
local children = structure.children
if children then
for i=1,#children do
output, filters = recursive_build(elem, children[i], output, filters, player_index)
end
end
end
return output, filters, elem
end
--- Build a GUI structure.
-- @tparam LuaGuiElement parent
-- @tparam GuiStructure[] structures
-- @treturn GuiOutputTable output
-- @treturn GuiOutputFiltersTable filters
-- @usage
-- gui.build(player.gui.screen, {
-- {type="frame", direction="vertical", handlers="window", save_as="window", children={
-- -- titlebar
-- {type="flow", save_as="titlebar_flow", children={
-- {type="label", style="frame_title", caption="Menu", elem_mods={ignored_by_interaction=true}},
-- {type="empty-widget", style="flib_titlebar_drag_handle", elem_mods={ignored_by_interaction=true}},
-- {type="condition", condition=(not is_dialog_frame), children={
-- {template="frame_action_button",
-- sprite="utility/close_white",
-- handlers="titlebar.close_button",
-- save_as="titlebar.close_button"
-- }
-- }}
-- }},
-- {type="frame", style="inside_shallow_frame_with_padding", children={
-- {type="table", style="slot_table", column_count=10, save_as="content.slot_table"}
-- }},
-- {type="condition", condition=is_dialog_frame, children={
-- {type="flow", style="dialog_buttons_horizontal_flow", children={
-- {type="button", style="back_button", caption={"gui.back"}, handlers="footer.back_button"},
-- {type="empty-widget",
-- style="flib_dialog_footer_drag_handle",
-- style_mods={right_margin=0},
-- save_as="footer.drag_handle"
-- }
-- }}
-- }}
-- }}
-- })
function flib_gui.build(parent, structures)
local output = {}
local filters = {}
local player_index = parent.player_index or parent.player.index
for i=1,#structures do
output, filters = recursive_build(
parent,
structures[i],
output,
filters,
player_index
)
end
for name, filters_table in pairs(filters) do
flib_gui.update_filters(name, player_index, filters_table, "add")
end
return output, filters
end
--- Dispatch GUI handlers for the given event.
-- Only needed if not using @{gui.register_handlers} or if overriding a handler registered using that function.
-- @tparam Concepts.EventData event_data
-- @treturn boolean If a handler was dispatched.
-- @usage
-- event.on_gui_opened(function(e)
-- -- dispatch any matching handlers
-- if not gui.dispatch_handlers(e) then
-- -- run custom logic if no handlers were dispatched
-- inventory.on_gui_opened(e)
-- end
-- end)
function flib_gui.dispatch_handlers(event_data)
if not event_data.element or not event_data.player_index then return false end
local event_filters = global.__flib.gui[event_data.name]
if not event_filters then return false end
local player_filters = event_filters[event_data.player_index]
if not player_filters then return false end
local element = event_data.element
local element_name = string_gsub(element.name, "__.*", "")
local handler_name = player_filters[element.index] or player_filters[element_name]
if handler_name then
handler_lookup[handler_name].handler(event_data)
return true
else
return false
end
end
--- Add or remove GUI filters to or from a handler or group of handlers.
-- When destroying a GUI element with a filter, be certain to call this function destroying that filter, to avoid
-- memory leaks.
-- @tparam string name The handler name, or group name.
-- @tparam number player_index
-- @tparam GuiFilter[]|nil filters An array of filters, or `nil` to clear all filters when in `remove` mode.
-- @tparam string mode One of "add" or "remove".
-- @usage
-- -- add a filter to a group of events
-- gui.update_filters("main.content.inventory_button", player_index, {"demo_inventory_button"}, "add")
-- -- remove a filter from a group of events
-- gui.update_filters("main.content.inventory_button", player_index, {"demo_inventory_button"}, "remove")
-- -- remove all filters tied to a group of events
-- gui.update_filters("main.content.inventory_button", player_index, nil, "remove")
-- -- add a filter to a specific event
-- gui.update_filters("main.titlebar.drag_handle.on_gui_click", player_index, {elems.drag_handle.index}, "add")
function flib_gui.update_filters(name, player_index, filters, mode)
local handler_names = handler_groups[name] or {name}
for i = 1, #handler_names do
local handler_name = handler_names[i]
local handler_data = handler_lookup[handler_name]
if not handler_data then error("GUI handler ["..handler_name.."] does not exist!") end
local id = handler_data.id
local handler_filters = handler_data.filters
-- saved filters table (in global)
local __gui = global.__flib.gui
local saved_event_filters = __gui[id]
if not saved_event_filters then
__gui[id] = {__size=1, [player_index]={__size=0}}
saved_event_filters = __gui[id]
end
local saved_player_filters = saved_event_filters[player_index]
if not saved_player_filters then
saved_event_filters[player_index] = {__size=0}
saved_event_filters.__size = saved_event_filters.__size + 1
saved_player_filters = saved_event_filters[player_index]
end
-- handler filters table (in lookup)
local handler_player_filters = handler_filters[player_index]
if not handler_player_filters then
handler_filters[player_index] = {__size=0}
handler_player_filters = handler_filters[player_index]
end
-- update filters
if mode == "add" then
for _, filter in pairs(filters) do
saved_player_filters[filter] = handler_name
saved_player_filters.__size = saved_player_filters.__size + 1
handler_player_filters[filter] = filter
handler_player_filters.__size = handler_player_filters.__size + 1
end
elseif mode == "remove" then
-- if a filters table wasn't provided, remove all of them
for key, filter in pairs(filters or handler_player_filters) do
if key ~= "__size" then
saved_player_filters[filter] = nil
saved_player_filters.__size = saved_player_filters.__size - 1
handler_player_filters[filter] = nil
handler_player_filters.__size = handler_player_filters.__size - 1
end
end
-- clean up empty tables
if saved_player_filters.__size == 0 then
saved_event_filters[player_index] = nil
saved_event_filters.__size = saved_event_filters.__size - 1
if saved_event_filters.__size == 0 then
__gui[id] = nil
end
end
if handler_player_filters.__size == 0 then
handler_filters[player_index] = nil
end
else
error("Invalid GUI filter update mode ["..mode.."]")
end
end
end
--- Remove all GUI filters for the given player.
-- @tparam number player_index
function flib_gui.remove_player_filters(player_index)
for group_name in pairs(handler_groups) do
-- check for a level-1 group to minimize calls to update_filters()
if not string.find(group_name, "%.") then
flib_gui.update_filters(group_name, player_index, nil, "remove")
end
end
end
--- Fields
-- @section
--- GUI handlers, built using @{gui.add_handlers}.
-- @usage
-- -- add handlers
-- gui.add_handlers{
-- -- you can organize the handlers however you like
-- base = {
-- titlebar = {
-- -- this is a handler group for a specific GUI element
-- close_button = {
-- -- name of `defines.events` event -> handler function
-- on_gui_click = function(e)
-- log(serpent.block(e))
-- end
-- }
-- }
-- }
-- }
--
-- -- use the handlers
-- gui.build(player.gui.screen, {
-- {type="sprite-button",
-- style="frame_action_button",
-- sprite="utility/close_white",
-- handlers="base.titlebar.close_button"
-- }
-- })
flib_gui.handlers = handlers
--- One-dimensional handler lookup table, generated using @{gui.build_lookup_tables}.
-- This is what @{gui.dispatch_handlers} uses to retrieve and dispatch handlers tied to certain elements.
-- Each value is a table containing the event ID, handler, groups that handler belongs to, and a mapping of the GUI
-- filters currently assigned to the handler.
-- @usage
-- -- given:
-- gui.add_handlers{
-- base = {
-- titlebar = {
-- close_button = {
-- on_gui_click = function(e)
-- log(serpent.block(e))
-- end
-- }
-- }
-- }
-- }
-- gui.build(player.gui.screen, {
-- {type="sprite-button",
-- style="frame_action_button",
-- sprite="utility/close_white",
-- handlers="base.titlebar.close_button"
-- }
-- })
--
-- -- contents of gui.handler_lookup will be:
-- {
-- ["base.titlebar.close_button.on_gui_click"] = {
-- id = defines.events.on_gui_click,
-- handler = function(e)
-- __DebugAdapter.print(e)
-- end,
-- groups = {
-- "base",
-- "base.titlebar",
-- "base.titlebar.close_button"
-- },
-- filters = {
-- [1] = { -- the player's index
-- __size = 1,
-- [5] = 5 -- the element's index, as both the key and the value
-- }
-- }
-- }
-- }
flib_gui.handler_lookup = handler_lookup
--- Mapping of group names to all handlers belonging to them, generated using @{gui.build_lookup_tables}.
-- This is what @{gui.build} uses to find handler groups when using the `handlers` parameter in a @{GuiStructure}.
-- @usage
-- -- given:
-- gui.add_handlers{
-- base = {
-- titlebar = {
-- close_button = {
-- on_gui_click = function(e)
-- log(serpent.block(e))
-- end,
-- my_custom_event = {id=constants.my_custom_event, handler=function(e)
-- log(serpent.block(e))
-- }
-- }
-- },
-- content = {
-- item_button = {
-- on_gui_click = function(e)
-- log(serpent.block(e))
-- end
-- }
-- }
-- }
-- }
--
-- -- contents of gui.handler_groups will be:
-- {
-- ["base"] = {
-- "base.titlebar.close_button.on_gui_click",
-- "base.titlebar.close_button.my_custom_event",
-- "base.content.item_button.on_gui_click"
-- },
-- ["base.titlebar"] = {
-- "base.titlebar.close_button.on_gui_click",
-- "base.titlebar.close_button.my_custom_event"
-- },
-- ["base.titlebar.close_button"] = {
-- "base.titlebar.close_button.on_gui_click",
-- "base.titlebar.close_button.my_custom_event"
-- },
-- ["base.content"] = {
-- "base.content.item_button.on_gui_click"
-- },
-- ["base.content.item_button"] = {
-- "base.content.item_button.on_gui_click"
-- }
-- }
flib_gui.handler_groups = handler_groups
--- GUI templates, built using @{gui.add_templates}.
-- @usage
-- -- add content to the table
-- gui.add_templates{
-- -- templates are usually defined as GuiStructures
-- frame_action_button = {type="sprite-button", style="frame_action_button", mouse_button_filter={"left"}},
-- -- you can divide and organize templates however you wish
-- pushers = {
-- horizontal = {type="empty-widget", style_mods={horizontally_stretchable=true}},
-- vertical = {type="empty-widget", style_mods={vertically_stretchable=true}}
-- },
-- -- templates can also be functions
-- list_box_with_label = function(name)
-- return
-- {type="flow", direction="vertical", children={
-- {type="label", style="bold_label", caption={"my-listbox-labels."..name}, save_as="listboxes."..name..".label"},
-- {type="list-box", save_as="listboxes."..name..".list_box"}
-- }}
-- end
-- }
--
-- -- use the templates
-- gui.build(player.gui.screen, {
-- -- use GuiStructure templates using the "template" parameter
-- {template="pushers.horizontal"},
-- {template="frame_action_button", sprite="utility/close_white"},
-- -- use function templates by calling them directly
-- -- you do not necessarily need to keep function templates in the `templates` table, but the module supports doing so
-- gui.templates.list_box_with_label("ingredients"),
-- gui.templates.list_box_with_label("products")
-- })
flib_gui.templates = templates
--- One-dimensional template lookup table, generating using @{gui.build_lookup_tables}.
-- This is what @{gui.build} uses to find templates when using the `templates` parameter in a @{GuiStructure}.
-- @usage
-- -- given:
-- gui.add_templates{
-- frame_action_button = {type="sprite-button", style="frame_action_button", mouse_button_filter={"left"}},
-- pushers = {
-- horizontal = {type="empty-widget", style_mods={horizontally_stretchable=true}},
-- vertical = {type="empty-widget", style_mods={vertically_stretchable=true}}
-- }
-- }
--
-- -- contents of template_lookup will be:
-- {
-- ["frame_action_button"] = {type="sprite-button", style="frame_action_button", mouse_button_filter={"left"}},
-- ["pushers.horizontal"] = {type="empty-widget", style_mods={horizontally_stretchable=true}},
-- ["pushers.vertical"] = {type="empty-widget", style_mods={vertically_stretchable=true}}
-- }
flib_gui.template_lookup = template_lookup
return flib_gui
--- Concepts
-- @section
--- An index or string used for filtering GUI handlers on specific elements.
-- Defined as one of the following:
-- <ul>
-- <li>A @{string} corresponding to an element's name. Partial names may be matched by separating the common section
-- from the unique section with two underscores `__`.</li>
-- <li>A @{uint} corresponding to an element's index.</li>
-- </ul>
-- @Concept GuiFilter
--- A series of nested tables used to build a GUI.
-- This is an extension of @{LuaGuiElement}, providing new features and options.
--
-- This inherits all required properties from its base @{LuaGuiElement}, i.e. if the `type` field is
-- `sprite-button`, the @{GuiStructure} must contain all the fields that a `sprite-button` @{LuaGuiElement} requires.
--
-- There are two new types that are exposed, each of which restrict what parameters can be added:
-- <ul>
-- <li><strong>condition:</strong> Accepts the `condition` and `children` parameters only.</li>
-- <li><strong>tab-and-content:</strong> Accepts the `tab` and `content` parameters only.</li>
-- </ul>
--
-- There are a number of new fields that can be applied to a @{GuiStructure} depending on the type:
--
-- **_template_**
--
-- A @{string} corresponding to a @{GuiStructure} in the @{gui.template_lookup} table. The contents of this "template"
-- will be used as a base, and any other paramters in this @{GuiStructure} will overwrite / add to this base.
--
-- **_condition_**
--
-- For `condition` types only. If true, the children of this @{GuiStructure} will be added to the parent of this
-- @{GuiStructure}. If false, they will not.
--
-- **_tab_**
--
-- For `tab-and-content` types only. A @{GuiStructure} defining a tab to be placed in a tabbed-pane.
--
-- **_content_**
--
-- For `tab-and-content` types only. A @{GuiStructure} defining the content that will be shown when the corresponding
-- tab is active.
--
-- **_style_mods_**
--
-- A key -> value dictionary defining modifications to make to the element's style. Available properties are listed in
-- @{LuaStyle}.
--
-- **_elem_mods_**
--
-- A key -> value dictionary defining modifications to make to the element. Available properties are listed in
-- @{LuaGuiElement}.
--
-- **_handlers_**
--
-- A @{string} corresponding to an item in the @{gui.handler_groups} table. The element will be registered to the
-- handlers in that group, and when the events are raised by the game relating to this element, the corresponding
-- handlers will be dispatched.
--
-- **_save_as_**
--
-- A @{string} defining a table path to save this element to, in the first return value of @{gui.build}. This is a
-- dot-deliminated list of nested table names, followed by a key to save the element as. The module will construct the
-- output table dynamically based on the contents of `save_as` throughout the structure.
--
-- **_children_**
--
-- An array of @{GuiStructure} that will be added as children of this element.
-- @usage
-- {type="frame", direction="vertical", handlers="window", save_as="window", children={
-- -- titlebar
-- {type="flow", save_as="titlebar_flow", children={
-- {type="label", style="frame_title", caption="Menu", elem_mods={ignored_by_interaction=true}},
-- {type="empty-widget", style="flib_titlebar_drag_handle", elem_mods={ignored_by_interaction=true}},
-- {type="condition", condition=(not is_dialog_frame), children={
-- {template="frame_action_button",
-- sprite="utility/close_white",
-- handlers="titlebar.close_button",
-- save_as="titlebar.close_button"
-- }
-- }}
-- }},
-- {type="frame", style="inside_shallow_frame_with_padding", children={
-- {type="table", style="slot_table", column_count=10, save_as="content.slot_table"}
-- }},
-- {type="condition", condition=is_dialog_frame, children={
-- {type="flow", style="dialog_buttons_horizontal_flow", children={
-- {type="button", style="back_button", caption={"gui.back"}, handlers="footer.back_button"},
-- {type="empty-widget",
-- style="flib_dialog_footer_drag_handle",
-- style_mods={right_margin=0},
-- save_as="footer.drag_handle"
-- }
-- }}
-- }}
-- }}
-- @Concept GuiStructure
--- First output of @{gui.build}, containing saved elements.
-- The layout of this table is defined in the @{GuiStructure} using the `save_as` parameter. Consists of nested tables
-- and key -> @{LuaGuiElement} pairs.
-- @Concept GuiOutputTable
--- Second output of @{gui.build}, containing a handler_name -> filters mapping.
-- This is useful for knowing which filters are assigned to which handlers for this specific structure, so you can
-- remove them later using @{gui.update_filters}.
-- @Concept GuiOutputFiltersTable
-- @usage
-- {
-- ["window.on_gui_closed"] = {23},
-- ["content_pane.ingredients_list.ingredient_button.on_gui_click"] = {"demo_ingredient_button", 30},
-- ["titlebar.close_button.on_gui_click"] = {21}
-- }
|
require("prototypes.entity.entity")
require("prototypes.item.alien-economy")
require("prototypes.item.alien-components")
require("prototypes.item.alien-warfare")
require("prototypes.item.alien-module")
require("prototypes.item-group.item-groups-module")
require("prototypes.recipe.alien-module")
require("prototypes.recipe.alien-warfare")
require("prototypes.technology.technology")
require("prototypes.sounds")
local amount_setting = settings.startup["alien-module-drop-amount"].value / 100
function AddLootToEntity(entityType, entityName, probability, countMin, countMax)
if data.raw[entityType] ~= nil then
if data.raw[entityType][entityName] ~= nil then
if data.raw[entityType][entityName].loot == nil then
data.raw[entityType][entityName].loot = {}
end
table.insert(data.raw[entityType][entityName].loot, { item = "artifact-ore", probability = probability, count_min = countMin, count_max = math.floor(countMax + 0.5) })
end
end
end
local function AddLootToVanillaEnemies()
local SMALL_LOOT_PROBABILITY = 0.33 * amount_setting
local MEDIUM_LOOT_PROBABILITY = 0.66 * amount_setting
local BIG_LOOT_PROBABILITY = 0.83 * amount_setting
local ONE_PROBABILITY = 1 * amount_setting
AddLootToEntity("unit", "small-spitter", SMALL_LOOT_PROBABILITY, 1, 1)
AddLootToEntity("unit", "small-biter", SMALL_LOOT_PROBABILITY, 1, 1)
AddLootToEntity("unit", "medium-spitter", MEDIUM_LOOT_PROBABILITY, 1, 2)
AddLootToEntity("unit", "medium-biter", MEDIUM_LOOT_PROBABILITY, 1, 2)
AddLootToEntity("unit", "big-spitter", BIG_LOOT_PROBABILITY, 1, 5)
AddLootToEntity("unit", "big-biter", BIG_LOOT_PROBABILITY, 1, 5)
AddLootToEntity("unit", "behemoth-spitter", ONE_PROBABILITY, 2, 20)
AddLootToEntity("unit", "behemoth-biter", ONE_PROBABILITY, 2, 20)
AddLootToEntity("turret", "little-worm-turret", ONE_PROBABILITY, 1, 5)
AddLootToEntity("turret", "medium-worm-turret", ONE_PROBABILITY, 1, 10)
AddLootToEntity("turret", "big-worm-turret", ONE_PROBABILITY, 1, 25)
AddLootToEntity("turret", "behemoth-worm-turret", ONE_PROBABILITY, 10, 25)
AddLootToEntity("unit-spawner", "biter-spawner", ONE_PROBABILITY, 20, 50)
AddLootToEntity("unit-spawner", "spitter-spawner", ONE_PROBABILITY, 20, 50)
end
-- This is for the Natural Expansion Mod
local function AddLootToNEEnemies()
for i = 1, 20 do
local loot_probability = amount_setting * math.min(i * 0.04, 1) -- 80 % at highest tier
local max_loot_amount = math.floor(math.max(i * 0.101, 1))
AddLootToEntity("unit", "ne-biter-breeder-" .. i, loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "ne-biter-fire-" .. i, loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "ne-biter-fast-" .. i, loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "ne-biter-wallbreaker-" .. i, loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "ne-biter-tank-" .. i, loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "ne-spitter-breeder-" .. i, loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "ne-spitter-fire-" .. i, loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "ne-spitter-ulaunch-" .. i, loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "ne-spitter-webshooter-" .. i, loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "ne-spitter-mine-" .. i, loot_probability, 1, max_loot_amount)
end
for i = 2, 3 do
local MEDIUM_LOOT_PROBABILITY = 0.5 * amount_setting
local BIG_LOOT_PROBABILITY = 1 * amount_setting
AddLootToEntity("unit", "small-spitter-Mk" .. i, MEDIUM_LOOT_PROBABILITY, 1, 1)
AddLootToEntity("unit", "small-biter-Mk" .. i, MEDIUM_LOOT_PROBABILITY, 1, 1)
AddLootToEntity("unit", "medium-spitter-Mk" .. i, BIG_LOOT_PROBABILITY, 1, 2)
AddLootToEntity("unit", "medium-biter-Mk" .. i, BIG_LOOT_PROBABILITY, 1, 2)
AddLootToEntity("unit", "big-spitter-Mk" .. i, BIG_LOOT_PROBABILITY, 1, 5)
AddLootToEntity("unit", "big-biter-Mk" .. i, BIG_LOOT_PROBABILITY, 1, 5)
end
-- boss unit from NE
AddLootToEntity("unit", "ne-biter-megladon", 1 * amount_setting, 50, 200)
end
-- Rampant mod enemies
local function AddLootToRampantEnemies()
for t = 1, 10 do
for v = 1, 20 do
local loot_probability = amount_setting * math.min(t * 0.08, 1) -- 80 % at highest tier
local max_loot_amount = 1
AddLootToEntity("unit", "neutral-biter-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "neutral-spitter-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "acid-biter-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "acid-spitter-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "physical-biter-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "electric-biter-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "suicide-biter-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "nuclear-biter-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "fire-biter-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "fire-spitter-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "inferno-spitter-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "troll-biter-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "troll-spitter-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "fast-biter-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "fast-spitter-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "laser-biter-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "laser-spitter-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "wasp-spitter-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "spawner-spitter-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("unit", "spawner-biter-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("turret", "neutral-worm-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("turret", "acid-worm-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("turret", "physical-worm-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("turret", "electric-worm-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("turret", "suicide-worm-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("turret", "nuclear-worm-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("turret", "fire-worm-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("turret", "inferno-worm-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("turret", "troll-worm-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("turret", "fast-worm-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("turret", "laser-worm-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("turret", "wasp-worm-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
AddLootToEntity("turret", "spawner-worm-v" .. v .. "-t" .. t .. "-rampant", loot_probability, 1, max_loot_amount)
end
end
end
local function AddLootToSchallEndgameEnemies()
local loot_probability = 1 * amount_setting
--category 5 to 15 (behemoth = 4)
local units = data.raw.unit
for n = 5, 15 do
local loot_min = math.min(n * 1, 15)
local loot_max = math.min(n * 4, 35)
local biter_name = "Schall-category-"..n.."-biter"
local spitter_name = "Schall-category-"..n.."-spitter"
if units[biter_name] then
AddLootToEntity("unit", biter_name, loot_probability, loot_min, loot_max)
end
if units[spitter_name] then
AddLootToEntity("unit", spitter_name, loot_probability, loot_min, loot_max)
end
end
end
if amount_setting > 0 then
AddLootToVanillaEnemies()
AddLootToNEEnemies()
AddLootToRampantEnemies()
AddLootToSchallEndgameEnemies()
end
|
-- Says hello to the name entered in the text box on a button click
-- Create the controls
local vbox = as3.class.mx.containers.VBox.new()
local label = as3.class.mx.controls.Label.new()
local input = as3.class.mx.controls.TextInput.new()
local button = as3.class.mx.controls.Button.new()
label.text = "Name:"
button.label = "Say Hello"
-- Add a button listener to pop up an alert saying hello
button.addEventListener(as3.class.flash.events.MouseEvent.CLICK,
function (e)
as3.class.mx.controls.Alert.show("Hello " .. as3.tolua(input.text), as3.type(e))
end, false, 0, true) -- set useWeakReference=true so listener doesn't keep button reference
-- Add all the controls to the canvas in a VBox
vbox.addChild(label)
vbox.addChild(input)
vbox.addChild(button)
canvas.addChild(vbox)
|
local test = require('test')
local Matrix4x3 = Matrix4x3
local Vector3 = Vector3
test.suite('Matrix4x3 Library')
test.test('creation', function()
local m = Matrix4x3.new()
test.assert_equal(#m, 12)
test.expect_equal(m:get(1, 1), 1)
test.expect_equal(m:get(1, 2), 0)
test.expect_equal(m:get(1, 3), 0)
test.expect_equal(m:get(2, 1), 0)
test.expect_equal(m:get(2, 2), 1)
test.expect_equal(m:get(2, 3), 0)
test.expect_equal(m:get(3, 1), 0)
test.expect_equal(m:get(3, 2), 0)
test.expect_equal(m:get(3, 3), 1)
test.expect_equal(m:get(4, 1), 0)
test.expect_equal(m:get(4, 2), 0)
test.expect_equal(m:get(4, 3), 0)
local m = Matrix4x3.new(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
test.assert_equal(#m, 12)
test.expect_equal(m:get(1, 1), 1)
test.expect_equal(m:get(1, 2), 2)
test.expect_equal(m:get(1, 3), 3)
test.expect_equal(m:get(2, 1), 4)
test.expect_equal(m:get(2, 2), 5)
test.expect_equal(m:get(2, 3), 6)
test.expect_equal(m:get(3, 1), 7)
test.expect_equal(m:get(3, 2), 8)
test.expect_equal(m:get(3, 3), 9)
test.expect_equal(m:get(4, 1), 10)
test.expect_equal(m:get(4, 2), 11)
test.expect_equal(m:get(4, 3), 12)
local m = Matrix4x3.new{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
test.assert_equal(#m, 12)
test.expect_equal(m:get(1, 1), 1)
test.expect_equal(m:get(1, 2), 2)
test.expect_equal(m:get(1, 3), 3)
test.expect_equal(m:get(2, 1), 4)
test.expect_equal(m:get(2, 2), 5)
test.expect_equal(m:get(2, 3), 6)
test.expect_equal(m:get(3, 1), 7)
test.expect_equal(m:get(3, 2), 8)
test.expect_equal(m:get(3, 3), 9)
test.expect_equal(m:get(4, 1), 10)
test.expect_equal(m:get(4, 2), 11)
test.expect_equal(m:get(4, 3), 12)
test.expect_error(Matrix4x3.new, 1, 2)
end)
test.test('size', function()
local m = Matrix4x3.new()
test.expect_equal(#m, 12)
test.expect_equal(m:rows(), 4)
test.expect_equal(m:columns(), 3)
end)
test.test('get row', function()
local m = Matrix4x3.new(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
test.assert_equal(m:get(1), Vector3.new(1, 2, 3))
test.assert_equal(m:get(2), Vector3.new(4, 5, 6))
test.assert_equal(m:get(3), Vector3.new(7, 8, 9))
test.assert_equal(m:get(4), Vector3.new(10, 11, 12))
end)
test.test('equality', function()
local a = Matrix4x3.new(3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
local b = Matrix4x3.new(5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
test.assert_not_equal(a, b)
b = Matrix4x3.new(3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
test.assert_equal(a, b)
end)
test.test('table as parameter', function()
test.assert_equal(Matrix4x3.get({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, 4, 3), 12)
end)
test.test('table', function()
local m = Matrix4x3.new{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
local t = m:table()
test.assert_equal(#t, 12)
test.expect_equal(t[1], 1)
test.expect_equal(t[2], 2)
test.expect_equal(t[3], 3)
test.expect_equal(t[4], 4)
test.expect_equal(t[5], 5)
test.expect_equal(t[6], 6)
test.expect_equal(t[7], 7)
test.expect_equal(t[8], 8)
test.expect_equal(t[9], 9)
test.expect_equal(t[10], 10)
test.expect_equal(t[11], 11)
test.expect_equal(t[12], 12)
end)
test.test('set', function()
local m = Matrix4x3.new()
m:set(1, 1, 1)
m:set(1, 2, 2)
m:set(1, 3, 3)
m:set(2, 1, 4)
m:set(2, 2, 5)
m:set(2, 3, 6)
m:set(3, 1, 7)
m:set(3, 2, 8)
m:set(3, 3, 9)
m:set(4, 1, 10)
m:set(4, 2, 11)
m:set(4, 3, 12)
test.expect_equal(m:get(1, 1), 1)
test.expect_equal(m:get(1, 2), 2)
test.expect_equal(m:get(1, 3), 3)
test.expect_equal(m:get(2, 1), 4)
test.expect_equal(m:get(2, 2), 5)
test.expect_equal(m:get(2, 3), 6)
test.expect_equal(m:get(3, 1), 7)
test.expect_equal(m:get(3, 2), 8)
test.expect_equal(m:get(3, 3), 9)
test.expect_equal(m:get(4, 1), 10)
test.expect_equal(m:get(4, 2), 11)
test.expect_equal(m:get(4, 3), 12)
end)
test.test('setAll', function()
local m = Matrix4x3.new()
m:setAll(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
test.expect_equal(m:get(1, 1), 1)
test.expect_equal(m:get(1, 2), 2)
test.expect_equal(m:get(1, 3), 3)
test.expect_equal(m:get(2, 1), 4)
test.expect_equal(m:get(2, 2), 5)
test.expect_equal(m:get(2, 3), 6)
test.expect_equal(m:get(3, 1), 7)
test.expect_equal(m:get(3, 2), 8)
test.expect_equal(m:get(3, 3), 9)
test.expect_equal(m:get(4, 1), 10)
test.expect_equal(m:get(4, 2), 11)
test.expect_equal(m:get(4, 3), 12)
end)
test.test('transpose', function()
local m = Matrix4x3.new(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
m = m:transpose()
test.assert_equal(m:rows(), 3)
test.assert_equal(m:columns(), 4)
test.expect_equal(m:get(1, 1), 1)
test.expect_equal(m:get(1, 2), 4)
test.expect_equal(m:get(1, 3), 7)
test.expect_equal(m:get(1, 4), 10)
test.expect_equal(m:get(2, 1), 2)
test.expect_equal(m:get(2, 2), 5)
test.expect_equal(m:get(2, 3), 8)
test.expect_equal(m:get(2, 4), 11)
test.expect_equal(m:get(3, 1), 3)
test.expect_equal(m:get(3, 2), 6)
test.expect_equal(m:get(3, 3), 9)
test.expect_equal(m:get(3, 4), 12)
end)
test.test('apply', function()
local a = Matrix4x3.new(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
local b = a:apply(function(v, i, r, c) return v + i + r + c end)
test.expect_equal(b:get(1, 1), 4)
test.expect_equal(b:get(1, 2), 7)
test.expect_equal(b:get(1, 3), 10)
test.expect_equal(b:get(2, 1), 11)
test.expect_equal(b:get(2, 2), 14)
test.expect_equal(b:get(2, 3), 17)
test.expect_equal(b:get(3, 1), 18)
test.expect_equal(b:get(3, 2), 21)
test.expect_equal(b:get(3, 3), 24)
test.expect_equal(b:get(4, 1), 25)
test.expect_equal(b:get(4, 2), 28)
test.expect_equal(b:get(4, 3), 31)
end)
test.test('unary minus', function()
local a = Matrix4x3.new(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
a = -a
test.expect_equal(a:get(1, 1), -1)
test.expect_equal(a:get(1, 2), -2)
test.expect_equal(a:get(1, 3), -3)
test.expect_equal(a:get(2, 1), -4)
test.expect_equal(a:get(2, 2), -5)
test.expect_equal(a:get(2, 3), -6)
test.expect_equal(a:get(3, 1), -7)
test.expect_equal(a:get(3, 2), -8)
test.expect_equal(a:get(3, 3), -9)
test.expect_equal(a:get(4, 1), -10)
test.expect_equal(a:get(4, 2), -11)
test.expect_equal(a:get(4, 3), -12)
end)
|
local _, T = ...
if T.Mark ~= 50 then return end
local L, EV, G, api = T.L, T.Evie, T.Garrison, {}
local MISSION_PAGE_FRAME = GarrisonMissionFrame.MissionTab.MissionPage
local SHIP_MISSION_PAGE = GarrisonShipyardFrame.MissionTab.MissionPage
local RefreshActiveMissionsView, activeMissionsHandle
local RefreshAvailMissionsView, availMissionsHandle
local interestMissionsHandle
local Interest_RewardMap = {}
local function SetMissionsFrameTab(id)
local mainFrame = GarrisonMissionFrame
PlaySound("UI_Garrison_Nav_Tabs");
PanelTemplates_SetTab(mainFrame, id);
mainFrame:SelectTab(id);
end
local function abridge(n)
if n < 1e3 then
return ("%d"):format(n)
else
return (L"%sk"):format((n >= 1e5 and "%d" or "%.2g"):format(n/1e3))
end
end
local function oncePerFrame(f)
local ff
local function cf()
ff = nil
f()
end
return function()
if not ff then
ff = true
T.After0(cf)
end
end
end
local function dismissTooltip(self)
if GameTooltip:IsOwned(self) then
GameTooltip:Hide()
end
end
local function dismissTooltipAndHighlight(self)
if GameTooltip:IsOwned(self) then
GameTooltip:Hide()
end
self:GetParent():UnlockHighlight()
end
local function OpenToMission(mi, f1, f2, f3, isResume)
local FRAME, PAGE, _, s1, s2, s3, s4, s5, s6 = GarrisonMissionFrame, MISSION_PAGE_FRAME
if not mi then
return
elseif mi.followerTypeID == 2 then
FRAME, PAGE = GarrisonShipyardFrame, SHIP_MISSION_PAGE
end
if not (f1 or f2 or f3) then
f1, f2, f3 = G.GetMissionParty(mi.missionID)
if not (f1 or f2 or f3) then
f1, f2, f3 = api.roamingParty:GetFollowers()
else
isResume = true
end
end
if (f1 or f2 or f3) then
if not f2 then
f2, f3 = f3
end
if not f1 then
f1, f2, f3 = f2, f3
end
else
isResume = true
end
if isResume then
_, s1 = PlaySound("UI_Garrison_CommandTable_IncreaseSuccess")
_, s2 = PlaySound("UI_Garrison_CommandTable_100Success")
_, s3 = PlaySound("UI_Garrison_Mission_Threat_Countered")
_, s4 = PlaySound("UI_Garrison_CommandTable_AssignFollower")
_, s5 = PlaySound("UI_Garrison_CommandTable_UnassignFollower")
_, s6 = PlaySound("UI_Garrison_CommandTable_ReducedSuccessChance")
end
PlaySound("UI_Garrison_CommandTable_SelectMission")
FRAME.MissionTab.MissionList:Hide()
PAGE:Show()
FRAME:ShowMission(mi)
FRAME.followerCounters = C_Garrison.GetBuffedFollowersForMission(mi.missionID, false)
FRAME.followerTraits = C_Garrison.GetFollowersTraitsForMission(mi.missionID, false)
FRAME:ClearParty()
if C_Garrison.GetNumFollowersOnMission(mi.missionID) > 0 then
local ft = C_Garrison.GetBasicMissionInfo(mi.missionID).followers
for i=1,#ft do
C_Garrison.RemoveFollowerFromMission(mi.missionID, ft[i])
end
end
for i=1, mi.numFollowers do
if f1 then
FRAME:AssignFollowerToMission(PAGE.Followers[i], C_Garrison.GetFollowerInfo(f1))
end
f1, f2, f3 = f2, f3, f1
end
if isResume then
for i = 1, #PAGE.Enemies do
local enemyFrame = PAGE.Enemies[i]
for mechanicIndex = 1, #enemyFrame.Mechanics do
local mech = enemyFrame.Mechanics[mechanicIndex]
mech.Check:SetAlpha(mech.hasCounter and 1 or 0)
mech.Check:SetShown(mech.hasCounter)
mech.Anim:Stop()
end
end
PAGE.RewardsFrame.currentChance = nil
GarrisonMissionPageRewardsFrame_StopUpdate(PAGE.RewardsFrame)
FRAME:UpdateMissionData(PAGE)
PAGE.RewardsFrame.ChanceGlowAnim:Stop()
PAGE.Stage.MissionEnvIcon.Anim:Stop()
end
FRAME:UpdateMissionParty(PAGE.Followers)
FRAME.FollowerList:UpdateFollowers()
for i=1,6 do
s1, s2, s3, s4, s5, s6 = s2, s3, s4, s5, s6, s1 and StopSound(s1)
end
end
local function FollowerTooltip_SetFollower(owner, info, skipDescriptions)
local id = info.followerID
GarrisonFollowerTooltip:ClearAllPoints()
GarrisonFollowerTooltip:SetPoint("TOP", owner, "BOTTOM", 0, -2)
GarrisonFollowerTooltip_Show(info.garrFollowerID or info.followerID,
info.isCollected,
C_Garrison.GetFollowerQuality(id),
C_Garrison.GetFollowerLevel(id),
C_Garrison.GetFollowerXP(id),
C_Garrison.GetFollowerLevelXP(id),
C_Garrison.GetFollowerItemLevelAverage(id),
0,
C_Garrison.GetFollowerAbilityAtIndex(id, 1),
C_Garrison.GetFollowerAbilityAtIndex(id, 2),
C_Garrison.GetFollowerAbilityAtIndex(id, 3),
C_Garrison.GetFollowerAbilityAtIndex(id, 4),
C_Garrison.GetFollowerTraitAtIndex(id, 1),
C_Garrison.GetFollowerTraitAtIndex(id, 2),
C_Garrison.GetFollowerTraitAtIndex(id, 3),
C_Garrison.GetFollowerTraitAtIndex(id, 4),
skipDescriptions)
end
local function FormatCountdown(sec)
if sec >= 3600 then
return (sec % 3600 < 60) and HOUR_ONELETTER_ABBR:format(sec / 3600) or L("%dh %dm"):format(sec / 3600, sec / 60 % 60)
else
return format(SecondsToTimeAbbrev(sec < 0 and 0 or sec))
end
end
local GetAvailableResources do
local numFollowers, garrResources, ctID
local function forget()
numFollowers, garrResources, ctID = nil
end
function GetAvailableResources(ftID, dropCost, missions)
if ftID ~= ctID then
local n, _, r = 0, GetCurrencyInfo(ftID == 1 and GARRISON_CURRENCY or 1101)
for k,v in pairs(G.GetFollowerInfo()) do
if v.isCombat and v.followerTypeID == ftID and (v.status == GARRISON_FOLLOWER_IN_PARTY or v.status == nil) and not T.config.ignore[v.followerID] and not G.GetFollowerTentativeMission(v.followerID) then
n = n + 1
end
end
for i=1,#missions do
local mi = missions[i]
if mi.cost and G.HasTentativeParty(mi.missionID) == mi.numFollowers then
r = r - mi.cost
end
end
numFollowers, garrResources, ctID = n, r, ftID
T.After0(forget)
end
return numFollowers, garrResources - (dropCost or 0)
end
end
MISSION_PAGE_FRAME.StartMissionButton:SetScript("OnClick", function()
if (not MISSION_PAGE_FRAME.missionInfo.missionID) then
return
end
local f1, f2, f3 = G.StartMission(MISSION_PAGE_FRAME.missionInfo.missionID)
api.roamingParty:DropFollowers(f1, f2, f3)
PlaySound("UI_Garrison_CommandTable_MissionStart")
GarrisonMissionFrame:CloseMission()
RefreshAvailMissionsView(true)
if (not GetCVarBitfield("closedInfoFrames", LE_FRAME_TUTORIAL_GARRISON_LANDING)) then
GarrisonLandingPageTutorialBox:Show()
end
end)
do -- CreateLoader(parent, W, G, H)
local fin, N, c = setmetatable({}, {__mode="k"}), 9, "16FF1F1DEDFC9C04F6128CFEE8FF08FD3016FE9B17FF8DD2706F6E"
local function Loader_OnUpdate(self)
if self.job then
local t1, tlim, ok, er, i, x = debugprofilestop(), self.tlim
repeat
if coroutine.status(self.job) ~= "suspended" then
break
end
ok, er, i, x = coroutine.resume(self.job)
local tdiff, stop = debugprofilestop()-t1
t1, tlim, stop = t1+tdiff, tlim-tdiff, tlim < 2*tdiff
until not (i and x) or stop
if not (fin[self.job] or ok) then
if ok ~= nil then
securecall(error, "CO: " .. tostring(er) .. "\n" .. debugstack(self.job))
end
for i=1,#self do
self[i]:SetColorTexture(1, 0.1, 0)
end
return
elseif i and x then
local pg = x <= i and 9 or x > 0 and math.floor(i/x*10) or 0
if pg ~= self.pg then
for i=math.max(1, self.pg or 1), pg do
local si = self[i]
si:SetColorTexture(si.r or 0, si.g or 0, si.b or 0)
end
for i=pg+1, self.pg or 9 do
self[i]:SetColorTexture(0,0,0, 0.25)
end
self.pg = pg
end
self.nf = (self.nf or 0) + 1
return
else
for i=math.max(1, self.pg or 1), 9 do
local si = self[i]
si:SetColorTexture(si.r or 0, si.g or 0, si.b or 0)
end
fin[self.job or 1] = 1
if self.OnFinish then
securecall(self.OnFinish, self, self.nf or 0)
end
self.nf, self.job = 0
if self.animHide then
self.animHide:Stop()
end
end
end
if self.animHide and self:IsVisible() then
self.animHide:Play()
else
self:Hide()
end
end
local function Loader_OnHide(self)
if self.animHide then
self.animHide:Stop()
end
self:SetAlpha(1)
self.nf, self.job = 0
self:Hide()
end
function api.CreateLoader(parent, W, G, H, tlim, animHide)
local WG, loader = W + G, CreateFrame("Frame", nil, parent)
loader.tlim = tlim or 14
loader:SetSize(WG*N-G, H)
loader:Hide()
for i=1,N do
local tex = loader:CreateTexture(nil, "OVERLAY", nil, -8+i)
tex:SetSize(W, H)
local r,g,b = c:match("(%x%x)(%x%x)(%x%x)", 6*i-5)
tex.r, tex.g, tex.b = tonumber(r or 64,16)/255, tonumber(g or 64,16)/255, tonumber(b or 64,16)/255
tex:SetColorTexture(0,0,0, 0.25)
tex:SetPoint("LEFT", WG*(i-1), 0)
loader[i] = tex
end
if animHide then
local ag = loader:CreateAnimationGroup()
local aa = ag:CreateAnimation("Alpha")
aa:SetStartDelay(0.4)
aa:SetFromAlpha(1)
aa:SetToAlpha(0)
aa:SetDuration(0.6)
ag:SetScript("OnFinished", function()
loader:SetAlpha(1)
loader:Hide()
end)
loader.animHide = ag
end
loader:SetScript("OnUpdate", Loader_OnUpdate)
loader:SetScript("OnHide", Loader_OnHide)
return loader
end
end
local missionList = CreateFrame("Frame", "MasterPlanMissionList", GarrisonMissionFrameMissions) do
missionList:SetAllPoints()
local hidden = CreateFrame("Frame", nil, missionList) do
hidden:Hide()
hidden.Tab1, hidden.Tab2 = GarrisonMissionFrameMissionsTab1, GarrisonMissionFrameMissionsTab2
missionList:SetScript("OnShow", function()
GarrisonMissionFrameMissionsTab1:SetParent(hidden)
GarrisonMissionFrameMissionsTab2:SetParent(hidden)
GarrisonMissionFrameMissionsListScrollFrame:SetParent(hidden)
end)
missionList:SetScript("OnHide", function(self)
GarrisonMissionFrameMissionsTab1:SetParent(self:GetParent())
GarrisonMissionFrameMissionsTab2:SetParent(self:GetParent())
GarrisonMissionFrameMissionsListScrollFrame:SetParent(self:GetParent())
end)
end
local ctlContainer = CreateFrame("Frame", nil, missionList) do
missionList.ctlContainer = ctlContainer
ctlContainer:SetPoint("BOTTOMLEFT", GarrisonMissionFrameMissions, "TOPLEFT", 6, 0)
ctlContainer:SetHeight(43)
ctlContainer:Hide()
local t, is, ts = ctlContainer:CreateTexture(nil, "BACKGROUND"), 18, 1/16
t:SetAtlas("Garr_Mission_MaterialFrame")
t:SetTexCoord(0, ts, 0, 1)
t:SetPoint("TOPLEFT")
t:SetPoint("BOTTOMRIGHT", ctlContainer, "BOTTOMLEFT", is, 0)
t = ctlContainer:CreateTexture(nil, "BACKGROUND")
t:SetTexCoord(ts, 1-ts, 0, 1)
t:SetAtlas("Garr_Mission_MaterialFrame")
t:SetPoint("TOPLEFT", is, 0)
t:SetPoint("BOTTOMRIGHT", -is, 0)
t = ctlContainer:CreateTexture(nil, "BACKGROUND")
t:SetTexCoord(1-ts, 1, 0, 1)
t:SetAtlas("Garr_Mission_MaterialFrame")
t:SetPoint("TOPRIGHT")
t:SetPoint("BOTTOMLEFT", ctlContainer, "BOTTOMRIGHT", -is, 0)
local function UpdateWidth(self, elapsed)
local tl = self.timeLeft - elapsed
if tl < 0 then
self:SetWidth(self.goalWidth)
self:SetScript("OnUpdate", nil)
else
local sw, gw = self.startWidth, self.goalWidth
local cw = sw + (gw - sw) * (1-tl*5)
self:SetWidth(cw)
self.timeLeft = tl
end
end
function ctlContainer:SetInnerWidth(width, now)
width = width + 20
if now then
self:SetWidth(width)
self:SetScript("OnUpdate", nil)
else
self.goalWidth, self.startWidth, self.timeLeft = width, self:GetWidth(), 0.2
self:SetScript("OnUpdate", UpdateWidth)
end
end
function ctlContainer:Steal(owner, resident)
if self.resident then
self.resident:ClearAllPoints()
self.resident:Hide()
end
if owner then
self:SetParent(owner)
self:Show()
else
self:Hide()
end
self.resident = resident
if resident then
resident:SetPoint("LEFT", ctlContainer, "LEFT", 10, 0)
resident:SetParent(self)
resident:Show()
self:SetInnerWidth(resident:GetWidth(), true)
end
end
end
end
local hoverFocus = CreateFrame("Frame") do
local OPEN_DELAY, CLOSE_DELAY, CLOSE_GRACE = 0.2, 0.4, 0.5
function hoverFocus:Update(elapsed)
if self.owner then
if not (self.owner:IsVisible() and (self.checkFunc == nil or self.checkFunc(self.owner))) then
self:Close()
end
end
if self.closeOwner then
if self.closeGrace then
local tl = self.closeGrace - elapsed
self.closeGrace = tl > 0 and tl or nil
end
local co, frame = self.closeOwner, self.frame
if co:IsVisible() and (co:IsMouseOver(4,-4,-4,4) or (frame and frame:IsMouseOver(4,-4,-4,4))) then
self.closeDelay = CLOSE_DELAY
else
local dl = self.closeDelay - elapsed
if dl > 0 then
self.closeDelay = dl
else
self:Close()
end
end
end
if self.openOwner then
if self.openOwner:IsVisible() and self.openOwner:IsMouseOver(4,-4,-4,4) then
local dl = self.openDelay - elapsed
if dl > 0 then
self.openDelay = dl
else
self.closeOwner, self.closeDelay, self.closeGrace = self.openOwner, CLOSE_DELAY, CLOSE_GRACE, self.openOwner:Click()
end
else
self.openOwner = nil
end
end
if not (self.owner or self.closeOwner or self.openOwner) then
self:SetScript("OnUpdate", nil)
end
end
function hoverFocus:Close()
if self.closeFunc then
securecall(self.closeFunc, self.owner)
end
self.closeFunc, self.owner, self.closeOwner = nil
end
function hoverFocus:Open(owner, frame, checkFunc, closeFunc)
if self.owner then self:Close() end
self.owner, self.frame, self.closeFunc, self.checkFunc, self.closeOwner, self.openOwner, self.closeGrace = owner, frame, closeFunc, checkFunc
self:SetScript("OnUpdate", self.Update)
end
function hoverFocus:CheckToggle(owner)
if self.owner == owner then
if self.closeOwner == owner and self.closeGrace then
self.closeOwner = nil
else
self:Close()
end
else
return true
end
end
function hoverFocus:DelayOpenClick(owner)
if self.owner ~= owner then
self.openOwner, self.openDelay = owner, OPEN_DELAY
self:SetScript("OnUpdate", self.Update)
end
end
end
local easyDrop = CreateFrame("Frame", "MPDropDown", nil, "UIDropDownMenuTemplate") do
api.easyDrop = easyDrop
function easyDrop:IsOpen(owner)
return self.owner == owner and UIDROPDOWNMENU_OPEN_MENU == self and DropDownList1:IsShown()
end
function easyDrop:Close()
hoverFocus:Close()
end
function easyDrop:CancelOpen(owner)
if hoverFocus.openOwner == owner then
hoverFocus.openOwner = nil
end
end
local function checkMenu()
if UIDROPDOWNMENU_OPEN_MENU == easyDrop and DropDownList1:IsShown() then
DropDownList1.isCounting = nil
return true
end
end
local function closeEasyDrop(owner)
if UIDROPDOWNMENU_OPEN_MENU == easyDrop then
CloseDropDownMenus()
end
if owner.OnEasyDropHide then
securecall(owner.OnEasyDropHide, owner)
end
easyDrop.owner = nil
end
function easyDrop:Open(owner, menu, ...)
self:Close()
hoverFocus:Open(owner, DropDownList1, checkMenu, closeEasyDrop)
self.owner, self.closeOwner, self.openOwner, self.closeGrace = owner
EasyMenu(menu, self, "cursor", 9000, 9000, "MENU", 4)
DropDownList1:ClearAllPoints()
DropDownList1:SetPoint(...)
end
function easyDrop:CheckToggle(owner)
return hoverFocus:CheckToggle(owner)
end
function easyDrop:Toggle(owner, ...)
if hoverFocus:CheckToggle(owner) then
self:Open(owner, ...)
end
end
function easyDrop:DelayOpenClick(owner)
if not self:IsOpen(owner) then
hoverFocus:DelayOpenClick(owner)
end
end
end
local activeUI = CreateFrame("Frame", nil, missionList) do
activeUI:SetSize(880, 22)
activeUI:SetPoint("BOTTOMLEFT", GarrisonMissionFrameMissions, "TOPLEFT", 0, 4)
activeUI:Hide()
activeUI.CompleteAll = CreateFrame("Button", "MPCompleteAll", activeUI, "UIPanelButtonTemplate") do
local b = activeUI.CompleteAll
b:SetSize(200, 26)
b:SetPoint("BOTTOM", -64, 5)
b:SetText(L"Complete All")
b:RegisterForClicks("LeftButtonUp", "RightButtonUp")
local function DissmissHelp(self)
if self.ShowingHelp then
HelpPlate_TooltipHide()
self.ShowingHelp = nil
end
end
b:SetScript("OnLeave", DissmissHelp)
b:SetScript("OnHide", DissmissHelp)
b:SetScript("OnKeyDown", function(self, key)
self:SetPropagateKeyboardInput(key ~= "SPACE")
if key == "SPACE" then
self:Click()
end
end)
end
activeUI.orders = T.CreateLazyItemButton(activeUI, 122514) do
activeUI.orders:SetSize(28, 28)
activeUI.orders:SetPoint("BOTTOMRIGHT", -308, 3)
end
local ctl = CreateFrame("Frame") do
ctl:SetSize(29, 22)
activeUI.waste = CreateFrame("Button", nil, ctl) do
local popup = CreateFrame("Frame", nil, UIParent) do
local f = popup
f:SetFrameStrata("DIALOG")
f:SetSize(260, 68)
f:SetBackdrop({edgeFile="Interface/Tooltips/UI-Tooltip-Border", bgFile="Interface/DialogFrame/UI-DialogBox-Background-Dark", tile=true, edgeSize=16, tileSize=16, insets={left=4,right=4,bottom=4,top=4}})
f:SetBackdropColor(0,0,0, 0.95)
f:SetBackdropBorderColor(0.75,0.75,0.75)
f:SetHitRectInsets(-4, -4, 0, -4)
f:EnableMouse(true)
f:Hide()
local t = f:CreateFontString(nil, "ARTWORK", "GameTooltipHeaderText")
t:SetTextColor(NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b)
t:SetText(L"Require Currency Reward")
t:SetPoint("TOPLEFT", 10, -10)
local s = CreateFrame("Slider", nil, popup)
s:SetSize(236, 17)
s:SetPoint("TOP", 0, -42)
s:SetHitRectInsets(0,0,-10,-10)
s:SetBackdrop({bgFile="Interface\\Buttons\\UI-SliderBar-Background", edgeFile="Interface\\Buttons\\UI-SliderBar-Border", tile=true, edgeSize=8, tileSize=8, insets={left=3,right=3,top=6,bottom=6}})
s:SetThumbTexture("Interface\\Buttons\\UI-SliderBar-Button-Horizontal")
local tt = s:GetThumbTexture()
tt:SetSize(24,32)
tt:SetTexCoord(4/32, 28/32, 0, 1)
s:SetOrientation("HORIZONTAL")
s:SetValue(110)
s:SetMinMaxValues(0, 100)
s:SetValueStep(10)
s:SetObeyStepOnDrag(true)
t = s:CreateTexture(nil, "BACKGROUND")
t:SetHeight(10)
t:SetColorTexture(0, 1, 0)
t:SetAlpha(0.25)
t:SetPoint("LEFT", 3, 0)
t:SetPoint("RIGHT", tt, "CENTER", 0, 0)
t = s:CreateTexture(nil, "BACKGROUND")
t:SetHeight(10)
t:SetColorTexture(1, 0, 0)
t:SetAlpha(0.25)
t:SetPoint("RIGHT", -3, 0)
t:SetPoint("LEFT", tt, "CENTER", 0, 0)
local lo = s:CreateFontString(nil, "ARTWORK", "GameFontDisableSmallLeft")
lo:SetPoint("BOTTOMLEFT", s, "TOPLEFT", 0, 0)
lo:SetText("0%")
local hi = s:CreateFontString(nil, "ARTWORK", "GameFontDisableSmallLeft")
hi:SetPoint("BOTTOMRIGHT", s, "TOPRIGHT", 4, 0)
hi:SetText("100%")
local vt = s:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
vt:SetPoint("BOTTOM", tt, "TOP", 0, -6)
s:SetScript("OnValueChanged", function(_self, v, user)
if user then
T.config.currencyWasteThreshold = 1-v/100
end
vt:SetText(v .. "%")
hi:SetAlpha(v < 90 and 1 or 0)
lo:SetAlpha(v > 10 and 1 or 0)
end)
s:SetScript("OnShow", function(self)
self:SetValue((1-T.config.currencyWasteThreshold)*100)
end)
s:SetValue(0)
end
local b = activeUI.waste
b:SetSize(20, 20)
b:SetPoint("LEFT", 4, 0)
b:SetNormalTexture("Interface\\Minimap\\ObjectIcons")
b:SetDisabledTexture("Interface\\Minimap\\ObjectIcons")
b:SetHighlightTexture("Interface\\Minimap\\ObjectIcons")
local nt = b:GetNormalTexture()
nt:SetTexCoord(0, 32/256, 64/256, 96/256)
nt:SetVertexColor(0.8, 0.8, 0.8)
local dt = b:GetDisabledTexture()
dt:SetTexCoord(0, 32/256, 64/256, 96/256)
dt:SetDesaturated(true)
dt:SetVertexColor(0.8, 0.8, 0.8)
local ht = b:GetHighlightTexture()
ht:SetTexCoord(0, 32/256, 64/256, 96/256)
ht:SetAlpha(0.25)
local function hidePopup()
popup:Hide()
end
b:SetScript("OnClick", function(self)
if hoverFocus:CheckToggle(self) then
hoverFocus:Open(self, popup, nil, hidePopup)
popup:SetPoint("TOPLEFT", self, "BOTTOMLEFT", -34, -2)
popup:Show()
end
end)
b:SetScript("OnEnter", function(self)
hoverFocus:DelayOpenClick(self)
end)
end
end
activeUI:SetScript("OnShow", function(self)
missionList.ctlContainer:Steal(self, ctl)
RefreshActiveMissionsView(true)
end)
local lootFrame = CreateFrame("Frame", nil, activeUI) do
local lf = lootFrame
activeUI.lootFrame = lf
lf:SetSize(560, 380)
lf:SetPoint("CENTER", GarrisonMissionFrameMissions, "CENTER")
local t = lf:CreateTexture(nil, "BACKGROUND", nil, -1)
t:SetAllPoints(GarrisonMissionFrameMissions)
t:SetColorTexture(0,0,0)
t:SetAlpha(0.35)
local w1, h1 = lf:GetSize()
local w2, h2 = GarrisonMissionFrameMissions:GetSize()
lf:SetHitRectInsets((w1-w2)/2, (w1-w2)/2, (h1-h2)/2, (h1-h2)/2)
lf:EnableMouse(true) lf:EnableMouseWheel(true)
lf:SetFrameStrata("DIALOG")
t = lf:CreateTexture(nil, "BACKGROUND")
t:SetAtlas("Garr_InfoBox-BackgroundTile", true)
t:SetHorizTile(true) t:SetVertTile(true)
t:SetAllPoints()
t = lf:CreateTexture(nil, "BORDER")
t:SetAtlas("_Garr_InfoBoxBorder-Top", true)
t:SetHorizTile(true) t:SetPoint("TOPLEFT") t:SetPoint("TOPRIGHT")
t = lf:CreateTexture(nil, "BORDER")
t:SetAtlas("_Garr_InfoBoxBorder-Top", true)
t:SetHorizTile(true) t:SetPoint("BOTTOMLEFT") t:SetPoint("BOTTOMRIGHT")
t:SetTexCoord(0, 1, 1, 0)
t = lf:CreateTexture(nil, "BORDER")
t:SetAtlas("!Garr_InfoBoxBorder-Left", true)
t:SetVertTile(true) t:SetPoint("TOPLEFT") t:SetPoint("BOTTOMLEFT")
t = lf:CreateTexture(nil, "BORDER")
t:SetAtlas("!Garr_InfoBoxBorder-Left", true)
t:SetVertTile(true) t:SetPoint("TOPRIGHT") t:SetPoint("BOTTOMRIGHT")
t:SetTexCoord(1,0, 0,1)
t = lf:CreateTexture(nil, "BORDER", nil, -1)
t:SetAtlas("!Garr_InfoBox-Left", true)
t:SetPoint("TOPLEFT", -7, 0)
t:SetPoint("BOTTOMLEFT", -7, 0)
t:SetVertTile(true)
t = lf:CreateTexture(nil, "BORDER", nil, -1)
t:SetAtlas("!Garr_InfoBox-Left", true)
t:SetPoint("TOPRIGHT", 7, 0)
t:SetPoint("BOTTOMRIGHT", 7, 0)
t:SetVertTile(true)
t:SetTexCoord(1,0, 0,1)
t = lf:CreateTexture(nil, "BORDER", nil, -1)
t:SetAtlas("_Garr_InfoBox-Top", true)
t:SetPoint("TOPLEFT", 0, 7)
t:SetPoint("TOPRIGHT", 0, 7)
t:SetHorizTile(true)
t = lf:CreateTexture(nil, "BORDER", nil, -1)
t:SetAtlas("_Garr_InfoBox-Top", true)
t:SetPoint("BOTTOMLEFT", 0, -7)
t:SetPoint("BOTTOMRIGHT", 0, -7)
t:SetHorizTile(true)
t:SetTexCoord(0,1, 1,0)
t = lf:CreateTexture(nil, "BORDER", nil, 1)
t:SetAtlas("Garr_InfoBoxBorder-Corner", true)
t:SetPoint("TOPLEFT")
t = lf:CreateTexture(nil, "BORDER", nil, 1)
t:SetAtlas("Garr_InfoBoxBorder-Corner", true)
t:SetPoint("TOPRIGHT") t:SetTexCoord(1,0, 0,1)
t = lf:CreateTexture(nil, "BORDER", nil, 1)
t:SetAtlas("Garr_InfoBoxBorder-Corner", true)
t:SetPoint("BOTTOMLEFT") t:SetTexCoord(0,1, 1,0)
t = lf:CreateTexture(nil, "BORDER", nil, 1)
t:SetAtlas("Garr_InfoBoxBorder-Corner", true)
t:SetPoint("BOTTOMRIGHT") t:SetTexCoord(1,0, 1,0)
t = lf:CreateFontString(nil, "ARTWORK", "QuestFont_Super_Huge")
t:SetPoint("TOP", 0, -12)
t:SetText((GARRISON_MISSION_REPORT:gsub("\n", " ")))
t = lf:CreateFontString(nil, "ARTWORK", "GameFontHighlightLarge")
t:SetPoint("TOP", 0, -40)
lf.numMissions = t
t = lf:CreateTexture(nil, "BORDER", nil, 1)
t:SetAtlas("Garr_InfoBox-CornerShadow", true)
t:SetPoint("BOTTOMRIGHT", lf, "TOPLEFT")
t = lf:CreateTexture(nil, "BORDER", nil, 1)
t:SetAtlas("Garr_InfoBox-CornerShadow", true)
t:SetPoint("BOTTOMLEFT", lf, "TOPRIGHT")
t:SetTexCoord(1,0, 0,1)
t = lf:CreateTexture(nil, "BORDER", nil, 1)
t:SetAtlas("Garr_InfoBox-CornerShadow", true)
t:SetPoint("TOPRIGHT", lf, "BOTTOMLEFT")
t:SetTexCoord(0,1, 1,0)
t = lf:CreateTexture(nil, "BORDER", nil, 1)
t:SetAtlas("Garr_InfoBox-CornerShadow", true)
t:SetPoint("TOPLEFT", lf, "BOTTOMRIGHT")
t:SetTexCoord(1,0, 1,0)
local function close(self)
lootFrame:Hide()
GarrisonMissionFrame.MissionComplete.completeMissions = C_Garrison.GetCompleteMissions(1)
GarrisonMissionFrame:UpdateMissions()
RefreshActiveMissionsView(self == lootFrame.Dismiss)
end
t = CreateFrame("Button", "MPLootSummaryDone", lootFrame, "UIPanelButtonTemplate")
t:SetSize(200, 24) t:SetText(L"Done") t:SetPoint("BOTTOM", 0, 18)
t:SetScript("OnClick", close)
t:SetScript("OnKeyDown", function(self, key)
self:SetPropagateKeyboardInput(key ~= "SPACE" and key ~= "ESCAPE")
if key == "SPACE" then
self:Click()
elseif key == "ESCAPE" then
lf.Dismiss2:Click()
end
end)
t, lf.Dismiss = CreateFrame("Button", nil, lootFrame, "UIPanelCloseButtonNoScripts"), t
t:SetSize(28, 28)
t:SetPoint("TOPRIGHT", 0, -2)
t:SetScript("OnClick", close)
lf.Dismiss2 = t
t = lf:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
t:SetPoint("BOTTOM", lf.Dismiss, "TOP", 0, 6)
t:SetText(("|cffff2020%s|r|n%s"):format(L"You have no free bag slots.", L"Additional mission loot may be delivered via mail."))
lf.noBagSlots = t
lf:Hide()
lf:SetScript("OnShow", function(self)
if self.onShowSound then
PlaySound(self.onShowSound)
self.onShowSound = nil
end
end)
end
local lootContainer, SetFollower = CreateFrame("Frame", nil, lootFrame) do
lootContainer:SetSize(490, 280)
lootContainer:SetPoint("TOP", 0, -65)
lootContainer:RegisterEvent("GET_ITEM_INFO_RECEIVED")
lootContainer:SetScript("OnEvent", function(self)
for i=1,#self.items do
local ii = self.items[i]
if ii.itemID and ii:IsShown() then
ii:SetIcon(select(10, GetItemInfo(ii.itemID)) or GetItemIcon(ii.itemID) or "Interface\\Icons\\Temp")
end
end
end)
do
local function AnimateXP(self, elapsed)
if self.levelUp:IsShown() then return end
local elapsed = self.xpGainElapsed + elapsed
local prog = elapsed > 0.75 and 1 or (elapsed/0.75)
self.xpProgressTex2:SetWidth(math.max(0.01, sin(90*prog) * self.xpGainWidth))
if prog == 1 then
self.xpGainWidth, self.xpGainElapsed = nil
self:SetScript("OnUpdate", nil)
else
self.xpGainElapsed = elapsed
end
end
function SetFollower(btn, info, award, oldQuality)
if not info then return end
local color = ITEM_QUALITY_COLORS[info.quality]
btn.PortraitRingQuality:SetVertexColor(color.r, color.g, color.b)
btn.LevelBorder:SetVertexColor(color.r, color.g, color.b)
btn.Level:SetText(info.level);
local pico = info.portraitIconID or 0
btn.Portrait:SetTexture(pico ~= 0 and pico or "Interface\\Garrison\\Portraits\\FollowerPortrait_NoPortrait")
if info.levelXP > info.xp and award > 0 then
local baseXP = info.xp - math.min(info.xp, award)
btn.xpProgressTex:SetWidth(math.max(0.01,46*baseXP/info.levelXP))
btn.xpProgressTex2:SetWidth(0.01)
btn.xpGainWidth, btn.xpGainElapsed = 46*math.min(info.xp - baseXP, award)/info.levelXP, 0
btn.xpProgressTex2:Show()
btn:SetScript("OnUpdate", AnimateXP)
btn.xpProgressTex:SetShown(baseXP > 0)
btn.xpProgressTex2:Show()
else
btn:SetScript("OnUpdate", nil)
btn.xpProgressTex:Hide()
btn.xpProgressTex2:Hide()
end
btn.info, btn.awardXP = info, award or 0
if award and award > (info.xp or 0) or (oldQuality and oldQuality ~= info.quality) then
lootFrame.onShowSound = "UI_Garrison_CommandTable_Follower_LevelUp"
btn.levelUp:Show()
btn.levelUp:SetAlpha(1)
btn.levelUp.Anim:Play()
btn.Level:SetFontObject(GameFontNormalSmall)
btn.LevelUpAnim:Play()
else
btn.levelUp:SetAlpha(0)
btn.levelUp:Hide()
btn.LevelUpAnim:Stop()
btn.Level:SetFontObject(GameFontHighlightSmall)
end
btn:Show()
end
end
lootContainer.followers = {} do
local function FollowerButton_OnEnter(self)
local info = self.info
FollowerTooltip_SetFollower(self, info)
G.ExtendFollowerTooltipGainedXP(GarrisonFollowerTooltip, self.awardXP, info)
end
local function FollowerButton_OnClick(self)
local id = self.info and self.info.followerID
if id and IsModifiedClick("CHATLINK") then
ChatEdit_InsertLink(C_Garrison.GetFollowerLink(id))
end
end
local function LevelPulse_OnStop(self)
self:GetParent().pulse:SetAlpha(0)
end
local function CreateFollower()
local b = CreateFrame("Button", nil, lootContainer, "GarrisonFollowerPortraitTemplate")
b.levelUp = CreateFrame("Frame", nil, b, "GarrisonFollowerLevelUpTemplate")
b.levelUp:SetScale(0.5)
b.levelUp:SetPoint("BOTTOM", 0, -47)
b.xpProgressTex = b:CreateTexture(nil, "ARTWORK", nil, 2)
b.xpProgressTex:SetPoint("TOPLEFT", b.LevelBorder, "TOPLEFT", 6, -6)
b.xpProgressTex:SetTexture("Interface\\Buttons\\GradBlue")
b.xpProgressTex:SetAlpha(0.4)
b.xpProgressTex:SetSize(30, 12)
b.xpProgressTex2 = b:CreateTexture(nil, "ARTWORK", nil, 2)
b.xpProgressTex2:SetTexture("Interface\\Buttons\\GradBlue")
b.xpProgressTex2:SetAlpha(0.6)
b.xpProgressTex2:SetSize(30, 12)
b.xpProgressTex2:SetPoint("LEFT", b.xpProgressTex, "RIGHT")
b.pulse = b:CreateTexture(nil, "BORDER", nil, 0)
b.pulse:SetAtlas("GarrMission_CurrentEncounter-Glow", true)
b.pulse:SetPoint("CENTER", b.Portrait)
b.pulse:SetAlpha(0)
b.LevelUpAnim = b:CreateAnimationGroup()
b.LevelUpAnim:SetLooping("REPEAT")
b.LevelUpAnim:SetScript("OnStop", LevelPulse_OnStop)
local t = b.LevelUpAnim:CreateAnimation("Alpha")
t:SetEndDelay(1.25)
t:SetDuration(1.5) t:SetFromAlpha(0) t:SetToAlpha(1)
t:SetChildKey("pulse")
local t = b.LevelUpAnim:CreateAnimation("Alpha")
t:SetStartDelay(1.5) t:SetEndDelay(0.25)
t:SetDuration(1) t:SetFromAlpha(1) t:SetToAlpha(0)
t:SetChildKey("pulse")
b:SetScript("OnEnter", FollowerButton_OnEnter)
b:SetScript("OnLeave", GarrisonMissionPageFollowerFrame_OnLeave)
b:SetScript("OnClick", FollowerButton_OnClick)
b:Hide()
return b
end
setmetatable(lootContainer.followers, {__index=function(self, k)
local b = CreateFollower()
self[k] = b
return b
end})
end
lootContainer.items = {} do
local function OnEnter(self)
GameTooltip:SetOwner(self, "ANCHOR_TOPLEFT")
if self.itemID then
G.SetItemTooltip(GameTooltip, self.itemID)
elseif self.tooltipHeader and self.tooltipText then
GameTooltip:AddLine(self.tooltipHeader)
GameTooltip:AddLine(self.tooltipText, 1,1,1)
elseif self.currencyID then
GameTooltip:SetCurrencyByID(self.currencyID)
else
GameTooltip:Hide()
return
end
if self.tooltipExtra then
GameTooltip:AddLine(self.tooltipExtra, 1,1,1)
end
GameTooltip:Show()
end
local function OnClick(self)
local link
if not IsModifiedClick("CHATLINK") then
elseif self.itemID then
link = select(2, GetItemInfo(self.itemID))
elseif self.currencyID and self.currencyID > 0 then
link = GetCurrencyLink(self.currencyID)
end
if link then
ChatEdit_InsertLink(link)
end
end
local function SetIcon(self, texture)
self.Icon:SetTexture(texture)
self.Icon:SetTexCoord(4/64, 60/64, 4/64, 60/64)
end
setmetatable(lootContainer.items, {__index=function(self, k)
local i = CreateFrame("Button", nil, lootContainer)
i:SetSize(46, 46)
i.Icon = i:CreateTexture(nil, "ARTWORK")
i.Icon:SetPoint("TOPLEFT", 3*46/64, -3*46/64)
i.Icon:SetPoint("BOTTOMRIGHT", -3*46/64, 3*46/64)
i.Border = i:CreateTexture(nil, "ARTWORK", 2)
i.Border:SetAllPoints()
i.Border:SetTexture("Interface\\Buttons\\UI-Quickslot2")
i.Border:SetTexCoord(12/64,52/64,12/64,52/64)
i.Quantity = i:CreateFontString(nil, "OVERLAY", "GameFontHighlightOutline")
i.Quantity:SetPoint("BOTTOMRIGHT", -3, 4)
i:SetScript("OnEnter", OnEnter)
i:SetScript("OnLeave", dismissTooltip)
i:SetScript("OnClick", OnClick)
self[k], i.SetIcon = i, SetIcon
return i
end})
end
end
lootContainer.nothing = lootContainer:CreateFontString(nil, "OVERLAY", "GameFontHighlightLarge")
lootContainer.nothing:SetPoint("CENTER")
lootContainer.nothing:SetText(L"No loot received.")
function activeUI:SetCompletionRewards(rewards, followers, numMissions, overflowLoot)
lootFrame.noBagSlots:SetShown(overflowLoot)
lootFrame.numMissions:SetFormattedText(GARRISON_NUM_COMPLETED_MISSIONS, numMissions or 1)
lootFrame.onShowSound = rewards and next(rewards) and "UI_Garrison_CommandTable_ChestUnlock_Gold_Success" or "UI_Garrison_CommandTable_ChestUnlock"
local fi, fn = G.GetFollowerInfo(), 1
for k,v in pairs(followers) do
if v.xpAward and v.xpAward > 0 then
SetFollower(lootContainer.followers[fn], fi[k], v.xpAward, v.oqual)
fn = fn + 1
end
end
for i=fn, #lootContainer.followers do
lootContainer.followers[i]:Hide()
end
local ni = 1
for k,v in pairs(rewards) do
local quantity, icon, tooltipHeader, tooltipText, _, tooltipExtra = v.quantity
if v.itemID then
icon, tooltipExtra = select(10, GetItemInfo(v.itemID)) or GetItemIcon(v.itemID) or "Interface\\Icons\\Temp", v.itemID == 120205 and rewards.xp and rewards.xp.playerXP and XP_GAIN:format(BreakUpLargeNumbers(rewards.xp.playerXP)) or nil
elseif v.currencyID == 0 then
icon, tooltipHeader, tooltipText = "Interface\\Icons\\INV_Misc_Coin_02", GARRISON_REWARD_MONEY, GetMoneyString(v.quantity)
quantity = floor(quantity/10000)
elseif v.currencyID then
_, _, icon = GetCurrencyInfo(v.currencyID)
end
if icon then
local ib = lootContainer.items[ni]
ib:SetPoint("CENTER", lootContainer.followers[fn], "CENTER", 0, 4)
ib:SetIcon(icon)
ib.Quantity:SetText(quantity > 1 and quantity)
ib.itemID, ib.currencyID, ib.tooltipHeader, ib.tooltipText, ib.tooltipExtra = v.itemID, v.currencyID, tooltipHeader, tooltipText, tooltipExtra
ib:Show()
ni, fn = ni + 1, fn + 1
end
end
for i=ni,#lootContainer.items do
lootContainer.items[i]:Hide()
end
local numTotal = fn - 1 do
local perRow, baseY = 9, 0, 0
if numTotal <= 9 then
perRow, baseY = numTotal, -76
elseif numTotal <= 18 then
perRow, baseY = 6, numTotal <= 12 and -64 or -32
elseif numTotal <= 32 then
perRow, baseY = 8, numTotal <= 24 and -24 or 0
end
local baseX = (504 - perRow*56)/2
for i=1,numTotal do
lootContainer.followers[i]:SetPoint("TOPLEFT", baseX + ((i-1) % perRow) * 56, baseY - 64*floor((i-1)/perRow))
end
lootContainer.count = numTotal
end
lootContainer.nothing:SetShown(ni == 1 and fn == 1)
lootFrame:Show()
end
end
local availUI = CreateFrame("Frame", nil, missionList) do
availUI:SetSize(880, 22)
availUI:SetPoint("BOTTOMLEFT", GarrisonMissionFrameMissions, "TOPLEFT", 0, 4)
availUI:Hide()
local ctl = CreateFrame("Frame") do
ctl:SetSize(56, 22)
local sortIndicator = CreateFrame("Button", nil, ctl) do
sortIndicator:SetPoint("LEFT", 4, 0)
sortIndicator:SetSize(20, 20)
for i=1, 2 do
local t = sortIndicator:CreateTexture(nil, i == 1 and "BACKGROUND" or "HIGHLIGHT")
t:SetTexture("Interface\\Buttons\\SquareButtonTextures")
t:SetTexCoord(0.45312500, 0.64062500, 0.01562500, 0.20312500)
t:SetSize(14, 18)
t:SetPoint("LEFT", 2, 4)
if i == 1 then t:SetVertexColor(3/4, 3/4, 3/4) end
t = sortIndicator:CreateTexture(nil, i == 1 and "BACKGROUND" or "HIGHLIGHT")
t:SetTexture("Interface\\Buttons\\SquareButtonTextures")
t:SetTexCoord(0.45312500, 0.64062500, 0.20312500, 0.01562500)
t:SetSize(14, 18)
t:SetPoint("LEFT", 2, -4)
if i == 1 then t:SetVertexColor(3/4, 3/4, 3/4) end
end
local menu, sortOrders = {
{text=L"Mission order:", isTitle=true, notCheckable=true},
{text=L"Reward type", arg1="reward"},
{text=L"Follower experience", arg1="xp"},
{text=L"Follower experience per hour", arg1="xptime"},
{text=L"Chance of success", arg1="threats"},
{text=L"Mission level", arg1="level"},
{text=L"Mission duration", arg1="duration"},
{text=L"Mission expiration", arg1="expire"},
}, {}
local function isChecked(self)
return T.config.availableMissionSort == self.arg1
end
for i=2,#menu do
local m = menu[i]
sortOrders[m.arg1], m.checked, m.func = m.text, isChecked, MasterPlan.SetMissionOrder
end
sortIndicator:SetScript("OnClick", function(self)
easyDrop:Toggle(self, menu, "TOPLEFT", self, "BOTTOMLEFT", -24, -3)
end)
sortIndicator:SetScript("OnEnter", function(self)
easyDrop:DelayOpenClick(self)
end)
end
local horizon = CreateFrame("Button", nil, ctl) do
horizon:SetPoint("LEFT", 30, 0)
horizon:SetSize(20, 20)
for i=1, 2 do
local t = horizon:CreateTexture(nil, i == 1 and "BACKGROUND" or "HIGHLIGHT")
t:SetTexture("Interface\\FriendsFrame\\StatusIcon-Away")
t:SetSize(16,16)
t:SetPoint("LEFT", 2, 0)
t:SetTexCoord(2/16, 14/16, 2/16, 14/16)
if i == 1 then
t:SetVertexColor(3/4, 3/4, 3/4)
end
end
local function isChecked(self)
return T.config.timeHorizon == self.arg1
end
local menu = {
{text=L"Time Horizon", isTitle=true, notCheckable=true, justifyH="CENTER"},
{text=L"Instant", checked=isChecked, func=MasterPlan.SetTimeHorizon, arg1=0},
{arg1=3600},
{arg1=7200},
{arg1=10800},
{arg1=14400},
{arg1=21600},
{arg1=28800},
{arg1=43200},
{arg1=86400},
}
for i=3,#menu do
menu[i].text, menu[i].checked, menu[i].func = INT_GENERAL_DURATION_HOURS:format(menu[i].arg1/3600), isChecked, MasterPlan.SetTimeHorizon
end
local function showHint()
if easyDrop:IsOpen(horizon) then
GameTooltip:SetOwner(horizon, "ANCHOR_PRESERVE")
GameTooltip:ClearAllPoints()
GameTooltip:SetPoint("TOPLEFT", DropDownList1, "TOPRIGHT", 4, 0)
GameTooltip:SetText(L"Time Horizon")
GameTooltip:AddLine(L"Time until you next expect to be able to interact with garrison missions.\n\nThis may affect suggested groups and mission sorting order.", 1,1,1,1)
GameTooltip:Show()
end
end
horizon:SetScript("OnClick", function(self)
easyDrop:Toggle(self, menu, "TOPLEFT", self, "BOTTOMLEFT", -24, -3)
showHint()
end)
horizon.OnEasyDropHide = dismissTooltip
horizon:SetScript("OnEnter", function(self)
easyDrop:DelayOpenClick(self)
showHint()
end)
end
local loader = api.CreateLoader(ctl, 10, 4, 10, 10, true) do
loader:SetPoint("LEFT", horizon, "RIGHT", 8, 0)
local baseWidth = ctl:GetWidth()
loader:HookScript("OnShow", function()
missionList.ctlContainer:SetInnerWidth(baseWidth + 8 + loader:GetWidth(), true)
end)
loader:HookScript("OnHide", function()
missionList.ctlContainer:SetInnerWidth(baseWidth)
end)
availUI.loader = loader
end
end
availUI:SetScript("OnShow", function(self)
missionList.ctlContainer:Steal(self, ctl)
RefreshAvailMissionsView(true)
self.notebook:SetShown(GetItemCount(self.notebook.itemID) > 0)
end)
local roamingParty = CreateFrame("Frame", nil, availUI) do
roamingParty:SetPoint("BOTTOMRIGHT", availUI, "BOTTOM", 106, -2)
local slots = {}
function roamingParty:GetFollowers()
local a, b, c
for i=#slots,1,-1 do
a, b, c = slots[i].followerID, a, b
end
return a, b, c
end
function roamingParty:DropFollowers(f1, f2, f3)
for i=1,#slots do
local f = slots[i].followerID
if f and (f == f1 or f == f2 or f == f3) then
slots[i].followerID = nil
end
end
self:Update()
end
function roamingParty:Update(changed)
changed = changed or false
for i=1,#slots do
local f, fi = slots[i].followerID
if f then
fi = C_Garrison.GetFollowerInfo(f)
if not fi or ((fi.status or "") ~= "" and fi.status ~= GARRISON_FOLLOWER_IN_PARTY) then
changed, f = true
end
end
if f then
slots[i].portrait:SetTexture(fi.portraitIconID)
slots[i].portrait:SetVertexColor(1, 1, 1)
else
slots[i].portrait:SetTexture("Interface\\Garrison\\Portraits\\FollowerPortrait_NoPortrait")
slots[i].portrait:SetVertexColor(0.50, 0.50, 0.50)
end
slots[i].followerID = f
end
if changed then
availMissionsHandle:Refresh(true)
end
end
function roamingParty:Clear()
for i=1,#slots do
slots[i].followerID = nil
end
self:Update(true)
end
local function Roamer_SetFollower(_, slot, follower)
local self = roamingParty
if slots[slot].followerID ~= follower then
for i=1,#slots do
if slots[i].followerID == follower then
slots[i].followerID = nil
end
end
PlaySound(follower and "UI_Garrison_CommandTable_AssignFollower" or "UI_Garrison_CommandTable_UnassignFollower")
slots[slot].followerID = follower
self:Update(true)
end
end
local function cmp(a,b)
local am, bm = a.level == 100 and a.quality > 3, b.level == 100 and b.quality > 3
if am ~= bm then
return bm
elseif a.level ~= b.level then
return a.level > b.level
elseif floor(a.iLevel/15) ~= floor(b.iLevel/15) then
return a.iLevel > b.iLevel
elseif a.quality ~= b.quality then
return a.quality > b.quality
else
return strcmputf8i(a.name, b.name) < 0
end
end
local function Roamer_OnEnter(self)
if easyDrop:IsOpen(self) then
elseif self.followerID then
for i=1,#slots do
if easyDrop:IsOpen(slots[i]) then
return
end
end
FollowerTooltip_SetFollower(self, C_Garrison.GetFollowerInfo(self.followerID))
else
GameTooltip:SetOwner(self, "ANCHOR_BOTTOM")
GameTooltip:SetText(L"Select a follower to focus on")
GameTooltip:AddLine(L"Group suggestions will be updated to include the selected follower.", 1,1,1,1)
GameTooltip:Show()
end
end
local function Roamer_OnLeave(self)
GarrisonFollowerTooltip:Hide()
if GameTooltip:IsOwned(self) then
GameTooltip:Hide()
end
end
local function RoamerMenu_OnMouse(self, _, id)
if self and id then
FollowerTooltip_SetFollower(self, C_Garrison.GetFollowerInfo(id))
GarrisonFollowerTooltip:ClearAllPoints()
GarrisonFollowerTooltip:SetPoint("LEFT", self, "RIGHT", 12, 0)
return RoamerMenu_OnMouse
else
GarrisonFollowerTooltip:Hide()
end
end
local function Roamer_OnClick(self, button)
if GameTooltip:IsOwned(self) then
GameTooltip:Hide()
end
if button == "RightButton" then
Roamer_SetFollower(nil, self:GetID(), nil)
GarrisonFollowerTooltip:Hide()
self:GetScript("OnEnter")(self)
elseif easyDrop:IsOpen(self) then
CloseDropDownMenus()
PlaySound("UChatScrollButton")
self:GetScript("OnEnter")(self)
else
PlaySound("UChatScrollButton")
local mn, f2, slot, cur = {}, C_Garrison.GetFollowers(1), self:GetID(), self.followerID
local a1, a2, a3 = roamingParty:GetFollowers()
table.sort(f2, cmp)
for i=1,#f2 do
local fi, fid = f2[i], f2[i].followerID
if fi.isCollected and (fi.status or "") == "" and (fid == cur or (fid ~= a1 and fid ~= a2 and fid ~= a3)) and not T.config.ignore[fid] and not G.GetFollowerTentativeMission(fid) then
mn[#mn+1] = {text=G.GetFollowerLevelDescription(fi.followerID, nil), func=Roamer_SetFollower, arg1=slot, arg2=fi.followerID, checked=cur==fi.followerID, tooltipOnButton=RoamerMenu_OnMouse}
end
end
if cur then
mn[#mn+1] = {text=REMOVE, func=Roamer_SetFollower, arg1=slot, justifyH="CENTER", notCheckable=true}
end
GarrisonFollowerTooltip:Hide()
easyDrop:Open(self, mn, "TOP", self, "BOTTOM", 0, -2)
end
end
for i=1,1 do
local x = CreateFrame("Button", nil, roamingParty, nil, i)
x:SetSize(36, 36) x:SetPoint("LEFT", 40*i-38, 0) x:RegisterForClicks("LeftButtonUp", "RightButtonUp")
local v = x:CreateTexture(nil, "ARTWORK", nil, 1) v:SetPoint("TOPLEFT", 3, -3) v:SetPoint("BOTTOMRIGHT", -3, 3) v:SetTexture("Interface\\Garrison\\Portraits\\FollowerPortrait_NoPortrait")
slots[i], x.portrait = x, v
local v = x:CreateTexture(nil, "ARTWORK", nil, 2) v:SetAllPoints() v:SetAtlas("Garr_FollowerPortrait_Ring", true)
local v = x:CreateTexture(nil, "HIGHLIGHT") v:SetPoint("TOPLEFT", -2, 2) v:SetPoint("BOTTOMRIGHT", 1, -1) v:SetTexture("Interface\\Minimap\\UI-Minimap-ZoomButton-Highlight") v:SetBlendMode("ADD")
x:SetScript("OnClick", Roamer_OnClick)
x:SetScript("OnEnter", Roamer_OnEnter)
x:SetScript("OnLeave", Roamer_OnLeave)
end
roamingParty:SetSize(#slots*40, 36)
local function clearRP()
roamingParty:Clear()
end
function EV:GARRISON_MISSION_NPC_CLOSED()
T.After0(clearRP)
end
end
availUI.SendTentative = CreateFrame("Button", "MPPokeTentativeParties", availUI, "UIPanelButtonTemplate") do
local b = availUI.SendTentative
b:SetSize(200, 26)
b:SetPoint("BOTTOM", -64, 5)
b:RegisterForClicks("LeftButtonUp", "RightButtonUp")
b:Hide()
b:SetScript("OnLeave", dismissTooltip)
b:SetScript("OnEnter", function(self)
if G.GetNumPendingMissionStarts() > 0 or G.GetTentativePartyCount(1) == 0 then return end
GameTooltip:SetOwner(self, "ANCHOR_BOTTOM")
GameTooltip:SetText(L"Start Missions")
if C_Garrison.IsAboveFollowerSoftCap(1) then
GameTooltip:AddLine(GARRISON_MAX_FOLLOWERS_MISSION_TOOLTIP, 1, 0, 0, 1)
else
local rewards, rtext = {}, ""
for mid, f1, f2, f3 in G.GetReadyTentativeParties(1) do
local mi = C_Garrison.GetBasicMissionInfo(mid)
local g = G.GetBackfillMissionGroups(mi, G.GroupFilter.ACTIVE, G.GroupRank.xp, 1, f1, f2, f3)[1]
if not g then
G.GetMissionParty(mid)
else
GameTooltip:AddDoubleLine(HIGHLIGHT_FONT_COLOR_CODE .. mi.name, g[1] .. "%")
local sp, ct, cq, _, expectedXP = g[1]/100, g[9] or 0, g[3] or 0, G.GetMissionGroupXP(g, mi)
if expectedXP > 0 then
rewards.xp = (rewards.xp or 0) + expectedXP
end
if g[1] > 0 and cq > 0 then
rewards[ct] = (rewards[ct] or 0) + cq*sp
end
end
end
if (rewards.xp or 0) > 0 then
rtext = L("%s XP"):format(BreakUpLargeNumbers(rewards.xp))
end
if (rewards[0] or 0) >= 1e4 then
rtext = rtext .. " " .. GetMoneyString(rewards[0] - rewards[0] % 1e4)
end
rewards.xp, rewards[0] = nil
for cid, cq in pairs(rewards) do
rtext = rtext .. " " .. floor(cq) .. " |T" .. (select(3,GetCurrencyInfo(cid)) or "Interface/Icons/Temp") .. ":12:12:0:0:64:64:4:60:4:60|t"
end
if rtext ~= "" then
GameTooltip:AddDoubleLine(L"Expected rewards:", rtext, nil, nil, nil, 1,1,1)
end
end
GameTooltip:AddLine("|n|TInterface\\TUTORIALFRAME\\UI-TUTORIAL-FRAME:14:12:0:-1:512:512:10:70:330:410|t " .. L"Clear all tentative parties.", 0.5, 0.8, 1)
GameTooltip:Show()
end)
b:SetScript("OnClick", function(_, button)
if G.GetNumPendingMissionStarts() > 0 then
G.AbortMissionQueue()
RefreshAvailMissionsView()
elseif button == "RightButton" or G.GetTentativePartyCount(1) == 0 then
G.DissolveAllTentativeParties(1)
PlaySound("UChatScrollButton")
elseif not C_Garrison.IsAboveFollowerSoftCap(1) then
G.SuppressFollowerEvents(1)
for mid, p1, p2, p3 in G.GetReadyTentativeParties(1) do
G.StartMissionQueue(mid, p1, p2, p3)
end
G.ReleaseFollowerEvents(1)
PlaySound("UI_Garrison_CommandTable_MissionStart")
end
end)
local syncLater do
local synced = true
local function sync()
synced = true
local np = G.GetNumPendingMissionStarts()
local nr, nt = G.GetTentativePartyCount(1)
b:SetShown(np > 0 or nt > 0)
if b:IsShown() then
local text
if np > 0 then
text = L("%d |4party:parties; remaining..."):format(np)
else
text = nr > 0 and L"Send Tentative Parties" or L"Clear Tentative Parties"
end
b:SetText(text)
if GameTooltip:IsOwned(b) then
if np == 0 then
b:GetScript("OnEnter")(b)
else
GameTooltip:Hide()
end
end
end
end
function syncLater()
if synced then
T.After0(sync)
synced = false
end
end
EV.MP_MISSION_START_QUEUE, EV.MP_TENTATIVE_PARTY_UPDATE = sync, syncLater
end
function EV:MP_MISSION_REJECT(mid)
syncLater()
G.GetMissionParty(mid, true)
PlaySound("igQuestFailed")
end
end
api.roamingParty = roamingParty
availUI.notebook = T.CreateLazyItemButton(availUI, 122606) do
availUI.notebook:SetSize(20, 20)
availUI.notebook:SetPoint("LEFT", GarrisonMissionFrame.MissionTab.MissionList.MaterialFrame, "LEFT", 14, 0)
availUI.notebook:SetScript("OnShow", function()
local f = GarrisonMissionFrame.MissionTab.MissionList.MaterialFrame.MPHeadcount
f.Text:SetPoint("LEFT", 40, 0)
end)
availUI.notebook:SetScript("OnHide", function()
local f = GarrisonMissionFrame.MissionTab.MissionList.MaterialFrame.MPHeadcount
f.Text:SetPoint("LEFT", 16, 0)
end)
end
end
local interestUI = CreateFrame("Frame", nil, missionList) do
interestUI:Hide()
interestUI.loader = api.CreateLoader(interestUI, 20, 30, 20)
interestUI.loader:SetPoint("CENTER", GarrisonMissionFrameMissions)
function interestUI.loader:OnFinish(nf)
if nf > 2 then
missionList.FadeIn:Play()
end
end
local ctl = CreateFrame("Frame") do
ctl:SetSize(83, 22)
ctl:Hide()
interestUI.excludeInactive = CreateFrame("CheckButton", nil, ctl) do
local b = interestUI.excludeInactive
b:SetSize(20, 20)
b:SetPoint("LEFT", 3, 0)
b:SetChecked(true)
b:SetNormalTexture("Interface\\FriendsFrame\\UI-Toast-FriendOnlineIcon")
b:SetHighlightTexture("Interface\\FriendsFrame\\UI-Toast-FriendOnlineIcon")
b:SetCheckedTexture("Interface\\PetBattles\\DeadPetIcon")
local nt = b:GetNormalTexture()
nt:SetTexCoord(4/32,28/32, 4/32,28/32)
nt:SetVertexColor(0.84, 0.76, 0.56)
local ct = b:GetCheckedTexture()
ct:SetBlendMode("BLEND")
ct:ClearAllPoints()
ct:SetSize(12, 12)
ct:SetPoint("BOTTOMRIGHT")
local ht = b:GetHighlightTexture()
ht:SetTexCoord(4/32,28/32, 4/32,28/32)
ht:SetAlpha(0.25)
b:SetScript("OnClick", function(self)
interestMissionsHandle:Show(not self:GetChecked())
if GameTooltip:IsOwned(self) then
self:GetScript("OnEnter")(self)
end
end)
b:SetScript("OnEnter", function(self)
GameTooltip:SetOwner(self, "ANCHOR_NONE")
GameTooltip:SetPoint("TOPLEFT", self, "BOTTOMLEFT", -24, -4)
GameTooltip:SetText(self:GetChecked() and L"Ignoring inactive followers" or L"Considering inactive followers")
GameTooltip:AddLine(self:GetChecked() and L"Inactive followers are never included in suggested groups." or L"Inactive followers are only included in suggested groups when they are beneficial.", 1,1,1, 1)
GameTooltip:Show()
easyDrop:Close()
end)
b:SetScript("OnLeave", dismissTooltip)
end
interestUI.stackMode = CreateFrame("Button", nil, ctl) do
local b = interestUI.stackMode
b:SetSize(20, 20)
b:SetPoint("LEFT", 30, 0)
b:SetScript("OnClick", function(self)
T.config.interestStack = bit.bxor(1, T.config.interestStack)
interestMissionsHandle:Show(not interestUI.excludeInactive:GetChecked())
if GameTooltip:IsOwned(self) then
self:GetScript("OnEnter")(self)
end
self:GetScript("OnShow")(self)
end)
b:SetScript("OnShow", function(self)
local tex = T.config.interestStack % 2 > 0 and "Interface/Minimap/TRACKING/Auctioneer" or "Interface/Minimap/TRACKING/Banker"
self:SetNormalTexture(tex)
self:GetNormalTexture():SetVertexColor(0.85, 0.85, 0.85, 0.90)
self:SetHighlightTexture(tex)
self:GetHighlightTexture():SetBlendMode("ADD")
self:GetHighlightTexture():SetAlpha(0.25)
end)
b:SetScript("OnEnter", function(self)
GameTooltip:SetOwner(self, "ANCHOR_NONE")
GameTooltip:SetPoint("TOPLEFT", self, "BOTTOMLEFT", -51, -4)
local isStacking = T.config.interestStack % 2 > 0
GameTooltip:AddLine(isStacking and L"Prioritizing expected reward" or L"Prioritizing success chance")
GameTooltip:AddLine(L"When a mission's reward can be increased by follower traits, groups can prioritize either the expected reward or mission success chance.", 1,1,1, 1)
GameTooltip:Show()
easyDrop:Close()
end)
b:SetScript("OnLeave", dismissTooltip)
end
interestUI.interestSet = CreateFrame("Button", nil, ctl) do
local b = interestUI.interestSet
b:SetSize(20, 20)
b:SetPoint("LEFT", 57, 0)
b:SetNormalTexture("Interface\\Minimap\\ObjectIcons")
b:SetHighlightTexture("Interface\\Minimap\\ObjectIcons")
local nt = b:GetNormalTexture()
nt:SetTexCoord(64/256, 96/256, 192/256, 224/256)
nt:SetVertexColor(0.8, 0.8, 0.8)
local ht = b:GetHighlightTexture()
ht:SetTexCoord(64/256, 96/256, 192/256, 224/256)
ht:SetAlpha(0.25)
local m = {
{isTitle=true, text=L"Desirable rewards", notCheckable=true, justifyH="CENTER"},
{arg1=118529},
{arg1=122484},
{arg1=120945},
{arg1=994},
{arg1=823},
{arg1=824},
{arg1=1101},
{arg1=0, text="|TInterface\\Icons\\INV_Misc_Coin_02:16:16:0:0:64:64:4:60:4:60|t " .. BONUS_ROLL_REWARD_MONEY},
{arg1=128315},
{arg1=128430},
{arg1=127748},
{arg1=128313},
{arg1=128316},
{arg1=128312},
{arg1=115280, text="|TInterface\\Minimap\\ObjectIcons:16:16:0:0:256:256:194:222:130:158|t |cffff8000" .. ITEM_QUALITY5_DESC},
}
local function toggleInterestBit(_, key)
T.config.interestMask = bit.bxor(T.config.interestMask, 2^(T.InterestMask[key]-1))
interestMissionsHandle:Show(not interestUI.excludeInactive:GetChecked())
end
local function checkInterestBit(self)
local b, m = T.InterestMask[self.arg1], T.config.interestMask
return (m % 2^b) < 2^(b-1)
end
local function ShowInterestFilterTip(self, arg1)
if type(arg1) ~= "number" or arg1 < 1 then return end
GameTooltip:SetOwner(self, "ANCHOR_NONE")
GameTooltip:SetPoint("TOPLEFT", self, "TOPRIGHT", 16, 8)
if arg1 < 2e3 then
GameTooltip:SetCurrencyByID(arg1)
else
GameTooltip:SetItemByID(Interest_RewardMap[arg1] or arg1)
end
end
for i=2,#m do
m[i].func, m[i].checked, m[i].isNotRadio, m[i].keepShownOnClick, m[i].tooltipOnButton = toggleInterestBit, checkInterestBit, true, true, ShowInterestFilterTip
end
b:SetScript("OnClick", function(self)
if m[#m].arg1 == 115280 and T.config.legendStep >= 2 then
m[#m] = nil
end
for i=2,#m do
local mi = m[i]
if (not mi.text or mi.placeholder) then
local key, name, ico, _ = mi.arg1
if key > 2e3 then
name, ico = GetItemInfo(key), GetItemIcon(key)
else
name, _, ico = GetCurrencyInfo(key)
end
mi.text, mi.placeholder = "|T" .. (ico or "Interaface\\Icons\\INV_Misc_QuestionMark") .. ":16:16:0:0:64:64:4:60:4:60|t " .. (name or ("#" .. key)), not name or nil
end
end
easyDrop:Toggle(self, m, "TOPLEFT", self, "BOTTOMLEFT", -78, -3)
end)
b:SetScript("OnEnter", function(self)
easyDrop:DelayOpenClick(self)
end)
b:SetScript("OnLeave", dismissTooltip)
end
end
interestUI:SetScript("OnShow", function(self)
missionList.ctlContainer:Steal(self, ctl)
interestMissionsHandle:Show(not interestUI.excludeInactive:GetChecked())
end)
end
do -- tabs
local activeTab = CreateFrame("Button", "GarrisonMissionFrameTab3", GarrisonMissionFrame, "GarrisonMissionFrameTabTemplate", 1)
local availTab, followerTab = GarrisonMissionFrameTab1, GarrisonMissionFrameTab2
local interestTab = CreateFrame("Button", "GarrisonMissionFrameTab4", GarrisonMissionFrame, "GarrisonMissionFrameTabTemplate", 1)
missionList.activeTab, missionList.availTab, missionList.interestTab, missionList.followerTab = activeTab, availTab, interestTab, followerTab
activeTab:SetPoint("LEFT", availTab, "RIGHT", -5, 0)
interestTab:SetPoint("LEFT", activeTab, "RIGHT", -5, 0)
activeTab.Pulse = activeTab:CreateAnimationGroup() do
local function cloneTexture(parent, key)
local t, o = parent:CreateTexture(nil, "BORDER"), parent[key]
t:SetTexture(o:GetTexture())
t:SetTexCoord(o:GetTexCoord())
t:SetAllPoints(o)
t:SetBlendMode(o:GetBlendMode())
return t
end
activeTab.p1, activeTab.p2 = cloneTexture(activeTab, "LeftHighlight"), cloneTexture(activeTab, "RightHighlight")
activeTab.p3, activeTab.p4 = cloneTexture(activeTab, "MiddleHighlight"), activeTab:CreateTexture(nil, "BACKGROUND", nil, 1)
activeTab.p4:SetPoint("TOPLEFT", activeTab.p3, "TOPLEFT", -16, -1)
activeTab.p4:SetPoint("BOTTOMRIGHT", activeTab.p3, "BOTTOMRIGHT", 6, 12)
activeTab.p4:SetTexture("Interface\\Buttons\\UI-ListBox-Highlight")
activeTab.p4:SetBlendMode("ADD")
activeTab.p4:SetTexCoord(16/128, 112/128, 0, 1)
local ag = activeTab.Pulse
ag:SetLooping("BOUNCE")
for i=1,4 do
local ap = ag:CreateAnimation("Alpha")
ap:SetDuration(1.25)
ap:SetFromAlpha(0)
ap:SetToAlpha(i < 4 and 0.5 or 0.2)
ap:SetChildKey("p" .. i)
end
ag:Play()
ag:SetScript("OnStop", function()
for i=1,4 do
activeTab["p" .. i]:SetAlpha(0)
end
end)
end
GarrisonMissionFrameTab2:SetPoint("LEFT", interestTab, "RIGHT", -5, 0)
PanelTemplates_DeselectTab(activeTab)
PanelTemplates_DeselectTab(interestTab)
local function ResizeTabs()
PanelTemplates_TabResize(activeTab, 10)
PanelTemplates_TabResize(availTab, 10)
PanelTemplates_TabResize(interestTab, 10)
end
hooksecurefunc("GarrisonMissionListTab_SetTab", function(self)
if missionList:IsShown() and self then
PanelTemplates_SetTab(GarrisonMissionFrame, self:GetID() == 2 and 3 or 1)
end
end)
local function SetTabState(tab, selected)
if selected == nil then
PanelTemplates_SetDisabledTabState(tab)
else
(selected and PanelTemplates_SelectTab or PanelTemplates_DeselectTab)(tab)
end
end
local updateMissionTabs = oncePerFrame(function()
local cm = GarrisonMissionFrame.MissionComplete.completeMissions
activeTab:SetFormattedText(L"Active Missions (%d)", math.max(#GarrisonMissionFrameMissions.inProgressMissions, cm and #cm or 0))
availTab:SetFormattedText(L"Available Missions (%d)", #GarrisonMissionFrameMissions.availableMissions)
interestTab:SetText(L"Missions of Interest")
ResizeTabs()
T.After0(ResizeTabs)
if #GarrisonMissionFrameMissions.inProgressMissions == 0 and (cm and #cm or 0) == 0 then
SetTabState(activeTab, nil)
else
SetTabState(activeTab, GarrisonMissionFrame.selectedTab == 3)
end
if not missionList:IsShown() then
SetTabState(interestTab, nil)
else
SetTabState(interestTab, GarrisonMissionFrame.selectedTab == 4)
end
SetTabState(availTab, GarrisonMissionFrame.selectedTab == 1)
SetTabState(followerTab, GarrisonMissionFrame.selectedTab == 2)
api.roamingParty:Update()
api:SetMissionsUI(GarrisonMissionFrame.selectedTab)
if GarrisonMissionFrame.selectedTab == 3 or #C_Garrison.GetCompleteMissions(1) == 0 then
activeTab.Pulse:Stop()
else
activeTab.Pulse:Play()
end
end)
T.UpdateMissionTabs = updateMissionTabs
hooksecurefunc(GarrisonMissionFrame, "UpdateMissions", updateMissionTabs)
GarrisonMissionFrame:HookScript("OnShow", updateMissionTabs)
hooksecurefunc("PanelTemplates_UpdateTabs", function(frame)
if frame == GarrisonMissionFrame then
updateMissionTabs()
end
end)
activeTab:SetScript("OnClick", function()
PlaySound("UI_Garrison_Nav_Tabs")
if GarrisonMissionFrame.MissionTab.MissionPage:IsShown() then
GarrisonMissionFrame.MissionTab.MissionPage.MinimizeButton:Click()
end
if GarrisonMissionFrame.selectedTab ~= 1 and GarrisonMissionFrame.selectedTab ~= 3 then
SetMissionsFrameTab(1)
end
PanelTemplates_SetTab(GarrisonMissionFrame, 3)
if not missionList:IsShown() then
GarrisonMissionListTab_SetTab(GarrisonMissionFrameMissionsTab2)
end
GarrisonMissionFrame:CheckCompleteMissions()
end)
availTab:SetScript("OnClick", function()
PlaySound("UI_Garrison_Nav_Tabs")
SetMissionsFrameTab(1)
if not missionList:IsShown() then
GarrisonMissionListTab_SetTab(GarrisonMissionFrameMissionsTab1)
end
end)
interestTab:SetScript("OnClick", function()
PlaySound("UI_Garrison_Nav_Tabs")
if GarrisonMissionFrame.MissionTab.MissionPage:IsShown() then
GarrisonMissionFrame.MissionTab.MissionPage.MinimizeButton:Click()
end
SetMissionsFrameTab(1)
PanelTemplates_SetTab(GarrisonMissionFrame, 4)
api:SetMissionsUI(4)
end)
hooksecurefunc("GarrisonMissionListTab_SetTab", updateMissionTabs)
function EV:GARRISON_MISSION_FINISHED()
if GarrisonMissionFrame:IsVisible() and GarrisonMissionFrame.selectedTab ~= 3 then
updateMissionTabs()
PlaySound("UI_Garrison_Toast_MissionComplete")
end
end
end
local GetActiveMissions, StartCompleteAll, CompleteMission, ClearCompletionState, GetFollowerXPAward do
local completionMissions, mark, completionFollowers = {}, {}
local function cmp(a,b)
local ac, bc = a.readyTime, b.readyTime
if (not ac) ~= (not bc) then
return not ac
elseif ac == bc then
ac, bc = strcmputf8i(a.name, b.name), 0
end
return ac < bc
end
function GetActiveMissions()
local rt, rn, now = {}, 1, time()
wipe(mark)
for i=1,#completionMissions do
rt[rn], rn, mark[completionMissions[i].missionID or 0] = completionMissions[i], rn + 1, 1
end
for j=1,2 do
local t = C_Garrison[j == 1 and "GetCompleteMissions" or "GetInProgressMissions"](1)
for i=1,#t do
local v = t[i]
if not mark[v.missionID] then
if j == 1 then
completionMissions[#completionMissions+1], v.readyTime = v, now - 1
end
G.ExtendMissionInfoWithXPRewardData(v)
if not v.readyTime then
local tls = v.followers and v.followers[1] and C_Garrison.GetFollowerMissionTimeLeftSeconds(v.followers[1])
v.readyTime = now + (tls or v.timeLeft and G.GetSecondsFromTimeString(v.timeLeft) or v.missionID/1000)
end
rt[rn], rn, mark[v.missionID or 0] = v, rn + 1, 1
end
end
end
table.sort(rt, cmp)
table.sort(completionMissions, cmp)
return rt
end
local function completeStep(state, stack, rew, fol, substate, mid)
if (state == "DONE" or state == "ABORT") and activeUI.completionState == "RUNNING" then
activeUI.completionState = state == "DONE" and "DONE" or nil
if next(rew) or next(fol) then
activeUI:SetCompletionRewards(rew, fol, #stack, not not substate)
elseif state == "DONE" then
activeUI.CompleteAll.ShowingHelp = true
HelpPlate_TooltipHide()
HelpPlateTooltip.ArrowDOWN:Show()
HelpPlateTooltip.ArrowGlowDOWN:Show()
HelpPlateTooltip:SetPoint("TOP", activeUI.CompleteAll, "BOTTOM", 0, -14)
HelpPlateTooltip.Text:SetText((L"No missions could be completed without exceeding currency caps, violating the %s setting."):format("|cffffd100" .. L"Require Currency Reward" .. "|r") .. "\n\n" .. L"To temporarily ignore wasted currency and complete the skipped missions, right-click this button, or left-click individual missions below.")
HelpPlateTooltip:Show()
end
end
if (substate == "FAIL" or substate == "COMPLETE") and mid then
PlaySoundKitID(substate == "FAIL" and 43501 or 43502, nil, false)
activeMissionsHandle:SetAnimation(mid, substate)
end
completionFollowers = fol
RefreshActiveMissionsView()
end
function StartCompleteAll()
wipe(completionMissions)
GetActiveMissions()
if #completionMissions > 0 then
activeUI.completionState = "RUNNING"
G.CompleteMissions(completionMissions, completeStep)
return true
end
end
function CompleteMission(mi)
GarrisonMissionFrame.MissionComplete:Show();
GarrisonMissionFrame.MissionCompleteBackground:Show();
GarrisonMissionFrame.MissionComplete.currentIndex = 1
GarrisonMissionFrame.MissionComplete.completeMissions = {mi}
GarrisonMissionFrame:MissionCompleteInitialize(GarrisonMissionFrame.MissionComplete.completeMissions, 1)
GarrisonMissionFrame.MissionComplete.NextMissionButton.returnToActiveList = true
end
function ClearCompletionState()
wipe(completionMissions)
completionFollowers = nil
end
function GetFollowerXPAward(fid)
local i = completionFollowers and completionFollowers[fid]
return i and i.xpAward
end
EV.MP_RELEASE_CACHES = ClearCompletionState
end
activeUI.CompleteAll:SetScript("OnClick", function(_, button)
PlaySound("UChatScrollButton")
if button ~= "RightButton" then
StartCompleteAll()
else
GarrisonMissionFrame.MissionComplete.completeMissions = C_Garrison.GetCompleteMissions(1)
GarrisonMissionFrameMissions.CompleteDialog.BorderFrame.ViewButton:Click()
end
end)
local core do
function api.createScrollList(parent, w, h)
local core, int, h = {}, {view={}}, h or 541
local sf, sc, bar = CreateFrame("ScrollFrame", nil, parent) do
sf:SetSize(w, h)
sf:SetPoint("CENTER")
bar = CreateFrame("Slider", nil, sf) do
bar:SetWidth(19)
bar:SetPoint("TOPRIGHT", 0, -6)
bar:SetPoint("BOTTOMRIGHT", 0, 8)
bar:SetThumbTexture("Interface\\Buttons\\UI-ScrollBar-Knob")
bar:GetThumbTexture():SetSize(18, 24)
bar:GetThumbTexture():SetTexCoord(0.20, 0.80, 0.125, 0.875)
bar:SetMinMaxValues(0, 100)
bar:SetValue(0)
local bg = bar:CreateTexture(nil, "BACKGROUND")
bg:SetPoint("TOPLEFT", 0, 16)
bg:SetPoint("BOTTOMRIGHT", 0, -14)
bg:SetColorTexture(0,0,0)
bg:SetAlpha(0.85)
local top = bar:CreateTexture(nil, "ARTWORK")
top:SetSize(24, 48)
top:SetPoint("TOPLEFT", -4, 17)
top:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-ScrollBar")
top:SetTexCoord(0, 0.45, 0, 0.20)
local bot = bar:CreateTexture(nil, "ARTWORK")
bot:SetSize(24, 64)
bot:SetPoint("BOTTOMLEFT", -4, -15)
bot:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-ScrollBar")
bot:SetTexCoord(0.515625, 0.97, 0.1440625, 0.4140625)
local mid = bar:CreateTexture(nil, "ARTWORK")
mid:SetPoint("TOPLEFT", top, "BOTTOMLEFT")
mid:SetPoint("BOTTOMRIGHT", bot, "TOPRIGHT")
mid:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-ScrollBar")
mid:SetTexCoord(0, 0.45, 0.1640625, 1)
local function Move(self)
if int.props then
bar:SetValue(bar:GetValue() - (2-self:GetID()) * int.props.entryHeight)
end
end
local up = CreateFrame("Button", nil, bar, "UIPanelScrollUpButtonTemplate", 1)
up:SetPoint("BOTTOM", bar, "TOP", 0, -2)
local down = CreateFrame("Button", nil, bar, "UIPanelScrollDownButtonTemplate", 3)
down:SetPoint("TOP", bar, "BOTTOM", 0, 2)
up:SetScript("OnClick", Move)
down:SetScript("OnClick", Move)
sf:SetScript("OnMouseWheel", function(_, direction)
(direction == 1 and up or down):Click()
end)
bar:SetScript("OnValueChanged", function(self, v, _isUserInteraction)
local _, x = self:GetMinMaxValues()
int:Update(v, true)
up:SetEnabled(v > 0)
down:SetEnabled(v < x)
end)
sf.Bar, bar.Up, bar.Down = bar, up, down
end
sc = CreateFrame("Frame", nil, sf) do
sc:SetSize(w-2, h+10)
sf:SetScrollChild(sc)
end
sf:SetScript("OnShow", function()
int:Update(bar:GetValue())
end)
missionList.FadeIn = {} do
local timeLeft
local function fadeInFinish()
sc:SetScript("OnUpdate", nil)
sc:SetScript("OnHide", nil)
sc:SetAlpha(1)
end
local function fadeIn(_, e)
timeLeft = timeLeft-e
if timeLeft < 0 then
fadeInFinish()
else
sc:SetAlpha(cos(timeLeft*360))
end
end
function missionList.FadeIn.Play()
timeLeft = 0.25
sc:SetScript("OnUpdate", fadeIn)
sc:SetScript("OnHide", fadeInFinish)
end
end
end
local function Release(keepMin, keepMax)
local t, w = int.view, int.props.widgets
for k,v in pairs(t) do
if k > keepMax or k < keepMin then
v:SetParent(nil)
v:ClearAllPoints()
v:Hide()
w[#w + 1], t[k] = v
end
end
end
function int:Update(ofs)
if not self.props then return end
if bar:GetValue() ~= ofs then return bar:SetValue(ofs) end
local entryHeight, bot, w = self.props.entryHeight, ofs + sf:GetHeight(), self.props.widgets
local baseIndex = (ofs - ofs % entryHeight) / entryHeight
local maxIndex = (bot + entryHeight - bot % entryHeight) / entryHeight
local minIndex, maxIndex, childLevel = max(1, baseIndex), min(#self.data, maxIndex), sc:GetFrameLevel()+1
Release(minIndex, maxIndex)
for i=minIndex,maxIndex do
local f = self.view[i]
if not f then
f, w[#w] = w[#w] or securecall(self.props.Spawn)
self.view[i] = f
end
if f then
f:SetID(i)
securecall(self.props.Update, f, self.data[i])
f:SetParent(sc)
f:SetFrameLevel(childLevel)
f:SetPoint("TOP", -10, ofs - 2 - (i-1)*entryHeight)
f:Show()
end
end
local mf = T.GetMouseFocus()
local oe = mf and T.IsDescendantOf(mf, sc) and mf:GetScript("OnEnter")
if mf and oe and mf.IsEnabled and mf:IsEnabled() then
oe(mf)
end
end
function core:SetData(data, propsHandle)
local reset = int.props ~= propsHandle
if int.props and reset then
Release(0, -1)
end
int.data, int.props = data, propsHandle
if data and propsHandle then
local mv = max(0, 3 + propsHandle.entryHeight * #data - sf:GetHeight())
bar:SetMinMaxValues(0, mv > 10 and mv or 0)
bar:GetScript("OnValueChanged")(bar, reset and 0 or bar:GetValue(), false)
else
bar:SetMinMaxValues(0, 0)
end
end
function core:GetRowData(handle, row)
local id = row:GetID()
if int.props == handle and int.data and int.view[id] == row then
return int.data[id]
end
end
function core:Refresh(handle)
if int.props == handle or handle == nil then
int:Update(bar:GetValue())
end
end
function core:SetShown(isShown)
sf:SetShown(isShown)
end
function core:IsShown()
return sf:IsShown()
end
function core:IsVisible()
return sf:IsVisible()
end
function core:IsOwned(propsHandle)
return int.props == propsHandle
end
function core:CreateHandle(createFunc, setFunc, entryHeight)
return {Spawn=createFunc, Update=setFunc, entryHeight=entryHeight, widgets={}}
end
return core, sf
end
core, missionList.List = api.createScrollList(missionList, 882)
end
do -- CreateMissionButton
local CreateRewards do
local function Reward_OnEnter(self)
if self.itemID then
GameTooltip:SetOwner(self, "ANCHOR_TOPRIGHT")
G.SetItemTooltip(GameTooltip, self.itemID)
elseif self.tooltipTitle and self.tooltipText then
GameTooltip:SetOwner(self, "ANCHOR_TOPRIGHT")
GameTooltip:AddLine(self.tooltipTitle)
GameTooltip:AddLine(self.tooltipText, 1,1,1,1)
if self.tooltipTitle == GARRISON_REWARD_MONEY then
G.SetCurrencyTraitTip(GameTooltip, 0, self.followerType)
end
elseif self.currencyID then
GameTooltip:SetOwner(self, "ANCHOR_TOPRIGHT")
GameTooltip:SetCurrencyByID(self.currencyID)
G.SetCurrencyTraitTip(GameTooltip, self.currencyID, self.followerType)
elseif self.bonusAbilityID and self.bonusInfo then
GameTooltip:SetOwner(self, "ANCHOR_TOPRIGHT")
GameTooltip:SetText(self.bonusInfo.name)
GameTooltip:AddLine(self.bonusInfo.description, 1,1,1,1)
GameTooltip:AddLine(" ")
GameTooltip:AddLine(GARRISON_BONUS_EFFECT_TIME_ACTIVE:format(SecondsToTime(self.bonusInfo.duration)))
else
return
end
if self:GetParent():IsEnabled() then
self:GetParent():LockHighlight()
end
if self.canIgnore then
local prompt = self.isIgnored and L"Unignore" or "Ignore"
GameTooltip:AddLine("|n|TInterface\\TUTORIALFRAME\\UI-TUTORIAL-FRAME:14:12:0:-1:512:512:10:70:330:410|t " .. prompt, 0.5, 0.8, 1)
end
GameTooltip:Show()
end
local function Reward_OnClick(self, button)
if self.canIgnore and button == "RightButton" then
local wasIgnored = self.isIgnored
MasterPlan:SetRewardIgnore(self.canIgnore, not wasIgnored or nil, IsAltKeyDown())
if wasIgnored and MasterPlan:IsRewardIgnored(self.canIgnore) then
MasterPlan:SetRewardIgnore(self.canIgnore, false, IsAltKeyDown())
end
elseif IsModifiedClick("CHATLINK") then
local qt, text, _ = self.quantity:GetText()
if self.itemID then
_, text = GetItemInfo(self.itemID)
elseif self.currencyID and self.currencyID ~= 0 then
text = GetCurrencyLink(self.currencyID)
elseif self.tooltipTitle then
text = self.tooltipTitle
end
qt = qt and not qt:match("|c") and qt or ""
if text and qt ~= "" and qt ~= "1" then
text = qt .. " " .. text
end
if text then
ChatEdit_InsertLink(text)
end
end
end
local function CreateReward(parent, h)
local r = CreateFrame("Button", nil, parent)
r:SetSize(h, h)
r:SetPoint("RIGHT", -12, 0)
r:RegisterForClicks("LeftButtonUp", "RightButtonUp")
local t = r:CreateTexture(nil, "BACKGROUND")
t:SetAtlas("GarrMission_RewardsShadow")
t:SetPoint("CENTER")
t:SetSize(h+4, h+4)
t = r:CreateTexture(nil, "BORDER")
t:SetPoint("CENTER")
t:SetSize(h+2, h+2)
t:Hide()
t, r.border = r:CreateTexture(nil, "BACKGROUND", nil, 1), t
t:SetAllPoints()
t:SetTexture("Interface\\ICONS\\Temp")
r.icon = t
t = r:CreateFontString(nil, "OVERLAY", "GameFontHighlightOutline")
local ins = h > 33 and 3 or 1
t:SetPoint("BOTTOMRIGHT", 2-ins, ins)
r.quantity = t
r:SetScript("OnEnter", Reward_OnEnter)
r:SetScript("OnLeave", dismissTooltipAndHighlight)
r:SetScript("OnHide", dismissTooltipAndHighlight)
r:SetScript("OnClick", Reward_OnClick)
return r
end
local rewardsMT = {__index=function(self, k)
local l = self[k-1]
local r = CreateReward(l:GetParent(), self._h)
r:SetPoint("RIGHT", l, "LEFT", -4, 0)
self[k] = r
return self[k]
end}
function CreateRewards(parent, h)
return setmetatable({_h=h, [1]=CreateReward(parent, h)}, rewardsMT)
end
end
local function RaiseVeil(self)
self:SetFrameLevel(self:GetParent():GetFrameLevel()+5)
end
function api.CreateMissionButton(h, w)
local b, w = CreateFrame("Button"), w or 845
b:SetSize(w, h)
local t = b:CreateTexture(nil, "BACKGROUND", nil, -1)
t:SetAtlas("GarrMission_MissionParchment", true)
t:SetPoint("TOPLEFT", 3, 0) t:SetPoint("BOTTOMRIGHT", -3, 0)
t:SetVertTile(true) t:SetHorizTile(true)
t = b:CreateTexture(nil, "BACKGROUND", nil, 1)
t:SetAtlas("!GarrMission_Bg-Edge", true)
t:SetVertTile(true)
t:SetPoint("TOPLEFT", -10, 0)
t:SetPoint("BOTTOMLEFT", -10, 0)
t = b:CreateTexture(nil, "BACKGROUND", nil, 1)
t:SetAtlas("!GarrMission_Bg-Edge", true)
t:SetVertTile(true)
t:SetPoint("TOPRIGHT", 10, 0)
t:SetPoint("BOTTOMRIGHT", 10, 0)
t:SetTexCoord(1,0, 0,1)
t = b:CreateTexture(nil, "BACKGROUND", nil, 2)
t:SetAtlas("_GarrMission_MissionListTopHighlight", true)
t:SetHorizTile(true)
t:SetPoint("TOPLEFT", 3, 0)
t:SetPoint("TOPRIGHT", -3, 0)
t = b:CreateTexture(nil, "BACKGROUND", nil, 2)
t:SetAtlas("_GarrMission_Bg-BottomEdgeSmall", true)
t:SetHorizTile(true)
t:SetPoint("BOTTOMLEFT", 3, 0)
t:SetPoint("BOTTOMRIGHT", -3, 0)
t = b:CreateTexture(nil, "BORDER")
t:SetAtlas("_GarrMission_TopBorder", true)
t:SetPoint("TOPLEFT", 20, 4)
t:SetPoint("TOPRIGHT", -20, 4)
t = b:CreateTexture(nil, "BORDER")
t:SetAtlas("_GarrMission_TopBorder", true)
t:SetPoint("BOTTOMLEFT", 20, -4)
t:SetPoint("BOTTOMRIGHT", -20, -4)
t:SetTexCoord(0,1, 1,0)
t = b:CreateTexture(nil, "BORDER", nil, 1)
t:SetAtlas("GarrMission_TopBorderCorner", true)
t:SetPoint("TOPLEFT", -5, 4)
t = b:CreateTexture(nil, "BORDER", nil, 1)
t:SetAtlas("GarrMission_TopBorderCorner", true)
t:SetPoint("TOPRIGHT", 6, 4)
t:SetTexCoord(1,0, 0,1)
t = b:CreateTexture(nil, "BORDER", nil, 1)
t:SetAtlas("GarrMission_TopBorderCorner", true)
t:SetPoint("BOTTOMLEFT", -5, -4)
t:SetTexCoord(0,1, 1,0)
t = b:CreateTexture(nil, "BORDER", nil, 1)
t:SetAtlas("GarrMission_TopBorderCorner", true)
t:SetPoint("BOTTOMRIGHT", 6, -4)
t:SetTexCoord(1,0, 1,0)
t = b:CreateTexture(nil, "HIGHLIGHT")
t:SetAtlas("_GarrMission_TopBorder-Highlight", true)
t:SetHorizTile(true)
t:SetPoint("TOPLEFT", 21, 4)
t:SetPoint("TOPRIGHT", -22, 4)
t = b:CreateTexture(nil, "HIGHLIGHT")
t:SetAtlas("_GarrMission_TopBorder-Highlight", true)
t:SetHorizTile(true)
t:SetPoint("BOTTOMLEFT", 21, -4)
t:SetPoint("BOTTOMRIGHT", -22, -4)
t:SetTexCoord(0,1, 1,0)
t = b:CreateTexture(nil, "HIGHLIGHT", nil, 1)
t:SetAtlas("GarrMission_TopBorderCorner-Highlight", true)
t:SetPoint("TOPLEFT", -5, 4)
t = b:CreateTexture(nil, "HIGHLIGHT", nil, 1)
t:SetAtlas("GarrMission_TopBorderCorner-Highlight", true)
t:SetPoint("TOPRIGHT", 4, 4)
t:SetTexCoord(1,0, 0,1)
t = b:CreateTexture(nil, "HIGHLIGHT", nil, 1)
t:SetAtlas("GarrMission_TopBorderCorner-Highlight", true)
t:SetPoint("BOTTOMLEFT", -5, -4)
t:SetTexCoord(0,1, 1,0)
t = b:CreateTexture(nil, "HIGHLIGHT", nil, 1)
t:SetAtlas("GarrMission_TopBorderCorner-Highlight", true)
t:SetPoint("BOTTOMRIGHT", 4, -4)
t:SetTexCoord(1,0, 1,0)
t = b:CreateTexture(nil, "HIGHLIGHT", nil, 1)
t:SetAtlas("GarrMission_ListGlow-Highlight")
t:SetGradient("VERTICAL", 0.5, 0.5, 0.5, 1,1,1)
t:SetPoint("TOPLEFT") t:SetPoint("TOPRIGHT")
t:SetHeight(30/44*h) -- SCALE
t = b:CreateTexture(nil, "BACKGROUND", nil, 5)
t:SetAtlas("Garr_MissionList-IconBG")
t:SetPoint("TOPLEFT", 0, -1)
t:SetPoint("BOTTOMLEFT", 0, 1)
t:SetWidth(46 + h) -- SCALE
t, b.iconBG = b:CreateTexture(nil, "ARTWORK"), t
t:SetPoint("LEFT", 56, 0) t:SetSize(h-16, h-16) -- SCALE
t, b.mtype = b:CreateFontString(nil, "ARTWORK", "Game30Font"), t
t:SetPoint("CENTER", b, "LEFT", 33, 0)
t:SetTextColor(0.84, 0.72, 0.57)
t, b.level = b:CreateFontString(nil, "ARTWORK", "QuestFont_Super_Huge"), t
t:SetPoint("LEFT", 52+h, 0) -- SCALE
t:SetTextColor(1,1,1)
t:SetShadowColor(0,0,0)
t:SetShadowOffset(1,-1)
t, b.title = b:CreateTexture(nil, "ARTWORK", nil, 2), t
t:SetAtlas("GarrMission_RareOverlay", true)
t:SetPoint("BOTTOMLEFT", -5, -4)
t, b.rare = CreateFrame("Frame", nil, b), t
t:SetScript("OnShow", RaiseVeil)
t, b.veil = t:CreateTexture(nil, "OVERLAY", nil, -1), t
t:SetAllPoints(b)
t:SetColorTexture(1,1,1)
t:SetGradient("VERTICAL", 0.8, 0.8, 0.8, 0.6, 0.6, 0.6)
t:SetBlendMode("MOD")
b.veil.tex, b.rewards = t, CreateRewards(b, 32/44*h)
b.rewards[1]:SetPoint("RIGHT", -14, 1)
return b
end
end
do -- CreateFollowerPortrait
local function Follower_OnEnter(self)
if self.followerID then
if self:GetParent():IsEnabled() then
self:GetParent():LockHighlight()
end
local info = C_Garrison.GetFollowerInfo(self.followerID)
FollowerTooltip_SetFollower(self, info, not self.showAbilityDescriptions)
if self.postEnter then
self:postEnter(info)
end
end
if GarrisonFollowerTooltip:GetTop() > self:GetBottom() then
GarrisonFollowerTooltip:ClearAllPoints()
GarrisonFollowerTooltip:SetPoint("BOTTOM", self, "TOP", 0, 2)
end
end
local function Follower_OnLeave(self)
GarrisonFollowerTooltip:Hide()
self:GetParent():UnlockHighlight()
end
function api.CreateFollowerPortrait(parent, size, id)
local x = CreateFrame("Button", nil, parent, nil, id)
x:SetSize(size, size)
local v = x:CreateTexture(nil, "ARTWORK", nil, 3)
v:SetPoint("TOPLEFT", 3, -3) v:SetPoint("BOTTOMRIGHT", -3, 3)
v, x.portrait = x:CreateTexture(nil, "ARTWORK", nil, 4), v
v:SetPoint("TOPLEFT", -2, 2) v:SetPoint("BOTTOMRIGHT", 2, -2)
v:SetAtlas("Garr_FollowerPortrait_Ring")
v, x.ring = x:CreateTexture(nil, "HIGHLIGHT"), v
v:SetPoint("TOPLEFT", -4, 2) v:SetPoint("BOTTOMRIGHT", 2, -2)
v:SetTexture("Interface\\Minimap\\UI-Minimap-ZoomButton-Highlight")
v:SetBlendMode("ADD")
v = x:CreateTexture(nil, "ARTWORK", nil, 5)
v:Hide()
v:SetTexture("Interface\\Buttons\\IconBorder-GlowRing")
v:SetPoint("TOPLEFT", 0,1)
v:SetPoint("BOTTOMRIGHT", -2,2)
v:SetBlendMode("ADD")
x.glow = v
x:SetScript("OnEnter", Follower_OnEnter)
x:SetScript("OnLeave", Follower_OnLeave)
x:SetScript("OnHide", Follower_OnLeave)
return x
end
end
local GroupButtonBase = {} do
local function GroupButton_OnMouseUp(self)
local tex = self.tex
for i=1,6 do
tex[i]:SetShown(i < 4)
end
end
local function GroupButton_OnMouseDown(self)
local tex, isDisabled = self.tex, self:GetButtonState() == "DISABLED"
for i=1,6 do
tex[i]:SetShown((i > 3) ~= isDisabled)
end
end
function GroupButtonBase:New(parent, id)
local b, bh, bw = CreateFrame("Button", nil, parent, nil, id), 24, 12
b:SetSize(120, bh)
local t, tt, tn = b:CreateTexture(nil, "BACKGROUND"), {}, 1
t:SetPoint("LEFT") t:SetSize(bw, bh)
t:SetTexture("Interface\\EncounterJournal\\UI-EncounterJournalTextures")
t:SetTexCoord(0.90039063, 0.925781255, 0.04980469, 0.07519531)
t, tt[tn], tn = b:CreateTexture(nil, "BACKGROUND"), t, tn + 1
t:SetPoint("RIGHT") t:SetSize(bw, bh)
t:SetTexture("Interface\\EncounterJournal\\UI-EncounterJournalTextures")
t:SetTexCoord(0.925781255, 0.95117188, 0.04980469, 0.07519531)
t, tt[tn], tn = b:CreateTexture(nil, "BACKGROUND"), t, tn + 1
t:SetPoint("TOPLEFT", bw, 0) t:SetPoint("BOTTOMRIGHT", -bw, 0)
t:SetTexture("Interface\\EncounterJournal\\UI-EncounterJournalTextures_Tile")
t:SetHorizTile(true)
t:SetTexCoord(0,1, 0.00195313, 0.05273438)
t, tt[tn], tn = b:CreateTexture(nil, "BACKGROUND"), t, tn + 1
t:SetPoint("LEFT") t:SetSize(bw, bh)
t:SetTexture("Interface\\EncounterJournal\\UI-EncounterJournalTextures")
t:SetTexCoord(0.63476563, 0.660156255, 0.06738281, 0.09277344)
t, tt[tn], tn = b:CreateTexture(nil, "BACKGROUND"), t, tn + 1
t:SetPoint("RIGHT") t:SetSize(bw, bh)
t:SetTexture("Interface\\EncounterJournal\\UI-EncounterJournalTextures")
t:SetTexCoord(0.660156255, 0.68554688, 0.06738281, 0.09277344)
t, tt[tn], tn = b:CreateTexture(nil, "BACKGROUND"), t, tn + 1
t:SetPoint("TOPLEFT", bw, 0) t:SetPoint("BOTTOMRIGHT", -bw, 0)
t:SetTexture("Interface\\EncounterJournal\\UI-EncounterJournalTextures_Tile")
t:SetHorizTile(true)
t:SetTexCoord(0,1, 0.05664063, 0.10742188)
t, tt[tn], tn = b:CreateTexture(nil, "HIGHLIGHT"), t, tn + 1
t:SetTexture("Interface\\EncounterJournal\\UI-EncounterJournalTextures")
t:SetTexCoord(0.72656250, 0.751953125, 0.06738281, 0.09277344)
t:SetSize(bw, bh) t:SetPoint("LEFT")
t = b:CreateTexture(nil, "HIGHLIGHT")
t:SetTexture("Interface\\EncounterJournal\\UI-EncounterJournalTextures")
t:SetTexCoord(0.751953125, 0.77734375, 0.06738281, 0.09277344)
t:SetSize(bw, bh) t:SetPoint("RIGHT")
t = b:CreateTexture(nil, "HIGHLIGHT")
t:SetTexture("Interface\\EncounterJournal\\UI-EncounterJournalTextures_Tile")
t:SetTexCoord(0,1, 0.11132813,0.16210938) t:SetHorizTile(true)
t:SetPoint("TOPLEFT", bw, 0) t:SetPoint("BOTTOMRIGHT", -bw, 0)
b.tex = tt
GroupButton_OnMouseUp(b, true)
b:SetPushedTextOffset(0, -1)
b:SetNormalFontObject(GameFontHighlightSmall)
b:SetText("!")
b:GetFontString():SetTextColor(0.973, 0.902, 0.581)
b:SetMotionScriptsWhileDisabled(true)
b:RegisterForClicks("LeftButtonUp", "RightButtonUp")
b:SetScript("OnMouseDown", GroupButton_OnMouseDown)
b:SetScript("OnMouseUp", GroupButton_OnMouseUp)
return b
end
function GroupButtonBase:ShowTooltip(mi, canSetTentative, invert, g, ug)
if g or ug then
GameTooltip:SetOwner(self, "ANCHOR_PRESERVE")
GameTooltip:ClearAllPoints()
if invert then
GameTooltip:SetPoint("TOPLEFT", self, "BOTTOMLEFT", -6, 0)
else
GameTooltip:SetPoint("BOTTOMLEFT", self, "TOPLEFT", -6, 0)
end
if g then
G.SetGroupTooltip(GameTooltip, g, mi)
if canSetTentative then
GameTooltip:AddLine("|TInterface\\TUTORIALFRAME\\UI-TUTORIAL-FRAME:14:12:0:-1:512:512:10:70:330:410|t " .. L"Set tentative party", 0.5, 0.8, 1)
end
else
G.SetUpGroupTooltip(GameTooltip, ug, mi)
end
GameTooltip:Show()
end
end
function GroupButtonBase:SetGroup(mi, g, minGroupButtonWidth, widthStep, rt, p1)
local sc, sp, text = "|cffffffff" .. g[1] .. "%", g[1]/100
local edt, ec, et, isxp, _, exp, tf = G.GetMissionGroupDeparture(g, mi), g[3]*sp, g[9]
if ec > 0 and et == 824 then
text = ("%d |TInterface\\Garrison\\GarrisonCurrencyIcons:0:0:0:0:128:128:12:52:12:52|t"):format(ec)
elseif ec > 0 and et == 1101 then
text = ("%d|TInterface\\Garrison\\GarrisonCurrencyIcons:0:0:0:2:128:128:70:104:68:104|t"):format(ec)
elseif ec > 0 and et == 823 then
text = ec .. " |T" .. select(3,GetCurrencyInfo(et)) .. ":0:0:0:1:64:64:4:60:4:60|t"
elseif ec >= 1e4 and et == 0 and G.HasSignificantRewards(mi) == "gold" then
text = GetMoneyString(ec - ec % 1e4)
else
if p1 and (g[11] and g[11] > 0) then
tf, exp = "|cffd0ff73%s|r", g[11]
else
_, exp = G.GetMissionGroupXP(g, mi)
end
if (exp or 0) <= 0 then
elseif T.config.availableMissionSort == "xptime" then
text, isxp = (L"%s XP/h"):format(abridge(floor(exp*3600/g[4]))), true
else
text, isxp = (L"%s XP"):format(abridge(floor(exp))), true
end
text = tf and tf:format(text) or text
end
if edt then
if text and not isxp then
text = text .. ", " .. sc
elseif rt == "threats" or not text then
text = sc
end
text = "|cffb0b0b0" .. FormatCountdown(edt-time()) .. ": " .. text
else
text = (text and text .. ", " or "") .. sc
end
self:SetEnabled(not edt)
self:SetText(text)
local bw = self:GetFontString():GetStringWidth()+14
bw = math.max(minGroupButtonWidth, bw)
self:SetWidth(bw + (widthStep - bw % widthStep) % widthStep)
self:Show()
end
end
do -- activeMissionsHandle
local anim = {}
local function ActiveFollower_OnEnter(self, info)
if info then
local award = GetFollowerXPAward(info.followerID)
if award then
G.ExtendFollowerTooltipGainedXP(GarrisonFollowerTooltip, award, info)
else
local row = core:GetRowData(activeMissionsHandle, self:GetParent())
G.ExtendFollowerTooltipProjectedRewardXP(row, info)
end
end
end
local function ActiveMission_OnClick(self)
local mi = core:GetRowData(activeMissionsHandle, self)
if IsModifiedClick("CHATLINK") then
local missionLink = C_Garrison.GetMissionLink(mi.missionID)
if (missionLink) then
ChatEdit_InsertLink(missionLink)
end
elseif mi.readyTime and mi.readyTime < time() and not (mi.succeeded or mi.failed) and activeUI.completionState ~= "RUNNING" then
CompleteMission(mi)
elseif SpellCanTargetGarrisonMission() then
C_Garrison.CastSpellOnMission(mi.missionID)
end
end
local function Banner_OnPlay(self)
local par = self:GetParent()
local fail = self == par.Fail
par.banner:SetVertexColor(fail and 1 or 0.2, fail and 0.2 or 1, 0.2)
par.banner:Show()
end
local function Banner_OnStop(self)
local par = self:GetParent()
par.banner:Hide()
end
local function RefreshTimeOnShow(self)
local ou = self:GetScript("OnUpdate")
if ou then
ou(self, math.huge)
end
end
local function CreateActiveMission()
local b = api.CreateMissionButton(44)
b:SetScript("OnClick", ActiveMission_OnClick)
b:SetScript("OnShow", RefreshTimeOnShow)
local t = b:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge")
t:SetPoint("RIGHT", -160, 0)
t:SetTextColor(0.84, 0.72, 0.57)
b.status = t
t = b:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge")
t:SetPoint("CENTER", b, "RIGHT", -120, 0)
t:SetTextColor(0.84, 0.72, 0.57)
b.chance = t
t = b:CreateTexture(nil, "OVERLAY")
t:SetAtlas("GarrMission_LevelUpBanner")
t:SetPoint("CENTER", 0, -1) t:SetSize(832*1.3, 44*2.85)
t:SetBlendMode("ADD")
t:SetAlpha(0)
b.banner = t
for i=1,2 do
local g = b:CreateAnimationGroup()
g:SetToFinalAlpha(true)
g:SetScript("OnPlay", Banner_OnPlay)
g:SetScript("OnStop", Banner_OnStop)
t = g:CreateAnimation("Alpha")
t:SetChildKey("banner")
t:SetFromAlpha(0) t:SetToAlpha(1)
t:SetDuration(0.2)
t = g:CreateAnimation("Scale")
t:SetChildKey("banner")
t:SetFromScale(0.3, 1) t:SetToScale(1, 1)
t:SetDuration(0.4)
t = g:CreateAnimation("Alpha")
t:SetChildKey("banner")
t:SetStartDelay(0.4) t:SetDuration(0.5)
t:SetFromAlpha(1) t:SetToAlpha(0)
b[i == 1 and "Fail" or "Success"] = g
end
b.followers = {}
for i=1,3 do
t = api.CreateFollowerPortrait(b, 32, i)
t:SetPoint("RIGHT", -265-34*i, 1)
t.postEnter, b.followers[i] = ActiveFollower_OnEnter, t
end
return b
end
local function TimerUpdate(self, elapsed)
local te = self.throttle or 0
if te > elapsed then
self.throttle = te - elapsed
return
end
local mi = core:GetRowData(activeMissionsHandle, self)
if mi and mi.readyTime and mi.state ~= 0 then
local sec = mi.readyTime - time()
if sec > 0 then
self.status:SetText(G.GetTimeStringFromSeconds(sec))
end
if sec < -1 then
self:SetScript("OnUpdate", nil)
RefreshActiveMissionsView(false)
else
self.throttle = sec > 60 and ((sec % 60 - 1) % 60 + 2) or 1
end
end
end
local function SetActiveMission(self, d)
local mid = d.missionID
self.level:SetText((d.isRare and "|cff4DB5FF" or "") .. (d.level == 100 and d.iLevel > 600 and d.iLevel or d.level))
self.rare:SetShown(d.isRare or false)
self.iconBG:SetVertexColor(0, d.isRare and 0.012 or 0, d.isRare and 0.291 or 0, 0.4)
self.mtype:SetAtlas(d.typeAtlas)
self.title:SetText(d.name)
local tl, col, state = d.readyTime-time(), ""
self:SetScript("OnUpdate", nil)
if tl > 0 then
self:SetScript("OnUpdate", TimerUpdate)
TimerUpdate(self, math.huge)
state = G.GetTimeStringFromSeconds(tl)
elseif d.failed then
col, state = "|cffff2020", L"Failed"
elseif d.skipped then
col, state = "|cffb0ff20", L"Skipped"
elseif d.succeeded or d.completed or (d.state and d.state >= 0) then
col, state = "|cff20ff20", L"Success"
else
col, state = "|cffffea10", L"Ready"
end
self.status:SetText(col .. state)
self.chance:SetText(d.successChance and (d.successChance .. "%") or "")
local sanim = anim[mid]
if sanim or (self.Fail.id ~= mid and (self.Fail:IsPlaying() or self.Success:IsPlaying())) then
self.Fail.id = mid
self.Fail:Stop()
self.Success:Stop()
if sanim then
self[sanim == "COMPLETE" and "Success" or "Fail"]:Play()
end
end
local nr, nf, r = 1, 1
if type(d.followers) == "table" then
local fin, fi, w = G.GetFollowerInfo()
for i=1,#d.followers do
fi, w = fin[d.followers[i]], self.followers[nf]
if fi and w then
w.followerID, nf = fi.followerID, nf + 1
w.portrait:SetTexture(fi.portraitIconID)
local ct = (fi.level < 100 or fi.quality < 4) and ITEM_QUALITY_COLORS[fi.quality]
if ct then
w.glow:SetVertexColor(ct.r, ct.g, ct.b)
w.glow:Show()
else
w.glow:Hide()
end
w:Show()
end
end
end
if type(d.rewards) == "table" then
for k,v in pairs(d.rewards) do
local icon, quant = v.icon, v.quantity ~= 1 and v.quantity
r, nr = self.rewards[nr], nr + 1
r.itemID, r.tooltipTitle, r.tooltipText, r.currencyID = v.itemID, v.title, v.tooltip, v.currencyID
if v.followerXP then
quant = abridge(v.followerXP)
elseif v.currencyID then
quant = v.quantity * G.GetRewardMultiplier(d, v.currencyID)
if v.currencyID == 0 then
quant, r.tooltipText = abridge(quant/10000), GetMoneyString(quant)
else
quant = abridge(quant)
end
elseif v.itemID then
local _, _, q, l, _, _, _, _, _, tex = GetItemInfo(v.itemID)
l, icon = T.CrateLevels[v.itemID] or l, tex or GetItemIcon(v.itemID)
if v.quantity == 1 and q and l and l > 500 then
quant = ITEM_QUALITY_COLORS[q].hex .. l
end
end
r.quantity:SetText(quant or "")
r.icon:SetTexture(icon or "Interface/Icons/Temp")
r:Show()
end
end
for i=nr, #self.rewards do
self.rewards[i]:Hide()
end
for i=nf, #self.followers do
self.followers[i]:Hide()
end
self.veil:SetShown(tl > 0)
end
activeMissionsHandle = core:CreateHandle(CreateActiveMission, SetActiveMission, 48)
function activeMissionsHandle:Activate(force)
if force then
ClearCompletionState()
end
local am, hasComplete = GetActiveMissions(), false
for i=1,#am do
local m = am[i]
if m.readyTime <= time() and not (m.succeeded or m.failed) then
hasComplete = true
break
end
end
core:SetData(am, activeMissionsHandle)
wipe(anim)
activeUI.CompleteAll:SetShown(not activeUI.lootFrame:IsShown() and (hasComplete and activeUI.completionState ~= "RUNNING"))
if force then
if #am == 0 then
SetMissionsFrameTab(1)
end
end
end
function activeMissionsHandle:SetAnimation(mid, state)
anim[mid] = state
end
end
do -- availMissionsHandle
local used = {}
local CreateThreat, SetThreat = {} do
local GetThreatColor do
local threatColors={[0]={1,0,0}, {0.15, 0.45, 1}, {0.20, 0.45, 1}, {1, 0.55, 0}, {0,1,0}}
function GetThreatColor(counters, missionLevel, finfo, threatID, used)
if not missionLevel then return 1,1,1 end
local finfo, quality, bk = finfo or G.GetFollowerInfo(), 0
for i=1,counters and #counters or 0 do
local fi = finfo[counters[i]]
local ld, mt = G.GetLevelEfficiency(G.GetFMLevel(fi), missionLevel), fi.missionEndTime and 0 or 2
local uk = fi.isCombat and (threatID .. "#" .. i)
if not fi.isCombat or (used and used[uk]) or T.config.ignore[fi.followerID] then
elseif ld == 1 and quality < (2+mt) then
quality, bk = 2+mt, uk
if mt == 2 then break end
elseif ld == 0.5 and quality < (1+mt) then
quality, bk = 1+mt, uk
end
end
if bk then used[bk] = 1 end
return unpack(threatColors[quality])
end
end
local function Threat_OnEnter(self)
self:GetParent():LockHighlight()
GameTooltip:SetOwner(self, "ANCHOR_TOP")
G.SetThreatTooltip(GameTooltip, self.id, nil, self.missionLevel)
GameTooltip:Show()
end
function CreateThreat(parent)
local b = CreateFrame("Button", nil, parent, "GarrisonAbilityCounterTemplate")
b:SetScript("OnEnter", Threat_OnEnter)
b:SetScript("OnLeave", dismissTooltipAndHighlight)
return b
end
function SetThreat(self, icon, threatID, level, counters, followers, used)
self.id, self.missionLevel = threatID, level
self.Icon:SetTexture(icon)
self.Border:SetVertexColor(GetThreatColor(counters, level, followers, threatID, used))
self:Show()
end
end
local CreateGroupButton do
local function GroupButton_OnEnter(self)
self:GetParent():LockHighlight()
local mi = core:GetRowData(availMissionsHandle, self:GetParent())
local g = mi.groups and mi.groups[self:GetID()]
GroupButtonBase.ShowTooltip(self, mi, self:IsEnabled(), false, g, mi.upgroup)
end
local function GroupButton_OnClick(self, button)
local mi = core:GetRowData(availMissionsHandle, self:GetParent())
local g = mi.groups and mi.groups[self:GetID()]
if not g then
local ug, ss = mi.upgroup
for i=1,mi.numFollowers do
ss = (ss and ss .. "/" or "") .. C_Garrison.GetFollowerName(ug[i])
end
local sb = GarrisonMissionFrameFollowers.SearchBox
sb:SetText(ss)
sb.clearText = ss
local ifid = G.GetUnderLevelledFollower(ug, mi) or ug[1]
GarrisonMissionFrameTab2:Click()
GarrisonMissionFrame.selectedFollower = ifid
GarrisonMissionFrame.FollowerTab.followerList:ShowFollower(ifid)
EV("MP_FORCE_FOLLOWER_TAB", ifid)
elseif button == "RightButton" then
G.SaveMissionParty(mi.missionID, g[5], g[6], g[7])
api.roamingParty:DropFollowers(g[5], g[6], g[7])
else
OpenToMission(mi, g[5], g[6], g[7])
end
end
function CreateGroupButton(...)
local b = GroupButtonBase:New(...)
b:SetScript("OnEnter", GroupButton_OnEnter)
b:SetScript("OnLeave", dismissTooltipAndHighlight)
b:SetScript("OnClick", GroupButton_OnClick)
return b
end
end
local function AvailMission_OnClick(self)
local mi = core:GetRowData(availMissionsHandle, self)
if IsModifiedClick("CHATLINK") then
local missionLink = C_Garrison.GetMissionLink(mi.missionID)
if (missionLink) then
ChatEdit_InsertLink(missionLink)
end
elseif mi.missionID then
OpenToMission(mi)
end
end
local function CreateAvailMission()
local b = api.CreateMissionButton(64)
b.title:ClearAllPoints()
b.title:SetPoint("TOPLEFT", 68+48, -9)
b.level:ClearAllPoints()
b.level:SetPoint("CENTER", b, "LEFT", 31, 4)
b:SetScript("OnClick", AvailMission_OnClick)
local t = b:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge2")
t:SetPoint("BOTTOMLEFT", b.title, "BOTTOMRIGHT", 6, 0)
t:SetTextColor(0.8, 0.8, 0.8)
t, b.stats = b:CreateTexture(nil, "BACKGROUND", nil, 3), t
t:SetSize(780, 62)
t:SetPoint("RIGHT")
t, b.loc = b:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall"), t
t:SetTextColor(0.84, 0.72, 0.57)
t:SetPoint("TOP", b, "TOPLEFT", 78, -5)
t, b.expire = b:CreateFontString(nil, "ARTWORK", "GameFontNormal"), t
t:SetPoint("TOP", b.level, "BOTTOM", 0, -1)
t, b.followers = {}, t
for i=1,7 do
t[i] = CreateThreat(b)
end
t[1]:SetPoint("TOPRIGHT", b, "RIGHT", -128, 23)
t[3]:SetPoint("BOTTOMRIGHT", b, "RIGHT", -143, -21)
t[2]:SetPoint("RIGHT", t[1], "LEFT", -9, 0)
t[4]:SetPoint("RIGHT", t[3], "LEFT", -9, 0)
t[5]:SetPoint("RIGHT", t[2], "LEFT", -9, 0)
t[6]:SetPoint("RIGHT", t[4], "LEFT", -9, 0)
t[7]:SetPoint("RIGHT", t[5], "LEFT", -9, 0)
t, b.threats = {}, t
for i=1,4 do
t[i] = CreateGroupButton(b, i)
t[i]:SetPoint("LEFT", t[i-1], "RIGHT", 4, 0)
end
t[1]:ClearAllPoints()
t[1]:SetPoint("BOTTOMLEFT", 112, 5)
b.groups = t
return b
end
local function SetAvailableMission(self, d)
self.level:SetText((d.isRare and "|cff4DB5FF" or "") .. (d.level == 100 and d.iLevel > 600 and d.iLevel or d.level))
self.rare:SetShown(d.isRare or false)
self.iconBG:SetVertexColor(0, d.isRare and 0.012 or 0, d.isRare and 0.291 or 0, 0.4)
self.mtype:SetAtlas(d.typeAtlas)
self.title:SetText(d.name)
local summary = d.duration
if d.durationSeconds >= GARRISON_LONG_MISSION_TIME then
summary = format(GARRISON_LONG_MISSION_TIME_FORMAT, summary)
end
self.stats:SetFormattedText(PARENS_TEMPLATE, summary)
local _, _, expTimeShort = G.GetMissionSeen(d.missionID, d)
self.expire:SetText(expTimeShort or "")
if d.locPrefix then
self.loc:SetAtlas(d.locPrefix.."-List")
end
self.loc:SetShown(not not d.locPrefix)
local fol = "" do
local nf = G.HasTentativeParty(d.missionID)
for i=1, d.numFollowers do
fol = fol .. "|TInterface\\FriendsFrame\\UI-Toast-FriendOnlineIcon:11:11:3:0:32:32:8:24:8:24:" ..
(nf < i and "214:170:115|t" or "255:180:0|t")
end
end
self.followers:SetText(fol)
local nr, isIgnored = 1, d.ord0 == -1
if type(d.rewards) == "table" then
for k,v in pairs(d.rewards) do
local icon, quant, r = v.icon, v.quantity ~= 1 and v.quantity
r, nr = self.rewards[nr], nr + 1
r.itemID, r.tooltipTitle, r.tooltipText, r.currencyID, r.isIgnored, r.canIgnore = v.itemID, v.title, v.tooltip, v.currencyID, isIgnored
r.border:Hide()
if v.followerXP then
quant, r.canIgnore = v.followerXP, d.level == 100 and "f:xp10" or d.level < 95 and "f:xp90" or "f:xp95"
elseif v.currencyID == 0 then
quant = floor(v.quantity/10000)
r.tooltipText, r.canIgnore = GetMoneyString(v.quantity), "c:0"
elseif v.currencyID then
r.canIgnore = "c:" .. v.currencyID
elseif v.itemID then
local _, _, q, l, _, _, _, _, _, tex = GetItemInfo(v.itemID)
r.canIgnore, icon, l = "i:" .. v.itemID, tex or GetItemIcon(v.itemID), T.CrateLevels[v.itemID] or l
if v.quantity == 1 and q and l and l > 500 then
quant = ITEM_QUALITY_COLORS[q].hex .. l
if G.IsLevelAppropriateToken(v.itemID) then
local ac = q == 3 and "blue" or q == 4 and "purple" or "green"
r.border:SetAtlas("loottoast-itemborder-" .. ac)
r.border:Show()
end
end
end
if r.canIgnore and not isIgnored and MasterPlan:IsRewardIgnored(r.canIgnore) then
r.isIgnored = true
end
r.quantity:SetText(quant or "")
r.icon:SetTexture(icon or "Interface/Icons/Temp")
r.icon:SetDesaturated(r.isIgnored)
if r.isIgnored then
r.icon:SetVertexColor(0.8,0.4,0.4)
elseif isIgnored then
r.icon:SetVertexColor(0.8,0.6,0.6)
else
r.icon:SetVertexColor(1,1,1)
end
r:Show()
end
end
for i=nr, #self.rewards do
self.rewards[i]:Hide()
end
local cinfo, finfo, mlvl = G.GetCounterInfo(), G.GetFollowerInfo(), G.GetFMLevel(d)
local enemies, ename, edesc, etex, _ = d.enemies, d.envName, d.envDescription, d.envTexture
if not (enemies and ename and edesc and etex) then
_, _, ename, edesc, etex, _, _, enemies = C_Garrison.GetMissionInfo(d.missionID)
d.enemies, d.envName, d.envDescription, d.envTexture = enemies, ename, edesc, etex
end
local nt, tt, used = 1, self.threats, wipe(used) or used
for i=1,#enemies do
for id, minfo in pairs(enemies[i].mechanics) do
nt = nt + 1, SetThreat(tt[nt], minfo.icon, id, mlvl, cinfo[id], finfo, used)
end
end
for i=nt,#tt do
tt[i]:Hide()
end
local sg, p1, p2, p3 = d.groups, api.roamingParty:GetFollowers()
p1 = not (p2 and p3) and p1
local minGroupButtonWidth = GetLocale():match("zh") and 125 or 110
for i=1,#sg do
GroupButtonBase.SetGroup(self.groups[i], d, sg[i], minGroupButtonWidth, 10, sg.rankType, p1)
end
for i=#sg + (d.upgroup and 2 or 1), #self.groups do
self.groups[i]:Hide()
end
if d.upgroup and self.groups[#sg+1] then
local b = self.groups[#sg+1]
b:SetText("|TInterface\\Buttons\\UI-MicroStream-Green:0:0:0:0:32:32:6:24:24:6|t")
b:Enable()
b:SetWidth(25)
b:Show()
end
self.veil:SetShown(d.ord0 == -3)
end
local GetAvailableMissions do
local roamingParty = api.roamingParty
local function cmp(a,b)
local ac, bc = a.ord0, b.ord0
if ac == bc then
ac, bc = a.ord, b.ord
end
if ac == bc then
ac, bc = a.ord1, b.ord1
end
if ac == bc then
ac, bc = a.level, b.level
end
if ac == bc then
ac, bc = a.iLevel, b.iLevel
end
if ac == bc then
ac, bc = 0, strcmputf8i(a.name, b.name)
end
return ac > bc
end
local fields, eg, cw = {threats=1}, {0, [3]=0,[4]=0, [9]=0, [11]=0}, {}
local function sortMissions(missions, nf, nr)
local order, horizon = T.config.availableMissionSort, T.config.timeHorizon
local field = fields[order] or 1
local groupCache = G.GetSuggestedGroupsForAllMissions(1, order, roamingParty:GetFollowers())
local checkReq = (nf < 3 or nr < 100) and T.config.availableMissionSort ~= "expire"
local p1, p2, p3 = api.roamingParty:GetFollowers()
p1 = not (p2 and p3) and p1
if p1 then
local f1 = G.GetFollowerInfo()[p1]
if not (f1 and (f1.level < 100 or f1.quality < 4)) then
p1 = nil
end
end
local _, resq = GetCurrencyInfo(824)
cw[824] = resq < 3e3 and 10 or (resq < 7e3 and 6 or 3)
local _, oilq = GetCurrencyInfo(1101)
cw[1101] = C_Garrison.HasShipyard() and (oilq < 1e3 and 11 or 2) or 1
cw[823], cw[0], cw.minor = 4, 5, 1.5
for i=1, #missions do
local mi, g = missions[i]
local mid, sr = mi.missionID, G.HasSignificantRewards(mi)
local sg = groupCache[mid]
mi.groups, g = sg, sg[1] and not G.GetMissionGroupDeparture(sg[1], mi) and sg[1] or eg
mi.ord1 = (cw[g[9]] or cw[sr] or (sr and 8) or 0) * 1e16 + g[1]*g[3]*1e3 + (sr and g[1] or 0)
if order == "duration" then
mi.ord = -mi.durationSeconds
elseif order == "expire" then
local max = mi.offerEndTime or G.GetMissionSeen(mid, mi)
mi.ord = (max or -1) >= 0 and -floor(max/1800) or -math.huge
elseif order == "level" then
local i, l = mi.iLevel, mi.level
mi.ord = l == 100 and i > 600 and i or l
elseif order == "reward" then
mi.ord, mi.ord1 = mi.ord1, (g[11] or 0)*1e8 + ((g[5] and G.GetMissionGroupXP(g, mi) or 0)) * 100 + (g and g[1] or 0)
elseif g[5] and (order == "xp" or order == "xptime") then
local xp = p1 and (g[11] or 0) or G.GetMissionGroupXP(g, mi) or 0
mi.ord = order == "xptime" and xp/max(g[4], horizon) or xp
else
mi.ord = g[5] and g[field] or -math.huge
end
local tc = G.HasTentativeParty(mid)
if tc == mi.numFollowers then
mi.ord0 = -2
elseif checkReq and mi.numFollowers > (nf + tc) or (mi.cost > nr) then
mi.ord0 = -3
elseif MasterPlan:IsMissionIgnored(mi) then
mi.ord0 = -1
else
mi.ord0 = 0
end
end
table.sort(missions, cmp)
end
function GetAvailableMissions()
local missions, droppedMissionCost = G.GetAvailableMissions(1)
securecall(sortMissions, missions, GetAvailableResources(1, droppedMissionCost, missions))
local job = securecall(G.GetSuggestedMissionUpgradeGroups, missions, roamingParty:GetFollowers())
availUI.loader.job = job
if job then
availUI.loader:Show()
end
GarrisonMissionFrame.MissionTab.MissionList.EmptyListString:SetText(#missions > 0 and "" or GARRISON_EMPTY_MISSION_LIST)
return missions
end
end
local timeToNextRefresh = 0
availUI:SetScript("OnUpdate", function(_, elapsed)
if timeToNextRefresh < elapsed then
availMissionsHandle:Refresh(false)
else
timeToNextRefresh = timeToNextRefresh - elapsed
end
end)
function availUI.loader.OnFinish()
availMissionsHandle:Refresh(false)
end
availMissionsHandle = core:CreateHandle(CreateAvailMission, SetAvailableMission, 67)
function availMissionsHandle:Activate(full)
timeToNextRefresh = 60
if full then
core:SetData(GetAvailableMissions(), availMissionsHandle)
else
core:Refresh(availMissionsHandle)
end
end
function availMissionsHandle:Refresh(reload)
if core:IsOwned(self) and core:IsShown() then
if availUI:IsVisible() then
availMissionsHandle:Activate(reload)
else
core:SetData()
end
end
end
do -- RefreshAvailMissionsView
local isFullRefresh, ph, isDirty = true, {}
local function DoRefresh()
local reload = isFullRefresh
isDirty, isFullRefresh = nil
availMissionsHandle:Refresh(reload)
end
function RefreshAvailMissionsView(force)
if core:IsShown() and (force or core:IsOwned(availMissionsHandle)) then
if not isDirty then
isDirty, isFullRefresh = true, isFullRefresh or force or not core:IsOwned(availMissionsHandle)
if not core:IsOwned(availMissionsHandle) then
core:SetData(ph, availMissionsHandle)
end
T.After0(DoRefresh)
end
end
end
function EV:GARRISON_MISSION_LIST_UPDATE()
if availUI:IsVisible() then
RefreshAvailMissionsView(true)
end
end
end
function EV:MP_SETTINGS_CHANGED(s)
if s == "availableMissionSort" or s == "timeHorizon" or s == "missionIgnore" then
availMissionsHandle:Refresh(true)
end
end
function EV:MP_TENTATIVE_PARTY_UPDATE()
if availUI:IsVisible() then
RefreshAvailMissionsView(true)
end
end
end
do -- interestMissionsHandle
local usefulTraits, mappedRewards = setmetatable({}, T.AlwaysTraits), Interest_RewardMap
local function Threat_OnEnter(self)
GameTooltip:SetOwner(self, "ANCHOR_TOP")
G.SetThreatTooltip(GameTooltip, self.id, nil, self.missionLevel)
GameTooltip:Show()
end
local function CreateThreat(parent)
local b = CreateFrame("Frame", nil, parent)
b:SetSize(21, 21)
local t = b:CreateTexture(nil, "ARTWORK")
t:SetAllPoints()
t, b.Icon = b:CreateTexture(nil, "ARWORK", nil, 1), t
t:SetAtlas("GarrMission_EncounterAbilityBorder-Lg")
t:SetSize(34.5, 34.5)
t:SetPoint("CENTER")
b.Border, b.info = t, {}
b:SetScript("OnEnter", Threat_OnEnter)
b:SetScript("OnLeave", dismissTooltip)
return b
end
local function SetThreat(self, level, tid, _, icon)
self.id, self.missionLevel = tid, level
self.Icon:SetTexture(icon)
end
local function InterestFollower_OnClick(self)
if self.followerID then
local fid = self.followerID
GarrisonMissionFrame.selectedFollower = fid
GarrisonMissionFrame.FollowerTab.followerList:ShowFollower(fid)
GarrisonMissionFrameTab2:Click()
EV("MP_FORCE_FOLLOWER_TAB", fid)
local fl, idx, btn = GarrisonMissionFrameFollowers.followers do
for i=1,#fl do
if fl[i].followerID == fid then
idx = i
break
end
end
if idx then
local fl = GarrisonMissionFrameFollowers.followersList
for j=1,2 do
for i=1,#fl do
if fl[i] == idx then
btn = i
break
end
end
if btn then
break
else
GarrisonMissionFrameFollowers.SearchBox:SetText("")
end
end
end
end
if btn then
local v = 62*btn - 62
GarrisonMissionFrameFollowersListScrollFrameScrollBar:SetValue(v)
HybridScrollFrame_SetOffset(GarrisonMissionFrameFollowersListScrollFrame, v)
end
end
end
local function InterestFollower_OnEnter(self, info)
local data = core:GetRowData(interestMissionsHandle, self:GetParent())
if info and data and data.best then
local me, s, best, fi = info.followerID, data.s, data.best, G.GetFollowerInfo()
for i=1,#GarrisonFollowerTooltip.Abilities do
local b = GarrisonFollowerTooltip.Abilities[i]
local tid, prefix = b:IsShown() and G.GetMechanicInfo(tostring(b.CounterIcon:GetTexture())), false
if tid then
for j=#s,6,-1 do
if s[j] == tid then
prefix = data.best[j+1] == 2 and "|cfff0ff10" or "|cff10ff10"
break
end
end
b.Details:SetText((prefix or "|cffa0a0a0") .. b.Details:GetText())
end
end
wipe(usefulTraits)
usefulTraits[T.EnvironmentCounters[s[5]] or 0] = 1
for k,v in pairs(T.EnvironmentBonus) do
if v[s[5]] then
usefulTraits[k] = 1
end
end
local ts = T.TraitStack[s[4]]
usefulTraits[best.ttrait or 0] = 1
usefulTraits[ts or 0] = 1
usefulTraits[ts == 79 and 256 or 0] = 1
usefulTraits[232] = best.dtrait
for i=1,data.s[2] do
local fi = fi[best[i]]
if best[i] ~= me and fi and fi.affinity and fi.affinity > 0 then
usefulTraits[fi.affinity] = 1
end
end
for i=1,(info.quality or 0)-1 do
local b = GarrisonFollowerTooltip.Traits[i]
local t = C_Garrison.GetFollowerTraitAtIndex(info.followerID, i) or 0
if b and t > 0 then
local ut = (usefulTraits[t] or usefulTraits[T.EquivTrait[t]])
local c = ut and (ut == 2 and "|cffdcff0a" or "|cff10ff10") or "|cffa0a0a0"
b.Name:SetText(c .. (b.Name:GetText() or ""))
end
end
local mlvl2 = self.targetLevel
if (mlvl2 or 0) > 600 then
local m = "|cffa0a0a0" .. GARRISON_FOLLOWER_ITEM_LEVEL:format(info.iLevel) .. (info.iLevel < mlvl2 and "|cffff2020" or "") .. " (" .. mlvl2 .. ")"
if info.quality >= 4 and info.level >= 100 then
GarrisonFollowerTooltip.ILevel:SetText(m)
else
GarrisonFollowerTooltip.ClassSpecName:SetText(info.className .. " - " .. m)
end
end
end
end
local function CreateInterestMission()
local b = api.CreateMissionButton(58)
b.title:ClearAllPoints()
b.title:SetPoint("TOPLEFT", 68+42-15, -9)
b.level:ClearAllPoints()
b.level:SetPoint("CENTER", b, "LEFT", 40, 7)
b.rare:Hide()
b.veil:Hide()
b.mtype:Hide()
b.iconBG:SetVertexColor(0, 0, 0, 0.4)
b.iconBG:SetWidth(85)
b:Disable()
local t = b:CreateTexture(nil, "BACKGROUND", nil, 3)
t:SetSize(780, 62)
t:SetPoint("RIGHT")
t, b.loc = b:CreateTexture(nil, "BACKGROUND", nil, 6), t
t:SetAtlas("GarrMission_MissionParchment")
t:SetVertexColor(0.25, 0.25, 0.25)
t:SetTexCoord(0, 1, 0, 0.25)
t:SetHorizTile(true)
t:SetAllPoints()
t:Hide()
t, b.altBG = b:CreateFontString(nil, "ARTWORK", "GameFontNormal"), t
t:SetPoint("TOP", b.level, "BOTTOM", 0, -1)
t:SetAlpha(0.8)
t:SetTextColor(0.83, 0.66, 0.45)
t, b.fc = b:CreateFontString(nil, "ARTWORK", "GameFontNormalHuge"), t
t, b.chance = b:CreateFontString(nil, "ARTWORK", "GameFontNormal"), t
t:SetPoint("TOP", b.chance, "BOTTOM", 0, -1)
t, b.fstack = b:CreateFontString(nil, "ARTWORK", "GameFontNormal"), t
t:SetPoint("TOPLEFT", b.title, "BOTTOMLEFT", 0, -2)
t, b.seen = {}, t
for i=1,7 do
t[i] = CreateThreat(b)
t[i]:SetPoint("RIGHT", t[i-1], "LEFT", -10, 0)
end
t[1]:ClearAllPoints()
t[1]:SetPoint("TOPRIGHT", -140, -5)
t[4]:SetPoint("TOPRIGHT", t[1], "BOTTOMRIGHT", -15.5, -3)
t[7]:SetPoint("RIGHT", t[3], "LEFT", -10, 0)
b.threats = t
b.followers = {}
for i=1,3 do
t = api.CreateFollowerPortrait(b, 42, i)
t:SetPoint("RIGHT", -225-44*i, 1)
t:SetScript("OnClick", InterestFollower_OnClick)
t.showAbilityDescriptions, b.followers[i], t.postEnter = true, t, InterestFollower_OnEnter
end
return b
end
local unusedFollowers = CreateFrame("Button") do
unusedFollowers:SetSize(880, 38)
local c, t = {}, unusedFollowers:CreateFontString(nil, "ARTWORK", "GameFontNormal")
t:SetPoint("BOTTOM", unusedFollowers, "TOP", 0, 4)
unusedFollowers.ufollowers, unusedFollowers.label = c, t
for i=1,21 do
t = api.CreateFollowerPortrait(unusedFollowers, 34, i)
t:SetPoint("BOTTOMLEFT", 36*i-35, 4)
t:SetScript("OnClick", InterestFollower_OnClick)
c[i], t.showAbilityDescriptions = t, true
end
end
local function SetUnusedFollowers(self, d)
local isRed = d.lType == "redundant"
self.veil:Hide()
self.altBG:Show()
for i=1,#self.rewards do
self.rewards[i]:Hide()
end
for i=1,#self.followers do
self.followers[i]:Hide()
end
for i=1,#self.threats do
self.threats[i]:Hide()
end
self.level:SetText("")
self.fc:SetText("")
self.title:SetText("")
self.seen:SetText("")
self.chance:SetText("")
self.fstack:SetText("")
self.mtype:SetColorTexture(0,0,0,0)
unusedFollowers:SetParent(self)
unusedFollowers:SetPoint("BOTTOM")
unusedFollowers.label:SetText(isRed and L"Redundant followers:" or L"Inactive followers:")
local finfo, uf = G.GetFollowerInfo(), unusedFollowers.ufollowers
for i=1,#d do
local fb, fi = uf[i], finfo[d[i]]
if fb and fi then
fb.followerID = fi.followerID
fb.portrait:SetTexture(fi.portraitIconID or 0)
fb:Show()
end
end
for i=#d+1,#uf do
uf[i]:Hide()
end
unusedFollowers:SetWidth(36 * math.min(#d, #uf))
unusedFollowers:Show()
end
local function SetInterestMission(self, d)
if d.unused then
return SetUnusedFollowers(self, d.unused)
else
if unusedFollowers:GetParent() == self then
unusedFollowers:SetParent(nil)
unusedFollowers:Hide()
end
self.altBG:Hide()
end
local s, best, mname = d.s, d.best, C_Garrison.GetMissionName(d[1])
self.level:SetText(s[1])
self.title:SetText(mname ~= "" and mname or (L"Future Mission #%d"):format(d[1]))
self.loc:SetAtlas(T.MissionLocationBanners[d[2]] .. "-List")
self.fc:SetText(best and best.variants and ("|TInterface\\FriendsFrame\\UI-Toast-ChatInviteIcon:12:12:0:0:32:32:6:28:4:26:214:170:115|t: " .. best.variants) or ("|TInterface\\FriendsFrame\\UI-Toast-FriendOnlineIcon:11:11:3:0:32:32:8:24:8:24:214:170:115|t"):rep(s[2]))
self.veil:SetShown(d.redundantIgnored)
local mc, isAvailable, lastAppeared = T.MissionCoalescing[s[4]]
for i=0, mc and #mc or 0 do
local id = d[1] + (i > 0 and mc[i] or 0)
local _, _, _, la = G.GetMissionSeen(id)
isAvailable = isAvailable or G.IsMissionAvailable(id)
lastAppeared = la and (la <= (lastAppeared or la)) and la or lastAppeared
end
if (lastAppeared or 0) > 0 and not isAvailable then
self.seen:SetFormattedText(L"Last offered: %s ago", "|cffffffff" .. SecondsToTime(lastAppeared) .. "|r")
else
self.seen:SetText(isAvailable and (L"Available; expires in %s"):format("|cffffffff" .. (isAvailable.offerTimeRemaining or "?") .. "|r") or "")
end
for i=1, #self.threats do
local tb, tid = self.threats[i], s[5+i]
tb:SetShown(tid)
if tid then
SetThreat(tb, d[2], G.GetMechanicInfo(tid))
local countered = best and best[6+i]
if not countered or countered == 0 then
tb.Border:SetVertexColor(1, 0.2, 0.2)
elseif countered == true or countered and countered >= 1 then
tb.Border:SetVertexColor(0.2, 1, 0.2)
else
tb.Border:SetVertexColor(1, 0.65, 0.1)
end
end
end
local nf, blvl, mentor, finfo = best and s[2] or 0, best and best[6], best and best.mentorLevel or 0, G.GetFollowerInfo()
local muf = best and best.used or 0
for i=1,nf do
local mlvl = blvl and blvl % 1e3 or d[2]
blvl = blvl and (blvl - mlvl) / 1e3
local fb, fi, usedGlow = self.followers[i], finfo[best[i]]
if not fi then
fb:Hide()
else
fb.followerID, fb.targetLevel = best[i], (mentor < mlvl or fi.garrFollowerID == T.MENTOR_FOLLOWER) and mlvl or 0
fb.portrait:SetTexture(fi and fi.portraitIconID or 0)
fb.glow:Hide()
if fi.status == GARRISON_FOLLOWER_INACTIVE then
fb.portrait:SetVertexColor(0.2, 0.2, 1)
elseif fb.targetLevel > (mlvl > 100 and fi.iLevel or fi.level) then
fb.portrait:SetVertexColor(1, 0.6, 0.6)
fb.glow:Show()
fb.glow:SetVertexColor(1,0,0)
usedGlow = true
else
fb.portrait:SetVertexColor(1,1,1)
end
if not usedGlow and muf % 2^i >= 2^(i-1) then
fb.glow:Show()
fb.glow:SetVertexColor(1, 0.8, 0)
end
fb:Show()
end
end
for i=nf+1, #self.followers do
self.followers[i]:Hide()
end
self.chance:SetText(best and ("%d%%"):format(best[5]) or "")
if best and best[5] >= 100 then
self.chance:SetTextColor(0, 1, 0)
else
self.chance:SetTextColor(1, 0.55, 0)
end
if best and best[4] and nf > 0 then
local nf = T.UniqueTraits[T.TraitStack[s[4]]] or nf
local ms = nf * (T.MaxTraitStack[s[4]] or 1)
self.chance:SetPoint("RIGHT", -70, 6)
self.fstack:SetText(best[4] .. "/" .. ms .. " |T" .. C_Garrison.GetFollowerAbilityIcon(T.TraitStack[s[4]]) .. ":0:0:0:0:64:64:4:60:4:60|t")
local r, g, b = 0.1, 1, 0.1
if best[4] < nf then r, g, b = 1, 0.55, 0 end
self.fstack:SetTextColor(r,g,b)
else
self.chance:SetPoint("RIGHT", -70, 0)
self.fstack:SetText("")
end
local r, rt = self.rewards[1], mappedRewards[s[4]] or s[4]
if rt == 0 then
local rq = d[3] * (1+(best and best[4] or 0))
r.tooltipTitle, r.tooltipText, r.currencyID, r.itemID = GARRISON_REWARD_MONEY, GetMoneyString(rq), 0
r.icon:SetTexture("Interface\\Icons\\INV_Misc_Coin_02")
r.quantity:SetFormattedText("%d", rq / 1e4)
elseif rt < 2e3 then
local rq = d[3] * (1 + (best and best[4] or 0))
r.currencyID, r.itemID, r.tooltipTitle, r.tooltipText = rt
r.quantity:SetText(rq > 1 and rq or "")
r.icon:SetTexture((select(3,GetCurrencyInfo(rt))))
else
r.itemID, r.currencyID, r.tooltipTitle, r.tooltipText = rt
r.quantity:SetText(d[3] > 1 and d[3] or "")
r.icon:SetTexture(select(10, GetItemInfo(r.itemID)) or GetItemIcon(r.itemID) or "Interface/Icons/Temp")
end
r:Show()
end
interestMissionsHandle = core:CreateHandle(CreateInterestMission, SetInterestMission, 60)
local emptyTable, missions = {}, {}
local updateRedundantFollowers do
local unusedEntry = {unused={}}
local function mcmp(a, b)
local ac, bc = a == unusedEntry, b == unusedEntry
if ac == bc then
ac, bc = b.redundantIgnored, a.redundantIgnored
if ac == bc then
ac = a.ord < b.ord
end
end
return ac
end
function updateRedundantFollowers(missions)
local finfo = G.GetFollowerInfo()
local uf, ua, hasInactive = {}, unusedEntry.unused
wipe(ua)
for k, v in pairs(finfo) do
if v.status ~= GARRISON_FOLLOWER_INACTIVE and v.status ~= GARRISON_FOLLOWER_WORKING and not T.config.ignore[k] and v.followerTypeID == 1 then
uf[k] = true
end
end
for i=1,#missions do
local mi = missions[i]
local b, keep = mi.best, G.IsInterestedInMoI(mi)
mi.redundantIgnored, mi.ord = not keep, mi.ord or i
if b and keep then
local muf = b and b.used
for j=1, mi.s[2] do
if finfo[b[j]].status == GARRISON_FOLLOWER_INACTIVE then
if not hasInactive then
wipe(uf)
end
hasInactive, uf[b[j]] = true, 1
elseif not hasInactive and muf % (2^j) >= 2^(j-1) then
uf[b[j] or 0] = nil
end
end
end
end
table.sort(missions, mcmp)
for k in pairs(uf) do
ua[#ua + 1] = k
end
if #ua > 0 then
table.sort(ua, function(a,b)
a, b = finfo[a], finfo[b]
local ac, bc = a.level + a.iLevel, b.level + b.iLevel
if ac == bc then
ac, bc = a.name, b.name
end
return ac < bc
end)
ua.lType = hasInactive and "inactive" or "redundant"
table.insert(missions, 1, unusedEntry)
end
end
end
local function updateDisplayFromInfo(info)
wipe(missions) do
local ni = 1
for i, m, b in G.MoIMissions(1, info) do
if not m.drop then
missions[ni], ni, m.best = m, ni + 1, b
end
end
end
local ts = T.TraitStack
for k,r in pairs(T.MissionRewardSets) do
for i=1,#r do
local c, r = 0, r[i]
for i=3,r[2] > 0 and #r or 0 do
c = c + (tonumber(GetStatistic(r[i]) or 0) or 0)
end
if c >= r[2] then
mappedRewards[k], r[2], ts[k] = r[1], 0, ts[k] or r.ts
break
end
end
end
updateRedundantFollowers(missions)
return missions
end
function interestMissionsHandle:Show(includeInactive)
interestUI.excludeInactive:SetChecked(not includeInactive)
local info, job = G.GetBestGroupInfo(1, includeInactive, true)
if not info then
core:SetData(emptyTable, interestMissionsHandle)
interestUI.loader.job = job
interestUI.loader:Show()
return
else
interestUI.loader:Hide()
end
core:SetData(updateDisplayFromInfo(info), interestMissionsHandle)
end
function EV:MP_MOI_GROUPS_READY()
if core:IsOwned(interestMissionsHandle) and core:IsShown() then
interestMissionsHandle:Show(not interestUI.excludeInactive:GetChecked())
end
end
function EV:MP_RELEASE_CACHES()
missions, interestMissionsHandle.ident = {}
end
end
do -- Ships
local function CreateMissionPoI(parent)
local f = CreateFrame("FRAME", nil, parent)
f:SetAllPoints()
for i=1,2 do
local t = f:CreateTexture(nil, "ARWORK", nil, i)
t:SetSize(22-5*i, 22-5*i)
t:SetTexture("Interface\\CharacterFrame\\TempPortraitAlphaMaskSmall")
t:SetPoint("CENTER", f, "TOPRIGHT", -12, -12)
f[i == 1 and "outer" or "inner"] = t
end
local t = f:CreateTexture(nil, "ARWORK", nil, 3)
t:SetSize(12, 5)
t:SetTexture("Interface\\CharacterFrame\\TempPortraitAlphaMaskSmall")
t:SetTexCoord(0, 1, 7/12, 1)
t:SetPoint("BOTTOM", f.inner, "BOTTOM")
f.innerLow = t
f.outer:SetVertexColor(0.2, 0.2, 0.2)
f.inner:SetVertexColor(0, 1, 0)
parent.MPUI = f
return f
end
local function GetViableSuggestedGroup(mi)
local sg = G.GetSuggestedGroupsForMission(mi)
sg = sg and sg[1]
if sg and not G.GetMissionGroupDeparture(sg, mi) then
return sg
end
end
local function ShipMission_OnClick(self, button)
if IsModifiedClick("CHATLINK") and self.info then
ChatEdit_InsertLink(C_Garrison.GetMissionLink(self.info.missionID))
elseif self.info.canStart then
local f1, f2, f3
if button == "RightButton" then
local sg = GetViableSuggestedGroup(self.info)
if sg then
f1, f2, f3 = sg[5], sg[6], sg[7]
end
end
OpenToMission(self.info, f1, f2, f3)
end
end
local ShipMission_OnEnter do
local tipGroup = GarrisonShipyardMapMissionTooltip:CreateFontString(nil, "ARTWORK", "GameFontHighlightLeft")
tipGroup:SetTextColor(0.5, 0.8, 1)
hooksecurefunc("GarrisonShipyardMapMission_SetTooltip", function() tipGroup:Hide() end)
local function describeGroup(sg, mi)
local exp, sp = G.GetMissionGroupXP(sg, mi), sg[1]/100
local ex, ce, ct = exp >= 1 and ("; " .. (L"%s XP"):format(BreakUpLargeNumbers(floor(exp)))) or "", sg[3]*sp, sg[9]
if ct == 0 and ce > 1e4 then ex = ex .. "; " .. GetMoneyString(ce - ce % 1e4) end
return sg[1] .. "%" .. (ex or "")
end
function ShipMission_OnEnter(self, ...)
local mi = self.info
GarrisonShipyardMapMission_OnEnter(self, ...)
if mi and mi.canStart and GarrisonShipyardMapMissionTooltip:IsShown() then
local tipText, sg, lg, ld = "", G.GetSuggestedGroupsForMission(mi)
sg, lg = sg and sg[1], sg and sg[#sg]
if sg and not G.GetMissionGroupDeparture(sg, mi) then
tipText = string.format("|TInterface\\TUTORIALFRAME\\UI-TUTORIAL-FRAME:14:12:0:-1:512:512:10:70:330:410|t %s: |cffffffff%s", L"Suggested group", describeGroup(sg, mi))
end
ld = lg and G.GetMissionGroupDeparture(lg, mi)
if ld then
tipText = string.format("|cffb0b0b0%s:|cffffffff %s%s%s", FormatCountdown(ld-time()), describeGroup(lg, mi), tipText ~= "" and "\n|r" or "", tipText)
end
if tipText ~= "" then
tipGroup:SetText(tipText)
tipGroup:Show()
GarrisonShipyardMapMission_AnchorToBottomWidget(tipGroup, 0, -12)
GarrisonShipyardMapMission_SetBottomWidget(tipGroup)
tipGroup:SetWidth(math.max(180, (GarrisonShipyardMapMissionTooltip:GetWidth() or 16) - 12))
GarrisonShipyardMapMissionTooltip:SetHeight(GarrisonShipyardMapMissionTooltip:GetHeight() + tipGroup:GetHeight()+12)
return
end
end
end
hooksecurefunc("GarrisonShipyardMapMission_UpdateTooltipSize", function(self)
if tipGroup:IsVisible() then
GarrisonShipyardMapMissionTooltip:SetHeight(self:GetHeight() + tipGroup:GetHeight()+12)
end
end)
end
local function getGroupColor(s)
local c = T.config
if not s then
return 0.4, 0.4, 0.4
elseif s == 100 then
return 0.2, 0.7, 1
elseif c.ship4 > s then
return 0.6, 0, 0
elseif c.ship3 > s then
return 1, 0.4, 0
elseif c.ship2 > s then
return 1, 0.9, 0
elseif c.ship1 > s then
return 0.2, 1, 0.2
end
end
local function UpdateShipMissionMap()
local self = GarrisonShipyardFrame.MissionTab.MissionList
local sg = G.GetSuggestedGroupsForAllMissions(2)
local oil = select(2, GetCurrencyInfo(1101)) or 0
for i=1, #self.missions do
local mission, frame = self.missions[i], self.missionFrames[i]
if frame:IsShown() and not mission.inProgress then
local ui, sg = frame.MPUI or CreateMissionPoI(frame), sg[mission.missionID]
local fg, lg = sg and sg[1], sg and sg[#sg]
fg = fg and not G.GetMissionGroupDeparture(fg, mission) and fg
lg = lg and lg ~= fg and G.GetMissionGroupDeparture(lg, mission) and lg
local nt, r, g, b, r2, g2, b2 = G.HasTentativeParty(mission.missionID)
if nt == mission.numFollowers then
r,g,b = 1, 0.2, 0.6
elseif nt > 0 then
r,g,b = 0.6, 0.2, 1
elseif (mission.cost or 0) > oil then
r,g,b = 1/4, 1/4, 1/4
else
r,g,b = getGroupColor(fg and fg[1])
r2, g2, b2 = getGroupColor(lg and lg[1] or fg and fg[1])
end
ui.inner:SetVertexColor(r,g,b)
ui.innerLow:SetVertexColor(r2 or r, g2 or g, b2 or b)
ui:Show()
elseif frame.MPUI then
frame.MPUI:Hide()
end
frame:RegisterForClicks("LeftButtonUp", "RightButtonUp")
frame:SetScript("OnClick", ShipMission_OnClick)
frame:SetScript("OnEnter", ShipMission_OnEnter)
end
end
do -- update hook
local pendingUpdate
local function runUpdate()
pendingUpdate = false
return UpdateShipMissionMap()
end
local function enqueueUpdate()
if not pendingUpdate and GarrisonShipyardFrame.MissionTab.MissionList:IsVisible() then
pendingUpdate = true
T.After0(runUpdate)
end
end
hooksecurefunc("GarrisonShipyardMap_UpdateMissions", enqueueUpdate)
GarrisonShipyardFrame.MissionTab.MissionList:HookScript("OnShow", enqueueUpdate)
end
local CreateGroupButton do
local function ShipGroupButton_OnEnter(self)
GroupButtonBase.ShowTooltip(self, SHIP_MISSION_PAGE.missionInfo, false, true, self.group)
end
local function ShipGroupButton_OnClick(self)
OpenToMission(SHIP_MISSION_PAGE.missionInfo, unpack(self.group, 5, 7))
end
function CreateGroupButton(...)
local b = GroupButtonBase:New(...)
b:SetScript("OnEnter", ShipGroupButton_OnEnter)
b:SetScript("OnLeave", dismissTooltip)
b:SetScript("OnClick", ShipGroupButton_OnClick)
return b
end
end
local groups = CreateFrame("Frame", nil, SHIP_MISSION_PAGE)
groups:SetSize(410, 24)
groups.buttons = {CreateGroupButton(groups, 1), CreateGroupButton(groups, 2), CreateGroupButton(groups, 3), CreateGroupButton(groups, 4)}
groups.buttons[1]:SetPoint("LEFT")
groups:SetScript("OnHide", groups.Hide)
for i=2,#groups.buttons do
groups.buttons[i]:SetPoint("LEFT", groups.buttons[i-1], "RIGHT", 4, 0)
end
local noPendingSync = true
local function syncMissionGroups()
local Stage, mi = SHIP_MISSION_PAGE.Stage, SHIP_MISSION_PAGE.missionInfo
Stage.Title:SetPoint("LEFT", Stage.Header, "LEFT", 98, 10)
groups:SetPoint("BOTTOMLEFT", Stage.Header, "BOTTOMLEFT", 88, 4)
groups:Show()
local sg = mi and G.GetSuggestedGroupsForMission(SHIP_MISSION_PAGE.missionInfo)
local sgn = sg and #sg or 0
for i=sgn+1, #groups.buttons do
groups.buttons[i]:Hide()
end
for i=1,sgn do
local b, g = groups.buttons[i], sg[i]
GroupButtonBase.SetGroup(b, mi, g, 100, 20, sg.rankType)
b.group = g
end
noPendingSync = true
end
hooksecurefunc(GarrisonShipyardFrame, "ShowMission", syncMissionGroups)
function EV.GARRISON_FOLLOWER_LIST_UPDATE()
if noPendingSync and SHIP_MISSION_PAGE:IsVisible() then
noPendingSync = false
T.After0(syncMissionGroups)
end
end
end
do -- RefreshActiveMissionsView
local isFullRefresh, isDirty = true
local function DoRefresh()
local force = isFullRefresh
isFullRefresh, isDirty = nil
if force or core:IsOwned(activeMissionsHandle) then
activeMissionsHandle:Activate(force)
end
activeUI.orders:SetShown(GetItemCount(activeUI.orders.itemID) > 0)
end
function RefreshActiveMissionsView(force)
if core:IsShown() and (force or core:IsOwned(activeMissionsHandle)) then
isFullRefresh = isFullRefresh or force
if not isDirty then
isDirty = true
T.After0(DoRefresh)
end
end
end
end
function EV:GET_ITEM_INFO_RECEIVED()
if core:IsVisible() then
core:Refresh()
end
end
function EV:GARRISON_MISSION_FINISHED()
if activeUI:IsVisible() then
RefreshActiveMissionsView(false)
end
end
hooksecurefunc(GarrisonMissionFrame, "HideCompleteMissions", function(_, onClose)
if not onClose and core:IsOwned(activeMissionsHandle) then
RefreshActiveMissionsView(true)
end
end)
local oldComplete = GarrisonMissionFrame.CheckCompleteMissions
function GarrisonMissionFrame:CheckCompleteMissions(onShow, ...)
if not missionList:IsShown() then
return oldComplete(self, onShow, ...)
end
if not GarrisonMissionFrame.MissionComplete:IsShown() then
GarrisonMissionFrame.MissionComplete.completeMissions = C_Garrison.GetCompleteMissions(1)
if #GarrisonMissionFrame.MissionComplete.completeMissions > 0 then
T.UpdateMissionTabs()
end
end
if onShow and not activeUI:IsVisible() and #C_Garrison.GetCompleteMissions(1) > 0 then
missionList.activeTab:Click()
end
end
do -- periodic comleted missions check
local isTimerRunning = false
local function timer()
if GarrisonMissionFrame:IsShown() then
local cm = GarrisonMissionFrame.MissionComplete.completeMissions
if (cm and #cm or 0) == 0 then
GarrisonMissionFrame:CheckCompleteMissions()
end
C_Timer.After(15, timer)
isTimerRunning = true
else
isTimerRunning = false
end
end
GarrisonMissionFrame:HookScript("OnShow", function()
if not isTimerRunning then
timer()
end
end)
end
function EV:MP_RELEASE_CACHES()
core:SetData()
end
function api:SetMissionsUI(tab)
availUI:SetShown(tab == 1)
activeUI:SetShown(tab == 3)
interestUI:SetShown(tab == 4)
GarrisonMissionFrame.MissionTab.MissionList.selectedTab = 0
GarrisonMissionFrame.MissionTab.MissionList.EmptyListString:SetAlpha(tab == 1 and 1 or 0)
if not activeUI:IsShown() then
if activeUI.completionState == "RUNNING" then
G.AbortCompleteMissions()
end
activeUI.completionState = nil
if GarrisonMissionFrame.MissionComplete:IsShown() then
GarrisonMissionFrame:HideCompleteMissions(true)
end
end
EV("MP_SHOW_MISSION_TAB", tab)
end
T.MissionsUI = api
|
return Def.ActorFrame {
-- Speed
Def.Sprite {
OnCommand=function(self)
self:x(-85);
if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'1.5x') and SCREENMAN:GetTopScreen():GetScreenType() == "ScreenType_Gameplay" then
self:Load(THEME:GetPathB("","optionicon_P2/speed_x1_5_P1"));
elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'2x') then
self:Load(THEME:GetPathB("","optionicon_P2/speed_x2_P1"));
elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'3x') then
self:Load(THEME:GetPathB("","optionicon_P2/speed_x3_P1"));
elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'5x') then
self:Load(THEME:GetPathB("","optionicon_P2/speed_x5_P1"));
elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'8x') then
self:Load(THEME:GetPathB("","optionicon_P2/speed_x8_P1"));
elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'0.5x') then
self:Load(THEME:GetPathB("","optionicon_P2/speed_x0_5_P1"));
end;
end;
PlayerJoinedMessageCommand=function(self, params)
if params.Player == PLAYER_2 then
self:playcommand("On");
end;
end;
CodeMessageCommand=function(self, params)
if params.PlayerNumber == PLAYER_2 then
self:playcommand("On");
end;
end;
};
-- Boost
Def.Sprite {
InitCommand=function(self)
self:x(-68);
if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'boost') then
self:Load(THEME:GetPathB("","optionicon_P2/boost_on_P2"));
elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'brake') then
self:Load(THEME:GetPathB("","optionicon_P2/boost_brake_P2"));
elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'wave') then
self:Load(THEME:GetPathB("","optionicon_P2/boost_wave_P2"));
end;
end;
PlayerJoinedMessageCommand=function(self, params)
if params.Player == PLAYER_2 then
self:playcommand("Init");
end;
end;
};
-- Appearance
Def.Sprite {
InitCommand=function(self)
self:x(-51);
if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'hidden') then
self:Load(THEME:GetPathB("","optionicon_P2/appearance_hidden_P2"));
elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'sudden') then
self:Load(THEME:GetPathB("","optionicon_P2/appearance_sudden_P2"));
elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'stealth') then
self:Load(THEME:GetPathB("","optionicon_P2/appearance_stealth_P2"));
end;
end;
PlayerJoinedMessageCommand=function(self, params)
if params.Player == PLAYER_2 then
self:playcommand("Init");
end;
end;
};
-- Turn
Def.Sprite {
InitCommand=function(self)
self:x(-34);
if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'mirror') then
self:Load(THEME:GetPathB("","optionicon_P2/turn_mirror_P2"));
elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'left') then
self:Load(THEME:GetPathB("","optionicon_P2/turn_left_P2"));
elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'right') then
self:Load(THEME:GetPathB("","optionicon_P2/turn_right_P2"));
elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'shuffle') then
self:Load(THEME:GetPathB("","optionicon_P2/turn_shuffle_P2"));
end;
end;
PlayerJoinedMessageCommand=function(self, params)
if params.Player == PLAYER_2 then
self:playcommand("Init");
end;
end;
};
-- Dark
Def.Sprite {
InitCommand=function(self)
self:x(-17);
if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'dark') then
self:Load(THEME:GetPathB("","optionicon_P2/dark_on_P2"));
end;
end;
PlayerJoinedMessageCommand=function(self, params)
if params.Player == PLAYER_2 then
self:playcommand("Init");
end;
end;
};
-- Scroll
Def.Sprite {
InitCommand=function(self)
self:x(0);
if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'reverse') then
self:Load(THEME:GetPathB("","optionicon_P2/scroll_reverse_P2"));
end;
end;
PlayerJoinedMessageCommand=function(self, params)
if params.Player == PLAYER_2 then
self:playcommand("Init");
end;
end;
};
-- Arrow
Def.Sprite {
InitCommand=function(self)
self:x(17);
if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'NORMAL-FLAT')
or GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'CLASSIC-FLAT')
or GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'SOLO-FLAT')
or GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'PS3-FLAT') then
self:Load(THEME:GetPathB("","optionicon_P2/arrow_flat_P2"));
elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'NORMAL-NOTE')
or GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'CLASSIC-NOTE')
or GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'SOLO-NOTE')
or GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'PS3-NOTE') then
self:Load(THEME:GetPathB("","optionicon_P2/arrow_note_P2"));
elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'NORMAL-RAINBOW')
or GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'CLASSIC-RAINBOW')
or GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'SOLO-RAINBOW')
or GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'PS3-RAINBOW') then
self:Load(THEME:GetPathB("","optionicon_P2/arrow_rainbow_P2"));
end;
end;
PlayerJoinedMessageCommand=function(self, params)
if params.Player == PLAYER_2 then
self:playcommand("Init");
end;
end;
};
-- Cut
Def.Sprite {
InitCommand=function(self)
self:x(34);
if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'little') then
self:Load(THEME:GetPathB("","optionicon_P2/cut_on_P2"));
end;
end;
PlayerJoinedMessageCommand=function(self, params)
if params.Player == PLAYER_2 then
self:playcommand("Init");
end;
end;
};
-- Freeze arrow
Def.Sprite {
InitCommand=function(self)
self:x(51);
if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'noholds') then
self:Load(THEME:GetPathB("","optionicon_P2/freeze_arrow_off_P2"));
end;
end;
PlayerJoinedMessageCommand=function(self, params)
if params.Player == PLAYER_2 then
self:playcommand("Init");
end;
end;
};
-- Jump
Def.Sprite {
InitCommand=function(self)
self:x(68);
if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'nojumps') then
self:Load(THEME:GetPathB("","optionicon_P2/jump_off_P2"));
end;
end;
PlayerJoinedMessageCommand=function(self, params)
if params.Player == PLAYER_2 then
self:playcommand("Init");
end;
end;
};
-- Risky
Def.Sprite {
InitCommand=function(self)
self:x(85);
if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'battery')
and GAMESTATE:GetPlayMode() ~= 'PlayMode_Oni' then
self:Load(THEME:GetPathB("","optionicon_P2/Risky"));
end;
end;
PlayerJoinedMessageCommand=function(self, params)
if params.Player == PLAYER_2 then
self:playcommand("Init");
end;
end;
};
};
|
require "x_functions";
-- Set to "true" to disable all hotkeys
-- Set to "false" to enable hotkeys
NO_HOT_KEYS = true
-- -------------------------------------------------------------------------------
function forcez()
if memory.readdwordsigned(0x800BA028) == 32768 then
memory.writedword(0x800BA028, 26000);
end;
end;
function drawmap(x, y)
--gui.gdoverlay(0, 0, mapimage, 0.25);
locx = memory.readdwordsigned(0x800BA024);
locy = memory.readdwordsigned(0x800BA02C);
drawmapdot(x, y, locx, locy, "#ff00ff");
--[[
locx = 623575;
locy = 502062;
drawmapdot(x, y, locx, locy);
locx = 82662;
locy = 230944;
drawmapdot(x, y, locx, locy);
locx = 0;
locy = 0;
drawmapdot(x, y, locx, locy, "#ff0000");
locx = 0;
locy = -1500000;
drawmapdot(x, y, locx, locy, "#ff00ff");
--]]
end;
function drawmapdot(x, y, posx, posy, c)
if not c then
c = "#ffffff";
end;
xadd = 1622739;
xdiv = 17500;
yadd = 987500;
ydiv = 17500;
mapx = math.floor((posx + xadd) / xdiv);
mapy = 112 - math.floor((posy + yadd) / ydiv);
if (mapx < 0 or mapx > 160) and mapy >= 0 and mapy <= 120 then
if mapx < 0 then
line( 4 + x, mapy + y - 2, 5 + x, mapy + y - 2, c);
line( 2 + x, mapy + y - 1, 5 + x, mapy + y - 1, c);
line( 0 + x, mapy + y + 0, 5 + x, mapy + y + 0, c);
line( 2 + x, mapy + y + 1, 5 + x, mapy + y + 1, c);
line( 4 + x, mapy + y + 2, 5 + x, mapy + y + 2, c);
text( 7 + x, mapy + y - 3, string.format("%d", mapx * -1));
else
line( 155 + x, mapy + y - 2, 156 + x, mapy + y - 2, c);
line( 155 + x, mapy + y - 1, 158 + x, mapy + y - 1, c);
line( 155 + x, mapy + y + 0, 160 + x, mapy + y + 0, c);
line( 155 + x, mapy + y + 1, 158 + x, mapy + y + 1, c);
line( 155 + x, mapy + y + 2, 156 + x, mapy + y + 2, c);
text( 139 + x, mapy + y - 3, string.format("%4d", mapx - 160));
end;
elseif (mapx >= 0 and mapx <= 160) and (mapy < 0 or mapy >= 120) then
if mapy < 0 then
line( -2 + mapx + x, y + 4, -2 + mapx + x, y + 5, c);
line( -1 + mapx + x, y + 2, -1 + mapx + x, y + 5, c);
line( 0 + mapx + x, y + 0, 0 + mapx + x, y + 5, c);
line( 1 + mapx + x, y + 2, 1 + mapx + x, y + 5, c);
line( 2 + mapx + x, y + 4, 2 + mapx + x, y + 5, c);
text( -5 + mapx + x, y + 6, string.format("%3d", mapy * -1));
else
line( -2 + mapx + x, y + -5 + 120, -2 + mapx + x, y + -4 + 120, c);
line( -1 + mapx + x, y + -5 + 120, -1 + mapx + x, y + -2 + 120, c);
line( 0 + mapx + x, y + -5 + 120, 0 + mapx + x, y + -0 + 120, c);
line( 1 + mapx + x, y + -5 + 120, 1 + mapx + x, y + -2 + 120, c);
line( 2 + mapx + x, y + -5 + 120, 2 + mapx + x, y + -4 + 120, c);
text( -5 + mapx + x, y + -12 + 120, string.format("%3d", mapy - 120));
end;
else
box (mapx - 1 + x, mapy - 1 + y, mapx + 1 + x, mapy + 1 + y, c);
pixel(mapx - 1 + x, mapy - 1 + y, mapx + 1 + x, mapy + 1 + y, c);
end;
end;
function quickscreen(x, y, fmt, addr, isnotaddr)
local crud = addr;
if not isnotaddr then
-- double negatives
crud = memory.readdwordsigned(addr);
end;
gui.text(x, y * 8, string.format(fmt, crud));
end;
function quickscreen2(x, y, fmt, addr, isnotaddr)
local crud = addr;
if not isnotaddr then
-- double negatives
crud = memory.readwordsigned(addr);
end;
gui.text(x, y * 8, string.format(fmt, crud));
end;
function forcecam()
-- Force X, Y, Z
memory.writedword(0x800B9D20, memory.readdwordsigned(0x800BA024));
memory.writedword(0x800B9D28, memory.readdwordsigned(0x800BA02C));
memory.writedword(0x800B9D24, memory.readdwordsigned(0x800BA028) - 0xC000);
-- Z is set a ways above the player to give top-down perspective
-- Force straight-down
memory.writeword(0x800B9D8a, 0);
memory.writeword(0x800B9D88, -1000);
memory.writeword(0x800B9D8c, 0);
end;
function rangediv(min, max, val, mlt)
if not mlt then
mlt = 1;
end;
local base = min + max;
local val2 = val + min;
return math.min(math.max(0, val2 / base), 1) * mlt;
end;
derp = false;
fcam = false;
-- memory.register(0x0BA028, forcez);
last = {};
--[[
mapfile = assert(io.open("lua\\map.gd", "rb"));
mapimage = mapfile:read("*all");
io.close(mapfile);
--]]
mspeed = 100;
timer = 0;
inkey = input.get();
showcam = false;
camforce = {
x = 0,
y = 0,
z = -0xC000,
pan = 0,
tilt = -1000,
roll = 0
}
camforcel = {
min = {
x = -0x80000,
y = -0x80000,
z = -0xC000,
pan = -2000,
tilt = -1000,
roll = 0
},
max = {
x = 0x80000,
y = 0x80000,
z = 0xC000,
pan = 2000,
tilt = -1000,
roll = 0
}
};
while true do
timer = timer + 1;
lastkey = table.clone(inkey);
inkey = input.get();
if NO_HOT_KEYS then
inkey = {}
inkey.xmouse = 0
inkey.ymouse = 0
end
if inkey['P'] and not lastkey['P'] then
showcam = not showcam;
end;
-- Status goes yellow below 0550 (1360)
-- Status goes orange below 0410 (1040)
-- -- Status pulsates faster if health goes below 0320 ( 800)
-- Status goes red if below 0270 ( 624)
-- -- Pulsates even faster if health goes below 00A0 ( 160)
-- Health drinks recover 640 HP
if inkey['numpad3'] or (inkey['numpad6'] and not lastkey['numpad6']) then
hpt = hpt + 1;
hp2 = math.floor(hpt / 0x100);
hp1 = math.fmod(hpt, 0x100);
memory.writeword(0x800BA0BE, hp2);
memory.writebyte(0x800BA0BD, hp1);
elseif inkey['numpad2'] or (inkey['numpad5'] and not lastkey['numpad5']) then
hpt = hpt - 1;
hp2 = math.floor(hpt / 0x100);
hp1 = math.fmod(hpt, 0x100);
memory.writeword(0x800BA0BE, hp2);
memory.writebyte(0x800BA0BD, hp1);
end;
-- if (inkey['M']) then
-- memory.writebyte(0x80B9FC8, 9);
-- text(1, 1, "fart");
-- end;
--[[
loct = memory.readdwordsigned(0x800B9E08);
camt = memory.readdwordsigned(0x801FFD70);
text( 100, 176, string.format("C Pos %8d %8d", loct, camt));
--]]
quickscreen(200, 1, "X %8d", 0x800BA024);
quickscreen(200, 2, "Y %8d", 0x800BA02C);
quickscreen(200, 3, "Z %8d", 0x800BA028);
quickscreen(200, 4, "A %8.2f", memory.readdwordsigned(0x800BA030) / 0x0FFFFFFF * 360, true);
quickscreen(260, 1, "DCamX %8d", 0x800B9D14);
quickscreen(260, 2, "DCamY %8d", 0x800B9D1C);
quickscreen(260, 3, "DCamZ %8d", 0x800B9D18);
quickscreen(260, 5, "Cam X %8d", 0x800B9D20);
quickscreen(260, 6, "Cam Y %8d", 0x800B9D28);
quickscreen(260, 7, "Cam Z %8d", 0x800B9D24);
quickscreen(260, 8, "Cam ? %8d", 0x800B9D2C);
quickscreen2(260, 10, "Pan %8d", 0x800B9D8a);
quickscreen2(260, 11, "Tilt %8d", 0x800B9D88);
quickscreen2(260, 12, "Roll %8d", 0x800B9D8c);
quickscreen2(240, 20, "HP %d/1600", 0x800BA0BD);
quickscreen(240, 21, "Winded: %8d", 0x800BA108);
--[[
quickscreen(130, 1, "Z1 %8d", 0x800B9DE8);
quickscreen(130, 2, "Z2 %8d", 0x800B9DF0);
quickscreen(130, 3, "Z3 %8d", 0x800BA028);
quickscreen(130, 4, "Z4 %8d", 0x800BA0F8);
quickscreen(130, 5, "Z5 %8d", 0x800C459C);
--]]
if inkey['Y'] then
memory.writedword(0x800B9DE8, 0);
memory.writedword(0x800B9DF0, 0);
memory.writedword(0x800BA028, 0);
memory.writedword(0x800BA0F8, 0);
memory.writedword(0x800C459C, 0);
end;
if inkey['P'] then
test = math.abs(math.sin(timer / 50) * 0xFFFF);
memory.writedword(0x800BC360, test);
end;
--[[
-- Camera movement speed; lock to 0 to stop camera from moving
quickscreen(260, 9, "CSpd? %8d", 0x800B9D30);
quickscreen(260, 10, "Cspd? %8d", 0x800B9D34);
quickscreen(260, 11, "Cspd? %8d", 0x800B9D38);
quickscreen(260, 12, "Cspd? %8d", 0x800B9D3C);
quickscreen2(260, 14, "RCm A %8d", 0x800B9D80);
quickscreen2(260, 15, "RCm B %8d", 0x800B9D82);
quickscreen2(260, 16, "RCm C %8d", 0x800B9D84);
quickscreen2(260, 17, "RCm D %8d", 0x800B9D86);
quickscreen2(260, 18, "RCm E %8d", 0x800B9D88);
quickscreen2(260, 19, "RCm F %8d", 0x800B9D8a);
quickscreen2(260, 20, "RCm G %8d", 0x800B9D8c);
quickscreen2(260, 21, "RCm H %8d", 0x800B9D8e);
--]]
if inkey['U'] then
gui.text(0, 20, "uuuuuuuuuuuuuuuu");
pukemode = math.ceil(math.sin(timer / 50) * 0x7FF);
-- memory.writeword(0x800B9D80, pukemode);
-- memory.writeword(0x800B9D82, pukemode);
-- memory.writeword(0x800B9D84, pukemode);
-- memory.writeword(0x800B9D86, pukemode);
memory.writeword(0x800B9D88, 0);
memory.writeword(0x800B9D8a, pukemode);
memory.writeword(0x800B9D8c, 0);
-- memory.writeword(0x800B9D8e, pukemode);
end;
--quickscreen(260, 8, "Cam ? %8d", 0x800B9D2C);
--quickscreen(260, 9, "Cam ? %8.2f", memory.readdwordsigned(0x800B9D2C) / 0xFFFF * 360, true);
if inkey['M'] then
forcecam();
else
fcam = false;
end;
if inkey['N'] then
memory.writedword(0x800B9D2C,
memory.readdwordsigned(0x800B9D2C) + 0x1000
);
gui.text(0, 8, "fart plus PLUS");
end;
wind = memory.readdword(0x800BA108);
mspeed = math.min(500, mspeed);
if inkey['left'] then
memory.writedword(0x800BA024, memory.readdwordsigned(0x800BA024) - mspeed);
text(100, 169, "LEEEEEEEFT");
mspeed = mspeed + 10;
elseif inkey['right'] then
memory.writedword(0x800BA024, memory.readdwordsigned(0x800BA024) + mspeed);
text(100, 169, "RIIIIIIGHT");
mspeed = mspeed + 10;
elseif inkey['up'] then
memory.writedword(0x800BA02C, memory.readdwordsigned(0x800BA02C) + mspeed);
text(100, 169, "UUUUUUUP");
mspeed = mspeed + 10;
elseif inkey['down'] then
memory.writedword(0x800BA02C, memory.readdwordsigned(0x800BA02C) - mspeed);
text(100, 169, "DOOOOOOWN");
mspeed = mspeed + 10;
elseif inkey['numpad1'] then
memory.writedword(0x800BA028, memory.readdwordsigned(0x800BA028) + mspeed);
text(100, 169, "HIGHHERRRRRRR");
mspeed = mspeed + 10;
elseif inkey['numpad0'] then
memory.writedword(0x800BA028, memory.readdwordsigned(0x800BA028) - mspeed);
text(100, 169, "LOWWWWERRRRRR");
mspeed = mspeed + 10;
else
mspeed = 100;
end;
temp1 = memory.readword(0x8006A5B8);
temp2 = memory.readword(0x8006A5BA);
temp3 = memory.readword(0x8006A594);
temp4 = memory.readword(0x8006A596);
-- text( 1, 30, string.format("?? %04X %04X %04X %04X", temp1, temp2, temp3, temp4));
-- text( 0, 130, string.format("0x800B9DFC = %08X", memory.readdword(0x800B9DFC)));
-- text( 0, 137, string.format("0x800B9FC8 = %08X", memory.readdword(0x800B9FC8)));
addresses = {
0x800B9DE4, -- X?
0x800B9DEC, -- Y? Seems higher than the other one
0x800B9DF4, -- Z? Bigger, doesn't react to input
0x800B9DFC, -- Z? Smaller, doesn't react to input either
0x800B9E24, -- Y? Seems lower than the other one
0x800B9E2C, -- ?
-- 0x800B9DE1,
-- 0x800B9DE2,
-- 0x800B9DE3,
-- 0x800B9DE9,
-- 0x800B9DEA,
-- 0x800B9DEB,
-- 0x800B9DED,
-- 0x800B9E21,
-- 0x800B9E22,
-- 0x800B9E23,
-- 0x800B9D45,
-- 0x800B9D46,
-- 0x800B9D47,
-- 0x800B9DE0,
-- 0x800B9DE4,
-- 0x800B9DE8,
-- 0x800B9DEC,
}
i = 1;
for k, v in pairs(addresses) do
i = i + 1;
vnow = memory.readdwordsigned(v);
-- text(1, i * 7 + 30, string.format("%08X = %12d", v, vnow));
update = true;
if last[v] then
chg = vnow - last[v][2];
if chg == 0 and not last[v][3] then
update = false;
end;
m = 1;
if chg == 0 and last[v][1] then
chgd = last[v][1];
else
chgd = chg;
end;
if chgd < 0 then
m = -1;
end;
-- box( 100, i * 7 + 33, 100 + math.sqrt(math.abs(chgd)) * m, i * 7 + 34, "#ff0000");
--text( 100, i * 7 + 30, math.sqrt(chg));
end;
if update then
last[v] = {chg, vnow};
else
last[v][3] = true;
end;
end;
-- pos1 = memory.readdwordsigned(0x800B9DE4);
-- lifebar( 50, 1, 200, 8, pos1 + 0x80000, 770000, "#ffffff", "#000000");
-- text( 120, 4, string.format("%11d", pos1));
-- pos2 = memory.readdwordsigned(0x800B9DEC);
-- lifebar( 50, 12, 200, 8, pos2 + 0x80000, 0xFFFFF, "#ffffff", "#000000");
-- text( 120, 15, string.format("%11d", pos2));
-- temp1 = memory.readdword(0x800B9D14);
-- text( 1, 30, string.format("%08X", temp1));
spd1 = last[0x800B9DE4][1];
spd2 = last[0x800B9DEC][1];
if spd1 and spd2 then
text(100, 100, string.format("%12d\n%12d", spd1, spd2));
spd1 = spd1 / 37.8;
spd2 = spd2 / -37.8;
line(128, 128, 128 + spd1, 128 + spd2, "#ffffff");
end;
xpos = memory.readdwordsigned(0x800B9DE4);
ypos = memory.readdwordsigned(0x800B9DEC);
--[[
xpos2 = 300000 + xpos;
xmax = 300000 + 770000;
ypos2 = 900000 - ypos;
ymax = 300000 + 600000;
xposa = xpos2 / xmax * 100 + 150;
yposa = ypos2 / ymax * 100 + 50;
-- box ( 150, 50, 250, 150, "#ffffff");
-- line( xposa, 40, xposa, 160, "#ffffff");
-- line( 140, yposa, 255, yposa, "#ffffff");
-- text(150, 50, string.format("X %d - Y %d", xposa, yposa));
--]]
if inkey['Z'] then
walkthroughwalls = true;
elseif inkey['X'] then
walkthroughwalls = false;
end;
if walkthroughwalls then
text( 255, 10, "NOCLIP");
memory.writeword(0x8006A5B8, 0xA997);
memory.writeword(0x8006A5BA, 0x0801);
memory.writeword(0x8006A694, 0xA9AE);
memory.writeword(0x8006A696, 0x0801);
-- memory.writeword(0x800BC35C, 0x0100); -- flashlight
else
memory.writeword(0x8006A5B8, 0x000C);
memory.writeword(0x8006A5BA, 0x1040);
memory.writeword(0x8006A694, 0x0134);
memory.writeword(0x8006A696, 0xAFA9);
-- memory.writeword(0x800BC35C, 0x0000);
end;
-- memory.writedword(0x800BCC08, 0xFFFFFFFF);
-- memory.writedword(0x800BCC0C, 0xFFFFFFFF);
-- memory.writedword(0x800BCC10, 0xFFFFFFFF);
drawmap(0, 0);
--[[
strange values:
0x800BC37A
0x800BC3AE
0x800BC4B2
0x800C4186
0x800CC933
0x800DDABE
0x800DFA39
0x801EEE12
]]
--[[
memory.writebyte(0x800BC37A, 0xFF);
memory.writebyte(0x800BC3AE, 0xFF);
memory.writebyte(0x800BC4B2, 0xFF);
memory.writebyte(0x800C4186, 0xFF);
memory.writebyte(0x800CC933, 0xFF);
memory.writebyte(0x800DDABE, 0xFF);
memory.writebyte(0x800DFA39, 0xFF);
memory.writebyte(0x801EEE12, 0xFF);
--]]
--[[
memory.writedword(0x800BC378, 0x00000000);
memory.writedword(0x800BC3AC, 0x00000000);
memory.writedword(0x800BC4B0, 0x00000000);
memory.writedword(0x800C4180, 0x44444444);
--]]
-- This magical piece of code turns the lights on (sometimes)
--quickscreen(0, 1, "%08x", 0x800C4180)
magic = 0x60606060
-- magic = magic * 0x00000001
-- magic = 0x20202020
for i = 0x00, 0x8F do
--quickscreen(0 + 40 * math.fmod(i, 4), math.floor(i / 4), "%08x", 0x800C4180 + 4 * i)
memory.writedword(0x800C4180 + 4 * i, magic);
--[[
-- wtf were these for again
memory.writedword(0x800CC930 + 4 * i, magic);
memory.writedword(0x800CC980 + 4 * i, magic);
memory.writedword(0x800DDAB0 + 4 * i, magic);
memory.writedword(0x801EEE10 + 4 * i, magic);
--]]
end;
memory.writedword(0x800C4180, 0x00000000);
-- memory.writedword(0x801A9150 + 4 * i, 0x10101010);
-- memory.writedword(0x801A9220 + 4 * i, 0x10101010);
-- text(240, 100, string.format("0x800BC37A = %02X", memory.readbyte(0x800BC37A)));
if showcam then
gui.box(0, 0, 100, 100, 0xffffffff);
menux = rangediv(camforcel['min']['x'], camforcel['max']['x'], camforce['x'], 100);
menuy = rangediv(camforcel['min']['y'], camforcel['max']['y'], camforce['y'], 100);
gui.line(0, menuy, 100, menuy, 0xffffffff);
gui.line(menux, 0, menux, 100, 0xffffffff);
if hitbox(inkey['xmouse'], inkey['ymouse'], inkey['xmouse'], inkey['ymouse'], 0, 0, 100, 100, "white", "red") then
gui.text(0, 0, "welp");
end;
--inpt['xmouse'] < 100 and inpt['ymouse'] < 100 then
end;
pcsx.frameadvance();
end;
|
-- Copyright (c) 2021 Trevor Redfern
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
local Position = require "game.rules.world.position"
local Selectors = {}
function Selectors.getDimensions(state)
if not state or not state.map then
return { width = 0, height = 0, levels = 0 }
end
return {
width = state.map.width,
height = state.map.height,
levels = state.map.levels
}
end
function Selectors.getNeighbors(state, position)
if state.map and state.map.tiles then
return {
nw = state.map.tiles[Position.northwest(position)],
n = state.map.tiles[Position.north(position)],
ne = state.map.tiles[Position.northeast(position)],
w = state.map.tiles[Position.west(position)],
center = state.map.tiles[position],
e = state.map.tiles[Position.east(position)],
sw = state.map.tiles[Position.southwest(position)],
s = state.map.tiles[Position.south(position)],
se = state.map.tiles[Position.southeast(position)],
down = state.map.tiles[Position.down(position)],
up = state.map.tiles[Position.up(position)]
}
end
end
function Selectors.getRooms(state)
return state.map.rooms
end
function Selectors.getTerrain(state, position)
local terrain = require "game.rules.map.terrain"
if state.map and state.map.tiles then
local tile = state.map.tiles[position]
if tile then return tile.terrain end
end
return terrain.list.blank
end
function Selectors.getTile(state, position)
if state.map and state.map.tiles then
return state.map.tiles[position]
end
end
return Selectors
|
-- TODO: Add filetype as an argument, delete all filetypes
local M = {}
local api = vim.api
local config = require('close_buffers.config')
local allowed_delete_type = {
nameless = true,
other = true,
hidden = true,
all = true,
this = true,
}
-- Match buffer name against glob or regex.
---@param bufnr number Buffer number to match.
---@param pattern table Table of parsed regex (vim.regex) and parsed glob (vim.glob2regpat).
---@return boolean Buffer name matches the pattern.
local function match_buffer_name(bufnr, pattern)
local bufname = api.nvim_buf_get_name(bufnr)
local glob = pattern.glob
local regex = pattern.regex
if glob then
return vim.fn.matchstr(bufname, glob) ~= ''
elseif regex then
return regex:match_str(bufname) ~= nil
end
return true
end
-- Match buffer filetype against filetypes or config filetype_ignore.
---@param bufnr number Buffer number to match.
---@param filetype? string Filetype to match.
---@return boolean Buffer filetype matches the given filetype of one of the filetyp in config.
local function match_buffer_filetype(bufnr, filetype)
if filetype ~= nil then
return api.nvim_buf_get_option(bufnr, 'filetype') == filetype
end
return config.get('filetype_ignore')[api.nvim_buf_get_option(bufnr, 'filetype')] ~= nil
end
-- Focus next buffer and preserve window layout.
---@param bufnr number Buffer number to switch focus.
---@param delete_type string Types of deletion to perform.
local function preserve_window_layout(bufnr, delete_type)
if not config.get('preserve_window_layout')[delete_type] then
return
end
local all_windows = api.nvim_list_wins()
local buffers = vim.tbl_filter(function(buf)
return api.nvim_buf_is_valid(buf) and api.nvim_buf_get_option(buf, 'buflisted')
end, api.nvim_list_bufs())
if #buffers < 2 then
local new_buf = api.nvim_create_buf(true, false)
for _, win in ipairs(all_windows) do
api.nvim_win_set_buf(win, new_buf)
end
return
end
if delete_type == 'all' then
local new_buf = api.nvim_create_buf(true, false)
for _, win in ipairs(all_windows) do
api.nvim_win_set_buf(win, new_buf)
end
return
end
if delete_type == 'other' then
for _, win in ipairs(all_windows) do
api.nvim_win_set_buf(win, api.nvim_get_current_buf())
end
return
end
local windows = vim.tbl_filter(function(win)
return api.nvim_win_get_buf(win) == bufnr
end, all_windows)
if #windows == 0 then
return
end
local next_buffer_cmd = config.get('next_buffer_cmd')
if next_buffer_cmd and type(next_buffer_cmd) == 'function' then
next_buffer_cmd(windows)
else
for index, buffer in ipairs(buffers) do
if buffer == bufnr then
local new_focus_index = index + 1 > #buffers and #buffers - 1 or index + 1
for _, win in ipairs(windows) do
api.nvim_win_set_buf(win, buffers[new_focus_index])
end
end
end
end
end
-- Validate delete type
---@param delete_type string | number Types of buffer to delete
---@return boolean Is an allowed delete type
local function validate_delete_type(delete_type)
return allowed_delete_type[delete_type] ~= nil or tonumber(delete_type) ~= nil
end
-- Main function to delete all buffers.
---@param delete_type string Types of buffer to delete.
---@param delete_cmd string Command to use to delete the buffer.
---@param force? boolean Force deletion.
---@param glob? string Filename pattern to match.
---@param regex? string Filename pattern.
function M.close(delete_type, delete_cmd, force, glob, regex)
vim.validate({
type = { delete_type, validate_delete_type },
delete_cmd = { delete_cmd, 'string' },
force = { force, 'boolean', true },
glob = { glob, 'string', true },
regex = { regex, 'string', true },
})
delete_cmd = force and delete_cmd .. '!' or delete_cmd
local pattern = { glob = glob and vim.fn.glob2regpat(glob), regex = regex and vim.regex(regex) }
if not validate_delete_type(delete_type) then
return
end
-- Delete provided buffer.
---@param buf number Buffer number to delete.
local function delete_buffer(buf)
vim.cmd(delete_cmd .. ' ' .. buf)
end
-- Fileter buffer based on filetype, glob and regex
---@param buf number Buffer number to filter.
---@return boolean Buffer is valid or not.
local function buffer_filter(buf)
if not api.nvim_buf_is_valid(buf) or not api.nvim_buf_get_option(buf, 'buflisted') then
return false
end
if glob or regex then
return match_buffer_name(buf, pattern)
else
for _, ignore_regex in ipairs(config.get('file_regex_ignore')) do
if match_buffer_name(buf, { regex = ignore_regex }) then
return false
end
end
for _, ignore_glob in ipairs(config.get('file_glob_ignore')) do
if match_buffer_name(buf, { glob = ignore_glob }) then
return false
end
end
end
if match_buffer_filetype(buf) then
return false
end
return true
end
local buffers = vim.tbl_filter(buffer_filter, api.nvim_list_bufs())
local bufnr
if tonumber(delete_type) == nil then
bufnr = api.nvim_get_current_buf()
else
bufnr = delete_type
delete_type = 'this'
end
if delete_type == 'this' and buffer_filter(bufnr) then
preserve_window_layout(bufnr, delete_type)
delete_buffer(bufnr)
return
end
local non_hidden_buffer = {}
if delete_type == 'hidden' then
for _, win in ipairs(api.nvim_list_wins()) do
non_hidden_buffer[api.nvim_win_get_buf(win)] = true
end
end
if delete_type == 'all' or delete_type == 'other' then
preserve_window_layout(bufnr, delete_type)
end
for _, buffer in ipairs(buffers) do
if api.nvim_buf_get_option(buffer, 'modified') and not force then
api.nvim_err_writeln(
string.format('No write since last change for buffer %d (set force to true to override)', buffer)
)
elseif delete_type == 'nameless' and api.nvim_buf_get_name(buffer) == '' then
preserve_window_layout(buffer, delete_type)
delete_buffer(buffer)
elseif delete_type == 'other' and bufnr ~= buffer then
delete_buffer(buffer)
elseif delete_type == 'hidden' and non_hidden_buffer[buffer] == nil then
delete_buffer(buffer)
elseif delete_type == 'all' then
delete_buffer(buffer)
end
end
end
return M
|
-- See LICENSE for terms
function OnMsg.LoadGame()
local o = BuildMenuPrerequisiteOverrides
if o.WindTurbine and TGetID(o.WindTurbine) == 401896326435 --[[You can't construct this building at this time]] then
o.WindTurbine = nil
end
end
|
-- INCLUDES
#include 'include/internal_events.lua'
-- VARIABLES
local g_Commands
local g_LoadingCmdList = false
local g_GuiParent, g_SearchEdit, g_CmdList
local g_HelpMgrRes = Resource('helpmanager')
-- FUNCTIONS
local function HlpUpdateList()
if(not g_CmdList or not g_Commands) then return end
guiGridListClear(g_CmdList)
local text = guiGetText(g_SearchEdit)
local pattern = text:lower()
for i, cmd in ipairs(g_Commands) do
local cmdNameLower = cmd[1]:lower()
local cmdDescLower = (cmd[2] or ''):lower()
if(pattern == '' or cmdNameLower:find(pattern, 1, true) or cmdDescLower:find(pattern, 1, true)) then
local row = guiGridListAddRow(g_CmdList)
guiGridListSetItemText(g_CmdList, row, 1, cmd[1], false, false)
guiGridListSetItemText(g_CmdList, row, 2, cmd[2] or '', false, false)
end
end
end
local function HlpCmdList(serverCommands)
local clientCommands = CmdMgr.getCommandsForHelp()
local allCommands = table.merge(serverCommands, clientCommands)
table.sort(allCommands, function(cmd1, cmd2) return cmd1[1]:lower() < cmd2[1]:lower() end)
g_Commands = allCommands
HlpUpdateList()
end
local function HlpCreateGui(parent, x, y, w, h)
local title = guiCreateLabel(x, y, w, 15, "Controls", false, parent)
guiSetFont(title, 'default-bold-small')
local userPanelKey = getKeyBoundToCommand('UserPanel')
local statsPanelKey = getKeyBoundToCommand('StatsPanel')
local invKey = getKeyBoundToCommand('UserInventory')
local mapInfoKey = getKeyBoundToCommand('MapInfoGui')
guiCreateLabel(x, y + 1*15, w, 15, MuiGetMsg("Press %s to show Statistics Panel."):format(statsPanelKey or '-'), false, parent)
guiCreateLabel(x, y + 2*15, w, 15, MuiGetMsg("Press %s to show User Panel."):format(userPanelKey or '-'), false, parent)
guiCreateLabel(x, y + 3*15, w, 15, MuiGetMsg("Press %s to show User Items."):format(invKey or '-'), false, parent)
guiCreateLabel(x, y + 4*15, w, 15, MuiGetMsg("Press %s to show Map Info."):format(mapInfoKey or '-'), false, parent)
if(ServerRules) then
local rulesLink = Link(x + w - 120, y, 150, 15, parent, "Server Rules")
addEventHandler('onClientGUIClick', rulesLink.el, ServerRules.display, false)
end
y = y + 5*15 + 10
local title = guiCreateLabel(x, y, w, 15, "Commands", false, parent)
guiSetFont(title, 'default-bold-small')
guiCreateLabel(x, y + 16, 50, 15, "Search:", false, parent)
g_SearchEdit = guiCreateEdit(x + 50, y + 15, 150, 20, '', false, parent)
addEventHandler('onClientGUIChanged', g_SearchEdit, HlpUpdateList, false)
g_CmdList = guiCreateGridList(x, y + 40, w, h - (y + 40), false, parent)
guiGridListAddColumn(g_CmdList, "Command", 0.2)
guiGridListAddColumn(g_CmdList, "Description", 0.7)
end
local function HlpLoadCmdList()
if(not g_Commands and not g_LoadingCmdList) then
g_LoadingCmdList = true
RPC('CmdMgr.getCommandsForHelp'):onResult(HlpCmdList):exec()
end
end
local function HlpTabShown()
if(not g_CmdList) then
local w, h = guiGetSize(g_GuiParent, false)
HlpCreateGui(g_GuiParent, 10, 10, w - 20, h - 20)
end
HlpLoadCmdList()
end
local function HlpCloseWnd()
guiSetVisible(g_GuiParent, false)
showCursor(false)
end
local function HlpCreateWnd()
local w, h = 500, 400
local x, y = (g_ScreenSize[1]-w)/2, (g_ScreenSize[2]-h)/2
g_GuiParent = guiCreateWindow(x, y, w, h, "Toxic Help", false)
guiWindowSetSizable(g_GuiParent, false)
local closeBtn = guiCreateButton(w - 90, h - 35, 80, 25, "Close", false, g_GuiParent)
addEventHandler('onClientGUIClick', closeBtn, HlpCloseWnd, false)
HlpCreateGui(g_GuiParent, 10, 25, w - 20, h - 45)
HlpLoadCmdList()
end
local function HlpOpenWnd()
if(not g_GuiParent) then
HlpCreateWnd()
else
guiSetVisible(g_GuiParent, true)
end
showCursor(true)
guiBringToFront(g_GuiParent)
end
local function HlpToggleWnd()
if(g_GuiParent and guiGetVisible(g_GuiParent)) then
HlpCloseWnd()
else
HlpOpenWnd()
end
end
local function HlpInit()
if(Settings.helpmgr and g_HelpMgrRes:isReady()) then
g_GuiParent = g_HelpMgrRes:call('addHelpTab', getThisResource(), true)
guiSetText(g_GuiParent, "Rafalh Scripts System")
addEventHandler('onClientGUITabSwitched', g_GuiParent, HlpTabShown)
local tabPanel = getElementParent(g_GuiParent)
if(not tabPanel) then Debug.warn('No tab panel found')
else guiGetSelectedTab(tabPanel) end
if(guiGetSelectedTab(tabPanel) == g_GuiParent) then
HlpTabShown()
end
else
bindKey('F9', 'down', HlpToggleWnd)
end
end
addInitFunc(HlpInit)
|
json = require("dkjson")
function printf(...)
print(string.format(...))
end
function round(val, dec)
if dec then
return math.floor(val * 10 ^ dec + 0.5) / 10 ^ dec
else
return math.floor(val + 0.5)
end
end
function processTemplateFile(name, directiveTable)
local state = { }
local out = io.open(name..".lua", "w")
out:write("-- This file is automatically generated, do not edit!\n")
for line in io.lines(name..".txt") do
local spec, args = line:match("#(%a+) ?(.*)")
if spec then
if directiveTable[spec] then
directiveTable[spec](state, args, out)
else
printf("Unknown directive '%s'", spec)
end
else
out:write(line, "\n")
end
end
out:close()
end
local function qFmt(s)
return '"'..s:gsub("\n","\\n"):gsub("\"","\\\"")..'"'
end
function writeLuaTable(out, t, indent)
out:write('{')
if indent then
out:write('\n')
end
for k, v in pairs(t) do
if indent then
out:write(string.rep("\t", indent))
end
out:write('[')
if type(k) == "number" then
out:write(k)
else
out:write(qFmt(k))
end
out:write(']=')
if type(v) == "table" then
writeLuaTable(out, v, indent and indent + 1)
elseif type(v) == "string" then
out:write(qFmt(v))
else
out:write(tostring(v))
end
if next(t, k) ~= nil then
out:write(',')
end
if indent then
out:write('\n')
end
end
if indent then
out:write(string.rep("\t", indent-1))
end
out:write('}')
end
function loadDat(name)
if _G[name] then
return
end
printf("Loading '%s'...", name)
local f = io.open(name..".json", "r")
if not f then
os.execute("pypoe_exporter dat json "..name..".json --files "..name..".dat")
f = io.open(name..".json", "r")
end
local text = f:read("*a")
f:close()
local t = json.decode(text)[1]
local headerMap = { }
for i, header in pairs(t.header) do
headerMap[header.name] = i
end
local rowMeta = {
__index = function(self, index)
if index == "print" then
return function()
for i, header in pairs(t.header) do
printf("%s = %s", header.name, type(self[i]) == "table" and ("{ "..table.concat(self[i], ", ").." }") or self[i])
end
end
else
return rawget(self, headerMap[index])
end
end
}
_G[name] = setmetatable({ maxRow = #t.data - 1, headerMap = headerMap }, {
__index = function(self, index)
if type(index) == "number" then
return setmetatable(t.data[index + 1], rowMeta)
elseif headerMap[index] then
return function(val, match)
local col = headerMap[index]
local out = { }
for index, row in ipairs(t.data) do
if type(row[col]) == "table" then
for _, v in pairs(row[col]) do
if (match and v:match(val)) or (not match and v == val) then
table.insert(out, index - 1)
break
end
end
else
if (match and row[col]:match(val)) or (not match and row[col] == val) then
table.insert(out, index - 1)
end
end
end
return out
end
end
end
})
_G[name:gsub("%l","")] = _G[name]
end
|
local proto = require 'proto'
local define = require 'proto.define'
local client = require 'client'
local json = require "json"
local config = require 'config'
local lang = require 'language'
local nonil = require 'without-check-nil'
local dontShowAgain = false
local function check(uri)
if dontShowAgain then
return
end
dontShowAgain = true
nonil.disable()
if config.get(uri, 'editor.semanticHighlighting.enabled') == 'configuredByTheme' then
proto.request('window/showMessageRequest', {
type = define.MessageType.Info,
message = lang.script.WINDOW_CHECK_SEMANTIC,
actions = {
{
title = lang.script.WINDOW_APPLY_SETTING,
},
{
title = lang.script.WINDOW_DONT_SHOW_AGAIN,
},
}
}, function (item)
if not item then
return
end
if item.title == lang.script.WINDOW_APPLY_SETTING then
client.setConfig {
{
key = 'editor.semanticHighlighting.enabled',
action = 'set',
value = true,
global = true,
}
}
end
end)
end
end
local function refresh()
if not client.isReady() then
return
end
log.debug('Refresh semantic tokens.')
proto.request('workspace/semanticTokens/refresh', json.null)
--check()
end
config.watch(function (uri, key, value, oldValue)
if key == '' then
refresh()
end
if key:find '^Lua.runtime'
or key:find '^Lua.workspace'
or key:find '^Lua.semantic'
or key:find '^files' then
refresh()
end
end)
return {}
|
--[[
Copyright (c) 2007 Gordon Gremme <gordon@gremme.org>
Copyright (c) 2007 Center for Bioinformatics, University of Hamburg
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
]]
-- testing the Lua bindings for the GFF3 GenomeVisitor (similar to the gff3
-- tool)
function usage()
io.stderr:write(string.format("Usage: %s GFF3_file\n", arg[0]))
io.stderr:write("Parse and output the given GFF3_file.\n")
os.exit(1)
end
if #arg == 1 then
gff3file = arg[1]
else
usage()
end
gs = gt.gff3_in_stream_new_sorted(gff3file)
gv = gt.gff3_visitor_new()
gn = gs:next_tree()
while (gn) do
gn:accept(gv)
gn = gs:next_tree()
end
cv = gt.custom_visitor_new()
gs = gt.gff3_in_stream_new_sorted(gff3file)
gn = gs:next_tree()
while (gn) do
gn:accept(cv)
gn = gs:next_tree()
end
cv = gt.custom_visitor_new()
gs = gt.gff3_in_stream_new_sorted(gff3file)
gn = gs:next_tree()
cv.features = 0
cv.regions = 0
cv.sequences = 0
cv.metas = 0
function cv:visit_feature(fn)
self.features = self.features + 1
end
function cv:visit_region(fn)
self.regions = self.regions + 1
end
function cv:visit_sequence(fn)
self.sequences = self.sequences + 1
end
function cv:meta(fn)
self.metas = self.metas + 1
end
while (gn) do
gn:accept(cv)
gn = gs:next_tree()
end
assert(cv.metas == 0)
assert(cv.sequences == 0)
assert(cv.features == 1)
assert(cv.regions == 1)
fn = gt.feature_node_new("test", "gene", 100, 1000, "+")
cv = gt.custom_visitor_new()
function cv:visit_feature(fn)
return 1 + nil
end
rval, err = pcall(fn.accept, fn, cv)
assert(not rval)
assert(string.find(err, "perform arithmetic on a nil"))
|
miner_settings = {
max_velocity = 30,
max_acceleration=10,
max_angular_velocity=0.25,
kp_1=30.0,
kd_1=3.0,
kp_2=3.0,
kd_2=5.0,
}
upgrade_maximums = {
max_velocity = 30,
max_acceleration=10,
max_angular_velocity=0.25,
kp_1=100.0,
kd_1=50.0,
kp_2=100.0,
kd_2=50.0
}
upgrade_amounts = {
5.0, 2.5, 0.125
}
-- a list of targets for miners to cycle between
miner_targets = {}
-- state given by create_state
-- control takes the form {angular_velocity, acceleration
function update_state(state, control, limits, dt)
-- q.x, q.y, q.d based directly off of q_dot.x, q_dot.y, q_dot.d
state.q.x += state.q_dot.x * dt
state.q.y += state.q_dot.y * dt
state.q.d += state.q_dot.d * dt
-- q_dot.x, q_dot.y based off of q_ddot
state.q_dot.x += state.q_ddot.x * dt
state.q_dot.y += state.q_ddot.y * dt
-- q_dot.d based off of control and angular momentum
state.q_dot.d = (rnd(0.2) + rnd(0.2) + 0.8) * control.angular_velocity
if limits != nil then
local vel_dir = atan2(state.q_dot.x, state.q_dot.y)
state.q_dot.x = mid(-limits.max_velocity * cos(vel_dir), state.q_dot.x, limits.max_velocity * cos(vel_dir))
state.q_dot.y = mid(-limits.max_velocity * sin(vel_dir), state.q_dot.y, limits.max_velocity * sin(vel_dir))
end
-- q_ddot.x and q_ddot.y based off of control, q.d
state.q_ddot.x = cos(state.q.d) * (rnd(0.3) + rnd(0.3) + 0.7) * control.acceleration
state.q_ddot.y = sin(state.q.d) * (rnd(0.3) + rnd(0.3) + 0.7) * control.acceleration
-- q_ddot.d unused
state.q_ddot.d = 0
if control.acceleration > 0 then
--sfx(1)
end
end
function update_miner_control(e)
if e.current_target > 0 and #miner_targets == 0 then
e.control = create_control()
return
end
if e.current_target > #miner_targets then
e.current_target = 1
end
local target_zone = nil
if e.current_target > 0 then
target_zone = miner_targets[e.current_target]
else
target_zone = e.zero_target_zone
end
if overlap(e, target_zone) or out_of_bounds(target_zone) then
if e.current_target == 0 then
e.current_target = flr(rnd_between(1, #miner_targets + 1))
else
e.current_target = (e.current_target % #miner_targets) + 1
end
target_zone = miner_targets[e.current_target]
end
if target_zone == nil then
e.current_target = flr(rnd_between(1, #miner_targets + 1))
e.control = create_control()
return
end
local dx, dy = target_zone.state.q.x - e.state.q.x, - target_zone.state.q.y + e.state.q.y
local dir = atan2(dx, dy)
local vx, vy = target_zone.state.q_dot.x - e.state.q_dot.x, target_zone.state.q_dot.y - e.state.q_dot.y
dx, dy = cos(e.state.q.d) * dx - sin(e.state.q.d) * dy, sin(e.state.q.d) * dx + cos(e.state.q.d) * dy
vx, vy = cos(dir) * vx - sin(dir) * vy, sin(dir) * vx + cos(dir) * vy
--dx *= e.controls.kp.dx
--dy *= e.controls.kp.dy
dx = max(0, dx)
e.control.angular_velocity = miner_settings.kp_2 * dy - miner_settings.kd_2 * vy
e.control.acceleration = miner_settings.kp_1 * dx + miner_settings.kd_1 * vx
e.control.angular_velocity = mid(e.control.angular_velocity, miner_settings.max_angular_velocity, -miner_settings.max_angular_velocity)
e.control.acceleration = mid(e.control.acceleration, miner_settings.max_acceleration, -miner_settings.max_acceleration)
end
function modify_miner_path()
local zone = nil
for i=1, #entities do
local e = entities[i]
if e.type == "zone" and overlap(e, player_camera) then
if zone == nil or e.radius < zone.radius then
zone = e
end
end
end
if zone == nil then
return false
end
local removed = del(miner_targets, zone)
if removed == nil then
add(miner_targets, zone)
end
return true
end
function switch_to_ship()
local ship = nil
for i=1, #entities do
local e = entities[i]
if e.type == "miner" and overlap(e, player_camera) then
ship = e
break
end
end
if ship == nil then
return false
end
player = ship
ship.type = "player"
return true
end
function switch_from_ship()
player.type = "miner"
player = nil
end
function miners_scatter()
for i = 1, #entities do
local e = entities[i]
if e.type == "miner" then
e.current_target = flr(rnd(#miner_targets)) + 1
end
end
--picked_zones = {}
--for i=1,#entities do
-- local e = entities[i]
-- if e.type == "miner" then
-- e.current_target = 0
-- e.zero_target_zone = next_random_zone(picked_zones)
-- add(picked_zones, e.zero_target_zone)
-- end
--end
end
-- returns one zone at random in entities that is not in removed.
function next_random_zone(removed)
local start = flr(rnd_between(1, #entities + 1))
for i=0,#entities-1 do
local e = entities[(start + i) % #entities + 1]
if e.type == "zone" and not contains(removed, e) then
return e
end
end
end
function contains(list, element)
for i=1,#list do
if list[i] == element then
return true
end
end
return false
end
|
SILE.hyphenator.languages["ro"] = {};
SILE.hyphenator.languages["ro"].patterns =
{
".a3ic",
".a4n3is",
".a2z",
".cre1",
".de2aj",
".de2z1",
".g4",
".i2a",
".i2e",
".i3ț",
".i4u3",
".i3v",
".î4m",
".n2",
".ni2",
".p4",
".pre3ș",
".s4",
".ș4",
".u4i",
".u5ni",
".z2",
"a1",
"2acă",
"achi5",
"a3e",
"afo3",
"a3i2a",
"a3i2e",
"a3il",
"ai3s2",
"a3iu",
"alie6",
"2alt",
"a2m",
"a2n",
"2an.",
"a5n2e",
"ani2e",
"ani3ș4",
"an4s",
"2anu",
"an2z",
"ao2g",
"ati4a",
"2atr",
"a5t4u",
"2ața",
"2ață",
"2au",
"a3ua",
"a3ud",
"a3ug",
"a3ul",
"a3un",
"a3ur",
"a3us",
"a3ute",
"a3u2ț",
"a3uz",
"2ă1",
"ă3i",
"ăi2e",
"ă2m2",
"ănu3",
"ărgi5",
"ă3ș",
"ă4ș3t",
"ă2ti.",
"ăti4e",
"ă3u",
"ă3v",
"ă2zi",
"1b",
"2b.",
"ba2ț",
"bănu5",
"2bc",
"2bd",
"bi2a.",
"bi2at",
"bi2e",
"3bii",
"b2l",
"3b4lim",
"b4lu",
"bo1",
"bo3ric",
"2bs",
"2bt",
"2bț",
"bți4ne.",
"bu3",
"1c",
"4c.",
"ca3ut",
"că2c",
"cătu5",
"2cc",
"ce2a",
"ce2ț",
"2chi.",
"2ci.",
"ci3ale",
"ci2o",
"cis2",
"ci3sp",
"ciza2",
"c4l",
"2cm",
"2c5n",
"copia2tă",
"co2ț",
"2cs",
"2ct",
"2cț",
"cu3im",
"3cul",
"cu2ț",
"2cv",
"1d",
"4d.",
"da4m",
"da2ț",
"2dc",
"de4sc",
"dez3in",
"di2an",
"dia2tă",
"2dj",
"2dm",
"2d1n",
"do4il",
"3du",
"e1ac",
"e1aj",
"e1al",
"e1aș",
"e1at",
"ea2ț",
"e1av",
"ebu5i",
"2ec",
"eci2a",
"ecla2re",
"edi4ulu",
"e3e",
"ee2a",
"1efa",
"e1h",
"e3i2a",
"e3i2e",
"e3ii",
"e3il",
"e3im",
"e3in",
"e3i2o",
"e3i3s2",
"e3it",
"e3i4u",
"e1î",
"2el",
"e2m",
"emon5",
"2en",
"e5ne",
"e1o1",
"e3on",
"e1r",
"2era",
"2eră",
"2erc",
"2e2s",
"es3co",
"es5ti",
"2eș",
"e3și",
"etan4ț",
"2eț",
"e3u",
"eu5ș",
"1evit",
"e2x",
"2ez",
"eză5",
"ezi3a",
"e2z1o",
"1f4",
"2f.",
"3fa",
"3făș",
"2fi.",
"fi3e",
"3fo",
"2ft",
"f5tu",
"1g2",
"2g.",
"gă3ț",
"2ghi.",
"2gi.",
"g4l",
"2g3m",
"2g3n",
"go5n",
"3gu3",
"2g3v",
"2h.",
"2hi.",
"hi2a",
"hi3c",
"hi4u",
"2h1n",
"2i1",
"4i.",
"3i2ac",
"ia3g4",
"i2ai",
"i2aș",
"ia2ț",
"i3că",
"i2ed",
"i3ia",
"i3ie",
"i3ii",
"i3il",
"i3in",
"i3ir",
"i3it",
"iitu2ră",
"i2î",
"4ila",
"i3le",
"i3lo",
"imateri6",
"i2n",
"i4n1ed",
"in2gă",
"inți4i",
"3inv",
"i3od",
"i3oni",
"io2ț",
"ipă5",
"i2s",
"is3f",
"4isp",
"iș3t",
"i5ti",
"iți2a",
"i3ți2o",
"i3ua",
"i3ul",
"i3um",
"i3und",
"i3unu",
"i3us",
"i3ut",
"iz3v",
"î2",
"î3d",
"î3e",
"î3lo",
"îna3",
"în5ș",
"î3ri",
"î3rî",
"îr5ș",
"îș3t",
"î3t",
"î4ti",
"î3ț",
"î4ți",
"î5ții",
"î3z",
"1j",
"2j.",
"2jd",
"2ji.",
"ji2ț",
"2jl",
"j4u",
"ju3t",
"1k",
"1l",
"4l.",
"larați2",
"lă2ti",
"lătu5",
"2lb",
"2lc",
"2ld",
"le2a",
"2lf",
"2lg",
"4li.",
"li3a",
"li3e",
"li3o",
"2lm",
"2l5n",
"2lp",
"2ls",
"2l3ș",
"2lt",
"2lț",
"3lu",
"2lv",
"1m",
"2m.",
"3ma",
"3mă",
"2mb",
"mblîn3",
"3me",
"me2z",
"2mf",
"3mi",
"4mi.",
"mi2ț",
"3mî",
"2m1n",
"3mo",
"mon4",
"2mp",
"2m3s2",
"2mt",
"2mț",
"3mu",
"mu2ț",
"2mv",
"4n.",
"3na",
"4n1ad",
"na3in",
"3nă",
"2nc",
"n2cis",
"n2ciz",
"2nd",
"3ne",
"ne1ab",
"ne1an",
"ne1ap",
"4nef",
"4n1eg",
"ne3s2",
"4nevi",
"4n1ex",
"2ng",
"ng3ăt",
"3ni",
"4ni.",
"ni3ez",
"3nî",
"n3j",
"n1n",
"3no",
"no4ș",
"n1r",
"2n3s2",
"ns3f",
"n4sî",
"ns3po",
"n3ș2",
"n4și",
"2nt",
"n5ti",
"n5t4u",
"2nț",
"5nu",
"nu3a",
"nu3ă",
"nu5m",
"nu3s2",
"2nz",
"o1ag",
"o2al",
"o2bi.",
"2oca",
"ocu5i",
"2od",
"odi2a",
"o3e",
"o3i2",
"oiecti2",
"oi3s2p",
"omedi2e.",
"om4n",
"2on",
"o1o",
"opi3e",
"opla2",
"oplagi2",
"o1ra",
"o1ră",
"or2c",
"o1re",
"o1ri",
"o2ric",
"o1rî",
"o1ro",
"or2te.",
"o1ru",
"os5ti",
"o3și",
"otați4",
"o5ti",
"ot3od",
"o3u",
"1p2",
"2p.",
"3pa",
"păr3ț",
"2p3c",
"pecți2",
"pe2ț",
"2pi.",
"pi2e",
"pi3e.",
"pi3ez",
"pi3o",
"pi2ț",
"pi2z",
"p4l",
"po4ș",
"po2ț",
"2p3s",
"2p3ș",
"2p3t",
"2p3ț",
"p4ți.",
"pu3b4",
"puri2e",
"pu4ș",
"4r.",
"2rb",
"2rc",
"2rd",
"r2e",
"re2bi",
"recizi2",
"re3s2cr",
"re4și",
"2rf",
"2rg",
"2r1h",
"4ri.",
"ri3a",
"ri4ali",
"ri3eț",
"ri3ez",
"ri5mi",
"2ri3un",
"ri3v",
"2rk",
"2rl",
"2rm",
"2r1n",
"rna2ț",
"rografi6",
"2rp",
"2r1r",
"2rs2",
"r3sp",
"r3st",
"2r3ș",
"2rt",
"rtua2le",
"2rț",
"ru3il",
"ru3sp",
"2rv",
"2rz",
"1s",
"4s.",
"5sa",
"5să",
"să4m",
"să4ș",
"2sc",
"4sc.",
"3s2co",
"3se",
"se2a",
"se4e.",
"ses2",
"se3sp",
"se4ș",
"4s2f",
"5sfî",
"3si",
"si3p",
"3sî",
"3s4l",
"4sm",
"s1n",
"3so",
"so3ric",
"2sp",
"2st",
"sto3",
"5su",
"su2ț",
"2ș",
"4ș.",
"3șa",
"șa2ț",
"3șă2",
"3șe",
"1și",
"4și.",
"5șii",
"5șil",
"3șin",
"3șî",
"4ș5n",
"șnu5",
"3șo",
"ș2p",
"ș2ti",
"4ști.",
"4ș3tr",
"3șu",
"1t2",
"4t.",
"ta3ut",
"2t3c",
"2t3d",
"te2a",
"te5ni",
"teri6ală",
"te3s2p",
"2t3f",
"4ti.",
"ti3a",
"ti3e",
"3tii.",
"3til",
"3tin",
"ti2ț",
"2tî.",
"t4l",
"2t3m",
"3tol",
"3tor",
"to2to",
"3tru.",
"3trul",
"3truo",
"4t3s2",
"2t3t",
"tu3a",
"tu3im",
"4t3un",
"tu4ș",
"4t3z",
"1ț",
"2ț.",
"3ța",
"3ță",
"țe2ț",
"2ți.",
"3ția",
"ți3a.",
"3ție",
"3ții",
"3țil",
"ți2ț",
"3țiu",
"țu3",
"țu5i",
"2u1",
"6u.",
"u2a.",
"u2ad",
"u3au",
"uă3",
"uăs2",
"u2bia",
"u2b3l",
"u2b1o",
"ub3s2",
"u3e",
"4ugu",
"u3i2a",
"u3i2e",
"u3in",
"u3ir",
"u3is",
"u3it",
"u3i2ț",
"u3iz",
"u2l",
"u3la",
"u3lă",
"u3le",
"u3lii",
"u3lî",
"u3lo",
"umi5r",
"ur2z",
"u2s",
"us2pr",
"u4st",
"u3ș",
"u4șt",
"u2to",
"3utor",
"u3ui",
"u3um",
"1v",
"2v.",
"ve5ni",
"ve2ț",
"ve2z",
"2vi.",
"vi2ț",
"2v1n",
"vorbito2",
"3vr",
"1x",
"2x.",
"3xa",
"3xă",
"3xe",
"xe2z",
"3xi",
"3xo",
"3xu",
"1z",
"2z.",
"za2ț",
"2zb",
"2z2g",
"2zi.",
"zi2an",
"zi2ar",
"3zii",
"3zil",
"z4m",
"2z1n",
"3z2ol",
"3zon",
"zu2ț",
"2z2v",
"z3vă",
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.