content
stringlengths 5
1.05M
|
|---|
local QBCore = exports['qb-core']:GetCoreObject()
QBCore.Functions.CreateCallback('qb-spawn:server:getOwnedHouses', function(source, cb, cid)
if cid ~= nil then
local houses = exports.oxmysql:executeSync('SELECT * FROM player_houses WHERE citizenid = ?', {cid})
if houses[1] ~= nil then
cb(houses)
else
cb(nil)
end
else
cb(nil)
end
end)
|
local txBackground = surface.GetTextureID("models/aw_model_materials/cloth_a")
local rt = GetRenderTarget( "AWFlagTexture", 512, 512 )
aw_flag_mat = CreateMaterial( "AWFlagMaterial", "UnlitGeneric", {
["$basetexture"] = "color/white",
["$model"] = "1"
} )
if !aw_team_flags or !flags_rts then
flags_rts = {}
aw_team_flags = {}
end
function draw_flag(flag, scale, res)
local x, y = 0, 0
for i=1, res*res do
draw.RoundedBox( 0, x * scale, y * scale, scale, scale, aw_flag_colors[flag[i] or 0] or Color(255, 255, 255))
x = x + 1
if x >= res then
x = 0
y = y + 1
end
end
end
function update_rt(team)
if !flags_rts[team] then
flags_rts[team] = GetRenderTarget( "AWFlagTexture"..team, 512, 512 )
end
render.PushRenderTarget( flags_rts[team], 0, 0, 1024, 1024)
cam.Start2D()
draw.RoundedBox( 0, 0, 0, 1024, 1024, Color(255, 255, 255) )
draw_flag(aw_team_flags[team] or {}, 1024 / 32, 32)
cam.End2D()
render.PopRenderTarget()
end
function aw_render_flag_texture(matScreen, team)
if !flags_rts[team] then
update_rt(team)
end
aw_flag_mat:SetTexture("$basetexture", flags_rts[team])
end
net.Receive("aw_sync_flag", function()
local team = net.ReadInt(16)
local len = net.ReadInt(32)
local flag = {}
for k=0, len do
table.insert(flag, net.ReadInt(5))
end
aw_team_flags[team] = flag
update_rt(team)
end)
|
require"imlua"
local filename = "lena.jpg"
local image = im.FileImageLoad(filename)
local r = image[0]
local g = image[1]
local b = image[2]
for row = 0, image:Height() - 1, 10 do
for column = 0, image:Width() - 1, 10 do
r[row][column] = 0
g[row][column] = 0
b[row][column] = 0
end
end
image:Save("lena_indexing.bmp", "BMP")
|
local _={}
_.set_random_color=function(entity)
entity.color={
r=_rnd(),
g=_rnd(),
b=_rnd(),
}
end
return _
|
-- mRename...lua
renamer:renameStart()
return true
|
------------------------------------------------------------
-- Copyright (c) 2016 tacigar. All rights reserved.
-- https://github.com/tacigar/maidroid
------------------------------------------------------------
-- maidroid.animation_frames represents the animation frame data
-- of "models/maidroid.b3d".
maidroid.animation_frames = {
STAND = {x = 1, y = 78},
SIT = {x = 81, y = 160},
LAY = {x = 162, y = 165},
WALK = {x = 168, y = 187},
MINE = {x = 189, y = 198},
WALK_MINE = {x = 200, y = 219},
}
-- maidroid.registered_maidroids represents a table that contains
-- definitions of maidroid registered by maidroid.register_maidroid.
maidroid.registered_maidroids = {}
-- maidroid.registered_cores represents a table that contains
-- definitions of core registered by maidroid.register_core.
maidroid.registered_cores = {}
-- maidroid.registered_eggs represents a table that contains
-- definition of egg registered by maidroid.register_egg.
maidroid.registered_eggs = {}
-- maidroid.is_core reports whether a item is a core item by the name.
function maidroid.is_core(item_name)
if maidroid.registered_cores[item_name] then
return true
end
return false
end
-- maidroid.is_maidroid reports whether a name is maidroid's name.
function maidroid.is_maidroid(name)
if maidroid.registered_maidroids[name] then
return true
end
return false
end
---------------------------------------------------------------------
-- maidroid.maidroid represents a table that contains common methods
-- for maidroid object.
-- this table must be contains by a metatable.__index of maidroid self tables.
-- minetest.register_entity set initial properties as a metatable.__index, so
-- this table's methods must be put there.
maidroid.maidroid = {}
-- maidroid.maidroid.get_inventory returns a inventory of a maidroid.
function maidroid.maidroid.get_inventory(self)
return minetest.get_inventory {
type = "detached",
name = self.inventory_name,
}
end
-- maidroid.maidroid.get_core_name returns a name of a maidroid's current core.
function maidroid.maidroid.get_core_name(self)
local inv = self:get_inventory()
return inv:get_stack("core", 1):get_name()
end
-- maidroid.maidroid.get_core returns a maidroid's current core definition.
function maidroid.maidroid.get_core(self)
local name = self:get_core_name()
if name ~= "" then
return maidroid.registered_cores[name]
end
return nil
end
-- maidroid.maidroid.get_nearest_player returns a player object who
-- is the nearest to the maidroid.
function maidroid.maidroid.get_nearest_player(self, range_distance)
local player, min_distance = nil, range_distance
local position = self.object:get_pos()
local all_objects = minetest.get_objects_inside_radius(position, range_distance)
for _, object in pairs(all_objects) do
if object:is_player() then
local player_position = object:get_pos()
local distance = vector.distance(position, player_position)
if distance < min_distance then
min_distance = distance
player = object
end
end
end
return player
end
-- maidroid.maidroid.get_front returns a position in front of the maidroid.
function maidroid.maidroid.get_front(self)
local direction = self:get_look_direction()
if math.abs(direction.x) >= 0.5 then
if direction.x > 0 then direction.x = 1 else direction.x = -1 end
else
direction.x = 0
end
if math.abs(direction.z) >= 0.5 then
if direction.z > 0 then direction.z = 1 else direction.z = -1 end
else
direction.z = 0
end
return vector.add(vector.round(self.object:get_pos()), direction)
end
-- maidroid.maidroid.get_front_node returns a node that exists in front of the maidroid.
function maidroid.maidroid.get_front_node(self)
local front = self:get_front()
return minetest.get_node(front)
end
-- maidroid.maidroid.get_look_direction returns a normalized vector that is
-- the maidroid's looking direction.
function maidroid.maidroid.get_look_direction(self)
local yaw = self.object:getyaw()
return vector.normalize{x = -math.sin(yaw), y = 0.0, z = math.cos(yaw)}
end
-- maidroid.maidroid.set_animation sets the maidroid's animation.
-- this method is wrapper for self.object:set_animation.
function maidroid.maidroid.set_animation(self, frame)
self.object:set_animation(frame, 15, 0)
end
-- maidroid.maidroid.set_yaw_by_direction sets the maidroid's yaw
-- by a direction vector.
function maidroid.maidroid.set_yaw_by_direction(self, direction)
self.object:set_yaw(math.atan2(direction.z, direction.x) - math.pi / 2)
end
-- maidroid.maidroid.get_wield_item_stack returns the maidroid's wield item's stack.
function maidroid.maidroid.get_wield_item_stack(self)
local inv = self:get_inventory()
return inv:get_stack("wield_item", 1)
end
-- maidroid.maidroid.set_wield_item_stack sets maidroid's wield item stack.
function maidroid.maidroid.set_wield_item_stack(self, stack)
local inv = self:get_inventory()
inv:set_stack("wield_item", 1, stack)
end
-- maidroid.maidroid.add_item_to_main add item to main slot.
-- and returns leftover.
function maidroid.maidroid.add_item_to_main(self, stack)
local inv = self:get_inventory()
return inv:add_item("main", stack)
end
-- maidroid.maidroid.move_main_to_wield moves itemstack from main to wield.
-- if this function fails then returns false, else returns true.
function maidroid.maidroid.move_main_to_wield(self, pred)
local inv = self:get_inventory()
local main_size = inv:get_size("main")
for i = 1, main_size do
local stack = inv:get_stack("main", i)
if pred(stack:get_name()) then
local wield_stack = inv:get_stack("wield_item", 1)
inv:set_stack("wield_item", 1, stack)
inv:set_stack("main", i, wield_stack)
return true
end
end
return false
end
-- maidroid.maidroid.is_named reports the maidroid is still named.
function maidroid.maidroid.is_named(self)
return self.nametag ~= ""
end
-- maidroid.maidroid.has_item_in_main reports whether the maidroid has item.
function maidroid.maidroid.has_item_in_main(self, pred)
local inv = self:get_inventory()
local stacks = inv:get_list("main")
for _, stack in ipairs(stacks) do
local itemname = stack:get_name()
if pred(itemname) then
return true
end
end
end
-- maidroid.maidroid.change_direction change direction to destination and velocity vector.
function maidroid.maidroid.change_direction(self, destination)
local position = self.object:get_pos()
local direction = vector.subtract(destination, position)
direction.y = 0
local velocity = vector.multiply(vector.normalize(direction), 1.5)
self.object:setvelocity(velocity)
self:set_yaw_by_direction(direction)
end
-- maidroid.maidroid.change_direction_randomly change direction randonly.
function maidroid.maidroid.change_direction_randomly(self)
local direction = {
x = math.random(0, 5) * 2 - 5,
y = 0,
z = math.random(0, 5) * 2 - 5,
}
local velocity = vector.multiply(vector.normalize(direction), 1.5)
self.object:setvelocity(velocity)
self:set_yaw_by_direction(direction)
end
-- maidroid.maidroid.update_infotext updates the infotext of the maidroid.
function maidroid.maidroid.update_infotext(self)
local infotext = ""
local core_name = self:get_core_name()
if core_name ~= "" then
if self.pause then
infotext = infotext .. "this maidroid is paused\n"
else
infotext = infotext .. "this maidroid is active\n"
end
infotext = infotext .. "[Core] : " .. core_name .. "\n"
else
infotext = infotext .. "this maidroid is inactive\n[Core] : None\n"
end
infotext = infotext .. "[Owner] : " .. self.owner_name
self.object:set_properties{infotext = infotext}
end
---------------------------------------------------------------------
-- maidroid.manufacturing_data represents a table that contains manufacturing data.
-- this table's keys are product names, and values are manufacturing numbers
-- that has been already manufactured.
maidroid.manufacturing_data = (function()
local file_name = minetest.get_worldpath() .. "/manufacturing_data"
minetest.register_on_shutdown(function()
local file = io.open(file_name, "w")
file:write(minetest.serialize(maidroid.manufacturing_data))
file:close()
end)
local file = io.open(file_name, "r")
if file ~= nil then
local data = file:read("*a")
file:close()
return minetest.deserialize(data)
end
return {}
end) ()
--------------------------------------------------------------------
-- register empty item entity definition.
-- this entity may be hold by maidroid's hands.
do
minetest.register_craftitem("maidroid:dummy_empty_craftitem", {
wield_image = "maidroid_dummy_empty_craftitem.png",
})
local function on_activate(self, staticdata)
self.object:set_properties{textures={"maidroid:dummy_empty_craftitem"}}
end
local function on_step(self, dtime)
if self.maidroid_object then
local luaentity = self.maidroid_object:get_luaentity()
if luaentity then
local stack = luaentity:get_wield_item_stack()
if stack:get_name() ~= self.itemname then
if stack:is_empty() then
self.itemname = ""
self.object:set_properties{textures={"maidroid:dummy_empty_craftitem"}}
else
self.itemname = stack:get_name()
self.object:set_properties{textures={self.itemname}}
end
end
return
end
end
-- if cannot find maidroid, delete empty item.
self.object:remove()
return
end
minetest.register_entity("maidroid:dummy_item", {
hp_max = 1,
visual = "wielditem",
visual_size = {x = 0.025, y = 0.025},
collisionbox = {0, 0, 0, 0, 0, 0},
physical = false,
textures = {"air"},
on_activate = on_activate,
on_step = on_step,
itemname = "",
maidroid_object = nil
})
end
---------------------------------------------------------------------
-- maidroid.register_core registers a definition of a new core.
function maidroid.register_core(core_name, def)
maidroid.registered_cores[core_name] = def
minetest.register_tool(core_name, {
stack_max = 1,
description = def.description,
inventory_image = def.inventory_image,
})
end
-- maidroid.register_egg registers a definition of a new egg.
function maidroid.register_egg(egg_name, def)
maidroid.registered_eggs[egg_name] = def
minetest.register_tool(egg_name, {
description = def.description,
inventory_image = def.inventory_image,
stack_max = 1,
on_use = function(itemstack, user, pointed_thing)
if pointed_thing.above ~= nil and def.product_name ~= nil then
-- set maidroid's direction.
local new_maidroid = minetest.add_entity(pointed_thing.above, def.product_name)
new_maidroid:get_luaentity():set_yaw_by_direction(
vector.subtract(user:get_pos(), new_maidroid:get_pos())
)
new_maidroid:get_luaentity().owner_name = user:get_player_name()
new_maidroid:get_luaentity():update_infotext()
itemstack:take_item()
return itemstack
end
return nil
end,
})
end
-- maidroid.register_maidroid registers a definition of a new maidroid.
function maidroid.register_maidroid(product_name, def)
maidroid.registered_maidroids[product_name] = def
-- initialize manufacturing number of a new maidroid.
if maidroid.manufacturing_data[product_name] == nil then
maidroid.manufacturing_data[product_name] = 0
end
-- create_inventory creates a new inventory, and returns it.
local function create_inventory(self)
self.inventory_name = product_name .. "_" .. tostring(self.manufacturing_number)
local inventory = minetest.create_detached_inventory(self.inventory_name, {
on_put = function(inv, listname, index, stack, player)
if listname == "core" then
local core_name = stack:get_name()
local core = maidroid.registered_cores[core_name]
core.on_start(self)
self:update_infotext()
end
end,
allow_put = function(inv, listname, index, stack, player)
-- only cores can put to a core inventory.
if listname == "main" then
return stack:get_count()
elseif listname == "core" and maidroid.is_core(stack:get_name()) then
return stack:get_count()
elseif listname == "wield_item" then
return 0
end
return 0
end,
on_take = function(inv, listname, index, stack, player)
if listname == "core" then
local core_name = stack:get_name()
local core = maidroid.registered_cores[core_name]
core.on_stop(self)
self:update_infotext()
end
end,
allow_take = function(inv, listname, index, stack, player)
if listname == "wield_item" then
return 0
end
return stack:get_count()
end,
on_move = function(inv, from_list, from_index, to_list, to_index, count, player)
if to_list == "core" or from_list == "core" then
local core_name = inv:get_stack(to_list, to_index):get_name()
local core = maidroid.registered_cores[core_name]
if to_list == "core" then
core.on_start(self)
elseif from_list == "core" then
core.on_stop(self)
end
self:update_infotext()
end
end,
allow_move = function(inv, from_list, from_index, to_list, to_index, count, player)
if to_list == "wield_item" then
return 0
end
if to_list == "main" then
return count
elseif to_list == "core" and maidroid.is_core(inv:get_stack(from_list, from_index):get_name()) then
return count
end
return 0
end,
})
inventory:set_size("main", 16)
inventory:set_size("core", 1)
inventory:set_size("wield_item", 1)
return inventory
end
-- create_formspec_string returns a string that represents a formspec definition.
local function create_formspec_string(self)
return "size[8,9]"
.. default.gui_bg
.. default.gui_bg_img
.. default.gui_slots
.. "list[detached:"..self.inventory_name..";main;0,0;4,4;]"
.. "label[4.5,1;core]"
.. "list[detached:"..self.inventory_name..";core;4.5,1.5;1,1;]"
.. "list[current_player;main;0,5;8,1;]"
.. "list[current_player;main;0,6.2;8,3;8]"
.. "label[5.5,1;wield]"
.. "list[detached:"..self.inventory_name..";wield_item;5.5,1.5;1,1;]"
end
-- on_activate is a callback function that is called when the object is created or recreated.
local function on_activate(self, staticdata)
-- parse the staticdata, and compose a inventory.
if staticdata == "" then
self.manufacturing_number = maidroid.manufacturing_data[product_name]
maidroid.manufacturing_data[product_name] = maidroid.manufacturing_data[product_name] + 1
create_inventory(self)
else
-- if static data is not empty string, this object has beed already created.
local data = minetest.deserialize(staticdata)
self.manufacturing_number = data["manufacturing_number"]
self.nametag = data["nametag"]
self.owner_name = data["owner_name"]
local inventory = create_inventory(self)
for list_name, list in pairs(data["inventory"]) do
inventory:set_list(list_name, list)
end
end
self:update_infotext()
self.object:set_nametag_attributes{
text = self.nametag
}
-- attach dummy item to new maidroid.
local dummy_item = minetest.add_entity(self.object:get_pos(), "maidroid:dummy_item")
dummy_item:set_attach(self.object, "Arm_R", {x = 0.065, y = 0.50, z = -0.15}, {x = -45, y = 0, z = 0})
dummy_item:get_luaentity().maidroid_object = self.object
local core = self:get_core()
if core ~= nil then
core.on_start(self)
else
self.object:set_velocity{x = 0, y = 0, z = 0}
self.object:set_acceleration{x = 0, y = -10, z = 0}
end
end
-- get_staticdata is a callback function that is called when the object is destroyed.
local function get_staticdata(self)
local inventory = self:get_inventory()
local data = {
["manufacturing_number"] = self.manufacturing_number,
["nametag"] = self.nametag,
["owner_name"] = self.owner_name,
["inventory"] = {},
}
-- set lists.
for list_name, list in pairs(inventory:get_lists()) do
data["inventory"][list_name] = {}
for i, item in ipairs(list) do
data["inventory"][list_name][i] = item:to_string()
end
end
return minetest.serialize(data)
end
-- maidroid.maidroid.pickup_item pickup items placed and put it to main slot.
local function pickup_item(self)
local pos = self.object:get_pos()
local radius = 1.0
local all_objects = minetest.get_objects_inside_radius(pos, radius)
for _, obj in ipairs(all_objects) do
if not obj:is_player() and obj:get_luaentity() then
local itemstring = obj:get_luaentity().itemstring
if minetest.registered_items[itemstring] ~= nil then
local inv = self:get_inventory()
local stack = ItemStack(itemstring)
local leftover = inv:add_item("main", stack)
minetest.add_item(obj:get_pos(), leftover)
obj:get_luaentity().itemstring = ""
obj:remove()
end
end
end
end
-- on_step is a callback function that is called every delta times.
local function on_step(self, dtime)
-- if owner didn't login, the maidroid does nothing.
if not minetest.get_player_by_name(self.owner_name) then
return
end
-- pickup surrounding item.
pickup_item(self)
-- do core method.
local core = self:get_core()
if (not self.pause) and core then
core.on_step(self, dtime)
end
end
-- on_rightclick is a callback function that is called when a player right-click them.
local function on_rightclick(self, clicker)
minetest.show_formspec(
clicker:get_player_name(),
"maidroid:gui",
create_formspec_string(self)
)
end
-- on_punch is a callback function that is called when a player punch then.
local function on_punch(self, puncher, time_from_last_punch, tool_capabilities, dir)
local core = self:get_core()
if self.pause == true then
self.pause = false
if core then
core.on_resume(self)
end
else
self.pause = true
if core then
core.on_pause(self)
end
end
self:update_infotext()
end
-- register a definition of a new maidroid.
minetest.register_entity(product_name, {
-- basic initial properties
hp_max = def.hp_max,
weight = def.weight,
mesh = def.mesh,
textures = def.textures,
physical = true,
visual = "mesh",
visual_size = {x = 7.5, y = 7.5},
collisionbox = {-0.25, -0.375, -0.25, 0.25, 0.75, 0.25},
is_visible = true,
makes_footstep_sound = true,
infotext = "",
nametag = "",
-- extra initial properties
pause = false,
manufacturing_number = -1,
owner_name = "",
-- callback methods.
on_activate = on_activate,
on_step = on_step,
on_rightclick = on_rightclick,
on_punch = on_punch,
get_staticdata = get_staticdata,
-- extra methods.
get_inventory = maidroid.maidroid.get_inventory,
get_core = maidroid.maidroid.get_core,
get_core_name = maidroid.maidroid.get_core_name,
get_nearest_player = maidroid.maidroid.get_nearest_player,
get_front = maidroid.maidroid.get_front,
get_front_node = maidroid.maidroid.get_front_node,
get_look_direction = maidroid.maidroid.get_look_direction,
set_animation = maidroid.maidroid.set_animation,
set_yaw_by_direction = maidroid.maidroid.set_yaw_by_direction,
get_wield_item_stack = maidroid.maidroid.get_wield_item_stack,
set_wield_item_stack = maidroid.maidroid.set_wield_item_stack,
add_item_to_main = maidroid.maidroid.add_item_to_main,
move_main_to_wield = maidroid.maidroid.move_main_to_wield,
is_named = maidroid.maidroid.is_named,
has_item_in_main = maidroid.maidroid.has_item_in_main,
change_direction = maidroid.maidroid.change_direction,
change_direction_randomly = maidroid.maidroid.change_direction_randomly,
update_infotext = maidroid.maidroid.update_infotext,
})
-- register maidroid egg.
maidroid.register_egg(product_name .. "_egg", {
description = product_name .. " egg",
inventory_image = def.egg_image,
product_name = product_name,
})
end
|
modifier_beastmaster_statue_activatable = class({})
--------------------------------------------------------------------------------
function modifier_beastmaster_statue_activatable:IsPurgable()
return false
end
--------------------------------------------------------------------------------
function modifier_beastmaster_statue_activatable:IsHidden()
return true
end
--------------------------------------------------------------------------------
function modifier_beastmaster_statue_activatable:IsAura()
return true
end
--------------------------------------------------------------------------------
function modifier_beastmaster_statue_activatable:GetModifierAura()
return "modifier_beastmaster_statue_aura_effect"
end
--------------------------------------------------------------------------------
function modifier_beastmaster_statue_activatable:GetAuraSearchTeam()
return DOTA_UNIT_TARGET_TEAM_ENEMY
end
--------------------------------------------------------------------------------
function modifier_beastmaster_statue_activatable:GetAuraSearchType()
return DOTA_UNIT_TARGET_HERO
end
--------------------------------------------------------------------------------
function modifier_beastmaster_statue_activatable:GetAuraRadius()
return self.aura_radius
end
--------------------------------------------------------------------------------
function modifier_beastmaster_statue_activatable:OnCreated( kv )
self.aura_radius = self:GetAbility():GetSpecialValueFor( "aura_radius" )
end
--------------------------------------------------------------------------------
|
return {'coquille','coquilles'}
|
--[[
3D2D VGUI Wrapper
Copyright (c) 2015 Alexander Overvoorde, Matt Stevens
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]--
local origin = Vector(0, 0, 0)
local angle = Vector(0, 0, 0)
local normal = Vector(0, 0, 0)
local scale = 0
-- Helper functions
local function getCursorPos()
local p = util.IntersectRayWithPlane(LocalPlayer():EyePos(), LocalPlayer():GetAimVector(), origin, normal)
-- if there wasn't an intersection, don't calculate anything.
if not p then return 0, 0 end
local offset = origin - p
local angle2 = angle:Angle()
angle2:RotateAroundAxis( normal, 90 )
angle2 = angle2:Forward()
local offsetp = Vector(offset.x, offset.y, offset.z)
offsetp:Rotate(-normal:Angle())
local x = -offsetp.y
local y = offsetp.z
return x, y
end
local function getParents( pnl )
local parents = {}
local parent = pnl:GetParent()
while ( parent ) do
table.insert( parents, parent )
parent = parent:GetParent()
end
return parents
end
local function absolutePanelPos( pnl )
local x, y = pnl:GetPos()
local parents = getParents( pnl )
for _, parent in ipairs( parents ) do
local px, py = parent:GetPos()
x = x + px
y = y + py
end
return x, y
end
local function pointInsidePanel( pnl, x, y )
local px, py = absolutePanelPos( pnl )
local sx, sy = pnl:GetSize()
x = x / scale
y = y / scale
return x >= px and y >= py and x <= px + sx and y <= py + sy
end
-- Input
local inputWindows = {}
local usedpanel = {}
local function isMouseOver( pnl )
return pointInsidePanel( pnl, getCursorPos() )
end
local function postPanelEvent( pnl, event, ... )
if ( not IsValid( pnl ) or not pnl:IsVisible() or not pointInsidePanel(pnl, getCursorPos()) ) then return false end
local handled = false
for i, child in pairs( pnl:GetChildren() ) do
if ( postPanelEvent( child, event, ... ) ) then
handled = true
break
end
end
if ( not handled and pnl[ event ] ) then
pnl[ event ]( pnl, ... )
usedpanel[pnl] = {...}
return true
else
return false
end
end
local function checkHover( pnl, x, y )
if not (x and y) then
x,y=getCursorPos()
end
pnl.WasHovered = pnl.Hovered
pnl.Hovered = pointInsidePanel( pnl, x, y )
if not pnl.WasHovered and pnl.Hovered then
if pnl.OnCursorEntered then pnl:OnCursorEntered() end
elseif pnl.WasHovered and not pnl.Hovered then
if pnl.OnCursorExited then pnl:OnCursorExited() end
end
for i, child in pairs( pnl:GetChildren() ) do
if ( child:IsValid() and child:IsVisible() ) then checkHover( child, x, y ) end
end
end
-- Mouse input
hook.Add( "KeyPress", "VGUI3D2DMousePress", function( _, key )
if ( key == IN_USE ) then
for pnl in pairs( inputWindows ) do
if ( IsValid( pnl ) ) then
origin = pnl.Origin
scale = pnl.Scale
angle = pnl.Angle
normal = pnl.Normal
local key = input.IsKeyDown(KEY_LSHIFT) and MOUSE_RIGHT or MOUSE_LEFT
postPanelEvent( pnl, "OnMousePressed", key )
end
end
end
end )
hook.Add( "KeyRelease", "VGUI3D2DMouseRelease", function( _, key )
if ( key == IN_USE ) then
for pnl, key in pairs( usedpanel ) do
if ( IsValid(pnl) ) then
origin = pnl.Origin
scale = pnl.Scale
angle = pnl.Angle
normal = pnl.Normal
if ( pnl[ "OnMouseReleased" ] ) then
pnl[ "OnMouseReleased" ]( pnl, key[ 1 ] )
end
usedpanel[ pnl ] = nil
end
end
end
end )
-- Key input
-- TODO, OH DEAR.
-- Drawing:
function vgui.Start3D2D( pos, ang, res )
origin = pos
scale = res
angle = ang:Forward()
normal = Angle( ang.p, ang.y, ang.r )
normal:RotateAroundAxis( ang:Forward(), -90 )
normal:RotateAroundAxis( ang:Right(), 90 )
normal = normal:Forward()
cam.Start3D2D( pos, ang, res )
end
local Panel = FindMetaTable("Panel")
function Panel:Paint3D2D()
if not self:IsValid() then return end
-- Add it to the list of windows to receive input
inputWindows[ self ] = true
-- Override gui.MouseX and gui.MouseY for certain stuff
local oldMouseX = gui.MouseX
local oldMouseY = gui.MouseY
local cx, cy = getCursorPos()
function gui.MouseX()
return cx / scale
end
function gui.MouseY()
return cy / scale
end
-- Override think of DFrame's to correct the mouse pos by changing the active orientation
if self.Think then
if not self.OThink then
self.OThink = self.Think
self.Think = function()
origin = self.Origin
scale = self.Scale
angle = self.Angle
normal = self.Normal
self:OThink()
end
end
end
-- Update the hover state of controls
checkHover( self )
-- Store the orientation of the window to calculate the position outside the render loop
self.Origin = origin
self.Scale = scale
self.Angle = angle
self.Normal = normal
-- Draw it manually
self:SetPaintedManually( false )
self:PaintManual()
self:SetPaintedManually( true )
gui.MouseX = oldMouseX
gui.MouseY = oldMouseY
end
function vgui.End3D2D()
cam.End3D2D()
end
-- Keep track of child controls
-- It's now useless
-- http://wiki.garrysmod.com/page/Panel/GetChildren
-- http://wiki.garrysmod.com/page/Panel/GetParent
--[[
if not vguiCreate then vguiCreate = vgui.Create end
function vgui.Create( class, parent )
local pnl = vguiCreate( class, parent )
if not pnl then return end
pnl.Parent = parent
pnl.Class = class
if parent and type(parent) == "Panel" and IsValid(parent) then
if not parent.Childs then parent.Childs = {} end
parent.Childs[ pnl ] = true
end
return pnl
end
--]]
|
local hudebug = {}
hudebug.active = false
hudebug.color = {}
hudebug.page = 1
hudebug.pageCount = 0
hudebug.color.r = 255
hudebug.color.g = 0
hudebug.color.b = 0
hudebug.color.a = 255
hudebug.posx = 5
hudebug.posy = 0
hudebug.scale = 1.2
hudebug.slots = {}
--[[
function hudebug.setHudColor
@param (number) r, (number) g, (number) b, (number) a
-Values for red, green, blue, and alpha (opacity) respectively.
Changes the color of the text displayed by HuDebug.
]]--
function hudebug.setHudColor(r,g,b,a)
hudebug.color.r = r
hudebug.color.g = g
hudebug.color.b = b
hudebug.color.a = a
end
--[[
function hudebug.setScale
@param (number) scale
-Value for scaling of text
Scales the HuDebug text.
]]--
function hudebug.setScale(scale)
hudebug.scale = scale
end
--[[
function hudebug.setPosition
@param (number) x, (number) y
-Values for position of debugging.
Moves the position of the top-left corner of the text.
]]--
function hudebug.setPosition(x,y)
hudebug.posx = x
hudebug.posy = y
end
--[[
function hudebug.pageName
@param (number) page, (string) name
-Which page index and what name for the page
Either creates or renames the page depending on whether or not hudebug.slots[page] existed.
]]--
function hudebug.pageName(page, name)
if not hudebug.slots[page] then
hudebug.slots[page] = {}
hudebug.slots[page].name = name
hudebug.pageCount = hudebug.pageCount + 1
else
hudebug.slots[page].name = name
end
end
--[[
function hudebug.updateMsg
@param (number) page, (integer/string) slot, (string/integer) msg
Stores the message msg to page page in the unique key slot
]]--
function hudebug.updateMsg(page,slot,msg)
if msg == "" then
msg = nil end
if not hudebug.slots[page] then
hudebug.slots[page] = {}
end
hudebug.slots[page][slot] = msg
end
--[[
function hudebug.reset
Resets all pages and values.
If you call this you need to create pages again. Maybe add a clear Page function
]]--
function hudebug.reset()
hudebug.slots = nil
hudebug.slots = {}
if hudebug.active then
hudebug.active = false
end
end
--[[
function hudebug.toggle
Sets active state of HuDebug to on/off
]]--
function hudebug.toggle()
hudebug.active = not hudebug.active
end
--[[
function hudebug.nextPage
Iterates through the pages. Pages, like lua tables, start at index 1.
]]--
function hudebug.nextPage()
local p = hudebug.page
if p == hudebug.pageCount then
hudebug.page = 1
else
hudebug.page = p + 1
end
end
--[[
function hudebug.draw
Draws the text to the screen.
]]--
function hudebug.draw()
if (not hudebug.active) then return end
local c = 1
local y = hudebug.posy
local page = hudebug.page
love.graphics.push()
love.graphics.scale(hudebug.scale)
love.graphics.reset()
love.graphics.setColor(hudebug.color.r,hudebug.color.g,hudebug.color.b,hudebug.color.a)
love.graphics.print("--Debug: " .. hudebug.slots[page].name .. "--",hudebug.posx,hudebug.posy)
for i,v in pairs(hudebug.slots[page]) do
if i ~= "name" then
y = hudebug.posy+ c*20
love.graphics.print(v,hudebug.posx,y)
c = c+1
end
end
love.graphics.pop()
end
return hudebug
|
local function query_tracetag()
local bar = tiler_lbar(active_display(), function(ctx,msg,done,set)
if (done and active_display().selected) then
image_tracetag(active_display().selected.canvas, msg);
end
return {};
end);
bar:set_label("tracetag (wnd.canvas):");
end
return {
{
name = "query_tracetag",
label = "Tracetag",
kind = "action",
handler = query_tracetag
}
};
|
-- Copyright (C) 2013 Yichun Zhang (agentzh)
require "resty.core.uri"
require "resty.core.hash"
require "resty.core.base64"
require "resty.core.regex"
require "resty.core.exit"
require "resty.core.shdict"
require "resty.core.var"
require "resty.core.ctx"
require "resty.core.misc"
require "resty.core.request"
require "resty.core.response"
local base = require "resty.core.base"
return {
version = base.version
}
|
local camZPlus1 = 1500
local camZPlus2 = 50
local pointCamCoords = 75
local pointCamCoords2 = 0
local cam1Time = 500
local cam2Time = 1000
local choosingSpawn = false
RegisterNetEvent('qb-spawn:client:openUI')
AddEventHandler('qb-spawn:client:openUI', function(value)
SetEntityVisible(PlayerPedId(), false)
DoScreenFadeOut(250)
Citizen.Wait(1000)
DoScreenFadeIn(250)
QBCore.Functions.GetPlayerData(function(PlayerData)
cam = CreateCamWithParams("DEFAULT_SCRIPTED_CAMERA", PlayerData.position.x, PlayerData.position.y, PlayerData.position.z + camZPlus1, -85.00, 0.00, 0.00, 100.00, false, 0)
SetCamActive(cam, true)
RenderScriptCams(true, false, 1, true, true)
end)
Citizen.Wait(500)
SetDisplay(value)
end)
RegisterNUICallback("exit", function(data)
SetNuiFocus(false, false)
SendNUIMessage({
type = "ui",
status = false
})
choosingSpawn = false
end)
local cam = nil
local cam2 = nil
RegisterNUICallback('setCam', function(data)
local location = tostring(data.posname)
local type = tostring(data.type)
DoScreenFadeOut(200)
Citizen.Wait(500)
DoScreenFadeIn(200)
if DoesCamExist(cam) then
DestroyCam(cam, true)
end
if DoesCamExist(cam2) then
DestroyCam(cam2, true)
end
if type == "current" then
QBCore.Functions.GetPlayerData(function(PlayerData)
cam2 = CreateCamWithParams("DEFAULT_SCRIPTED_CAMERA", PlayerData.position.x, PlayerData.position.y, PlayerData.position.z + camZPlus1, 300.00,0.00,0.00, 110.00, false, 0)
PointCamAtCoord(cam2, PlayerData.position.x, PlayerData.position.y, PlayerData.position.z + pointCamCoords)
SetCamActiveWithInterp(cam2, cam, cam1Time, true, true)
-- SetCamActiveWithInterp(camTo, camFrom, duration, easeLocation, easeRotation)
if DoesCamExist(cam) then
DestroyCam(cam, true)
end
Citizen.Wait(cam1Time)
cam = CreateCamWithParams("DEFAULT_SCRIPTED_CAMERA", PlayerData.position.x, PlayerData.position.y, PlayerData.position.z + camZPlus2, 300.00,0.00,0.00, 110.00, false, 0)
PointCamAtCoord(cam, PlayerData.position.x, PlayerData.position.y, PlayerData.position.z + pointCamCoords2)
SetCamActiveWithInterp(cam, cam2, cam2Time, true, true)
SetEntityCoords(PlayerPedId(), PlayerData.position.x, PlayerData.position.y, PlayerData.position.z)
end)
elseif type == "house" then
local campos = Config.Houses[location].coords.enter
cam2 = CreateCamWithParams("DEFAULT_SCRIPTED_CAMERA", campos.x, campos.y, campos.z + camZPlus1, 300.00,0.00,0.00, 110.00, false, 0)
PointCamAtCoord(cam2, campos.x, campos.y, campos.z + pointCamCoords)
SetCamActiveWithInterp(cam2, cam, cam1Time, true, true)
if DoesCamExist(cam) then
DestroyCam(cam, true)
end
Citizen.Wait(cam1Time)
cam = CreateCamWithParams("DEFAULT_SCRIPTED_CAMERA", campos.x, campos.y, campos.z + camZPlus2, 300.00,0.00,0.00, 110.00, false, 0)
PointCamAtCoord(cam, campos.x, campos.y, campos.z + pointCamCoords2)
SetCamActiveWithInterp(cam, cam2, cam2Time, true, true)
SetEntityCoords(PlayerPedId(), campos.x, campos.y, campos.z)
elseif type == "normal" then
local campos = QB.Spawns[location].coords
cam2 = CreateCamWithParams("DEFAULT_SCRIPTED_CAMERA", campos.x, campos.y, campos.z + camZPlus1, 300.00,0.00,0.00, 110.00, false, 0)
PointCamAtCoord(cam2, campos.x, campos.y, campos.z + pointCamCoords)
SetCamActiveWithInterp(cam2, cam, cam1Time, true, true)
if DoesCamExist(cam) then
DestroyCam(cam, true)
end
Citizen.Wait(cam1Time)
cam = CreateCamWithParams("DEFAULT_SCRIPTED_CAMERA", campos.x, campos.y, campos.z + camZPlus2, 300.00,0.00,0.00, 110.00, false, 0)
PointCamAtCoord(cam, campos.x, campos.y, campos.z + pointCamCoords2)
SetCamActiveWithInterp(cam, cam2, cam2Time, true, true)
SetEntityCoords(PlayerPedId(), campos.x, campos.y, campos.z)
elseif type == "appartment" then
local campos = Apartments.Locations[location].coords.enter
cam2 = CreateCamWithParams("DEFAULT_SCRIPTED_CAMERA", campos.x, campos.y, campos.z + camZPlus1, 300.00,0.00,0.00, 110.00, false, 0)
PointCamAtCoord(cam2, campos.x, campos.y, campos.z + pointCamCoords)
SetCamActiveWithInterp(cam2, cam, cam1Time, true, true)
if DoesCamExist(cam) then
DestroyCam(cam, true)
end
Citizen.Wait(cam1Time)
cam = CreateCamWithParams("DEFAULT_SCRIPTED_CAMERA", campos.x, campos.y, campos.z + camZPlus2, 300.00,0.00,0.00, 110.00, false, 0)
PointCamAtCoord(cam, campos.x, campos.y, campos.z + pointCamCoords2)
SetCamActiveWithInterp(cam, cam2, cam2Time, true, true)
SetEntityCoords(PlayerPedId(), campos.x, campos.y, campos.z)
end
end)
RegisterNUICallback('chooseAppa', function(data)
local appaYeet = data.appType
SetDisplay(false)
DoScreenFadeOut(500)
Citizen.Wait(5000)
TriggerServerEvent("apartments:server:CreateApartment", appaYeet, Apartments.Locations[appaYeet].label)
TriggerServerEvent('QBCore:Server:OnPlayerLoaded')
TriggerEvent('QBCore:Client:OnPlayerLoaded')
FreezeEntityPosition(ped, false)
RenderScriptCams(false, true, 500, true, true)
SetCamActive(cam, false)
DestroyCam(cam, true)
SetCamActive(cam2, false)
DestroyCam(cam2, true)
SetEntityVisible(PlayerPedId(), true)
end)
RegisterNUICallback('spawnplayer', function(data)
local location = tostring(data.spawnloc)
local type = tostring(data.typeLoc)
local ped = PlayerPedId()
local PlayerData = QBCore.Functions.GetPlayerData()
local insideMeta = PlayerData.metadata["inside"]
if type == "current" then
SetDisplay(false)
DoScreenFadeOut(500)
Citizen.Wait(2000)
QBCore.Functions.GetPlayerData(function(PlayerData)
SetEntityCoords(PlayerPedId(), PlayerData.position.x, PlayerData.position.y, PlayerData.position.z)
SetEntityHeading(PlayerPedId(), PlayerData.position.a)
FreezeEntityPosition(PlayerPedId(), false)
end)
if insideMeta.house ~= nil then
local houseId = insideMeta.house
TriggerEvent('qb-houses:client:LastLocationHouse', houseId)
elseif insideMeta.apartment.apartmentType ~= nil or insideMeta.apartment.apartmentId ~= nil then
local apartmentType = insideMeta.apartment.apartmentType
local apartmentId = insideMeta.apartment.apartmentId
TriggerEvent('qb-apartments:client:LastLocationHouse', apartmentType, apartmentId)
end
TriggerServerEvent('QBCore:Server:OnPlayerLoaded')
TriggerEvent('QBCore:Client:OnPlayerLoaded')
FreezeEntityPosition(ped, false)
RenderScriptCams(false, true, 500, true, true)
SetCamActive(cam, false)
DestroyCam(cam, true)
SetCamActive(cam2, false)
DestroyCam(cam2, true)
SetEntityVisible(PlayerPedId(), true)
Citizen.Wait(500)
DoScreenFadeIn(250)
elseif type == "house" then
SetDisplay(false)
DoScreenFadeOut(500)
Citizen.Wait(2000)
TriggerEvent('qb-houses:client:enterOwnedHouse', location)
TriggerServerEvent('QBCore:Server:OnPlayerLoaded')
TriggerEvent('QBCore:Client:OnPlayerLoaded')
TriggerServerEvent('qb-houses:server:SetInsideMeta', 0, false)
TriggerServerEvent('qb-apartments:server:SetInsideMeta', 0, 0, false)
FreezeEntityPosition(ped, false)
RenderScriptCams(false, true, 500, true, true)
SetCamActive(cam, false)
DestroyCam(cam, true)
SetCamActive(cam2, false)
DestroyCam(cam2, true)
SetEntityVisible(PlayerPedId(), true)
Citizen.Wait(500)
DoScreenFadeIn(250)
elseif type == "normal" then
local pos = QB.Spawns[location].coords
SetDisplay(false)
DoScreenFadeOut(500)
Citizen.Wait(2000)
SetEntityCoords(ped, pos.x, pos.y, pos.z)
TriggerServerEvent('QBCore:Server:OnPlayerLoaded')
TriggerEvent('QBCore:Client:OnPlayerLoaded')
TriggerServerEvent('qb-houses:server:SetInsideMeta', 0, false)
TriggerServerEvent('qb-apartments:server:SetInsideMeta', 0, 0, false)
Citizen.Wait(500)
SetEntityCoords(ped, pos.x, pos.y, pos.z)
SetEntityHeading(ped, pos.w)
FreezeEntityPosition(ped, false)
RenderScriptCams(false, true, 500, true, true)
SetCamActive(cam, false)
DestroyCam(cam, true)
SetCamActive(cam2, false)
DestroyCam(cam2, true)
SetEntityVisible(PlayerPedId(), true)
Citizen.Wait(500)
DoScreenFadeIn(250)
end
end)
function SetDisplay(bool)
choosingSpawn = bool
SetNuiFocus(bool, bool)
SendNUIMessage({
type = "ui",
status = bool
})
end
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
if choosingSpawn then
DisableAllControlActions(0)
else
Citizen.Wait(1000)
end
end
end)
RegisterNetEvent('qb-houses:client:setHouseConfig')
AddEventHandler('qb-houses:client:setHouseConfig', function(houseConfig)
Config.Houses = houseConfig
end)
RegisterNetEvent('qb-spawn:client:setupSpawns')
AddEventHandler('qb-spawn:client:setupSpawns', function(cData, new, apps)
if not new then
QBCore.Functions.TriggerCallback('qb-spawn:server:getOwnedHouses', function(houses)
local myHouses = {}
if houses ~= nil then
for i = 1, (#houses), 1 do
table.insert(myHouses, {
house = houses[i].house,
label = Config.Houses[houses[i].house].adress,
})
end
end
Citizen.Wait(500)
SendNUIMessage({
action = "setupLocations",
locations = QB.Spawns,
houses = myHouses,
})
end, cData.citizenid)
elseif new then
SendNUIMessage({
action = "setupAppartements",
locations = apps,
})
end
end)
|
local ls = require "luasnip"
local s = ls.snippet
local t = ls.text_node
local i = ls.insert_node
local snippets = {
s("shebang", {
t { "#!/usr/bin/env python", "" },
i(0),
}),
}
return snippets
|
vim.cmd [[
setlocal commentstring=//\ %s
setlocal formatoptions-=o
]]
|
local path = "hall/backpack/backpack_qn_pin.png"
local backpack_qn_pin_map = {
["backpack_bg.png"] = {
file=path,
x=2,y=2,
width=723,height=720,
rotated=false
},
["backpack_succes.png"] = {
file=path,
x=727,y=2,
width=278,height=529,
rotated=true
},
["backpack_tittle_bg.png"] = {
file=path,
x=2,y=724,
width=700,height=82,
rotated=false
},
["backpack_twocode_bg.png"] = {
file=path,
x=727,y=533,
width=218,height=218,
rotated=false
},
["backpack_compound_bg2.png"] = {
file=path,
x=2,y=808,
width=492,height=76,
rotated=false
},
["backpack_compound_bg.png"] = {
file=path,
x=496,y=808,
width=492,height=76,
rotated=false
},
["backpack_box.png"] = {
file=path,
x=1007,y=2,
width=189,height=186,
rotated=true
},
["backpack_recordNothing.png"] = {
file=path,
x=1198,y=2,
width=187,height=178,
rotated=false
},
["backpack_forNothing.png"] = {
file=path,
x=1387,y=2,
width=184,height=159,
rotated=false
},
["backpack_num_bg.png"] = {
file=path,
x=1573,y=2,
width=226,height=58,
rotated=false
},
["backpack_recharge_fail.png"] = {
file=path,
x=1801,y=2,
width=198,height=58,
rotated=false
},
["backpack_sell_num_bg.png"] = {
file=path,
x=1573,y=62,
width=222,height=49,
rotated=false
},
["backpack_box_name_bg.png"] = {
file=path,
x=1797,y=62,
width=186,height=48,
rotated=false
},
["backpack_title1.png"] = {
file=path,
x=1797,y=112,
width=166,height=44,
rotated=false
},
["backpack_shard_ok.png"] = {
file=path,
x=1573,y=113,
width=166,height=44,
rotated=false
},
["backpack_recharge_fail_tittle.png"] = {
file=path,
x=2001,y=2,
width=44,height=166,
rotated=true
},
["backpack_detail.png"] = {
file=path,
x=1741,y=158,
width=166,height=44,
rotated=false
},
["backpack_sell_success.png"] = {
file=path,
x=1573,y=159,
width=166,height=44,
rotated=false
},
["shop_sell_tittle.png"] = {
file=path,
x=1387,y=163,
width=166,height=44,
rotated=false
},
["backpack_getGift.png"] = {
file=path,
x=1198,y=182,
width=166,height=44,
rotated=false
},
["backpack_record_tittle.png"] = {
file=path,
x=1007,y=190,
width=166,height=44,
rotated=false
},
["backpack_record_button.png"] = {
file=path,
x=1909,y=170,
width=123,height=59,
rotated=false
},
["backpack_leftTop_corner.png"] = {
file=path,
x=1741,y=204,
width=142,height=44,
rotated=false
},
["backpack_sell_sub.png"] = {
file=path,
x=1555,y=205,
width=71,height=66,
rotated=false
},
["backpack_sell_add.png"] = {
file=path,
x=1628,y=205,
width=71,height=66,
rotated=false
},
["backpack_share_bg.png"] = {
file=path,
x=1366,y=209,
width=76,height=56,
rotated=true
},
["backpack_share_circle.png"] = {
file=path,
x=1444,y=209,
width=62,height=48,
rotated=false
},
["backpack_share_friend.png"] = {
file=path,
x=1175,y=228,
width=62,height=48,
rotated=false
},
["backpack_des_bg.png"] = {
file=path,
x=1741,y=113,
width=40,height=40,
rotated=false
},
["backpack_back.png"] = {
file=path,
x=1701,y=205,
width=39,height=39,
rotated=false
},
["backpack_bg2.png"] = {
file=path,
x=1508,y=209,
width=39,height=39,
rotated=false
},
["backpack_corner_num_bg.png"] = {
file=path,
x=1239,y=228,
width=59,height=25,
rotated=false
},
}
return backpack_qn_pin_map
|
--returns the length of a line from the origin to x, y.
function Magnitude(x, y)
return math.sqrt(x * x + y * y)
end
--returns the distance between two 2D points
function Distance(x1, y1, x2, y2)
return Magnitude(x2 - x1, y2 - y1)
end
--returns true if two circles overlap
function CirclesOverlap(x1, y1, radius1, x2, y2, radius2)
return Distance(x1, y1, x2, y2) <= radius1 + radius2
end
--returns true if two boxes overlap
function BoxesOverlap(x1, y1, w1, h1, x2, y2, w2, h2)
if x1 >= x2 + w2 then return false end
if y1 >= y2 + h2 then return false end
if x2 >= x1 + w1 then return false end
if y2 >= y1 + h1 then return false end
return true
end
--circle has x, y, radius; box has x, y, w, h.
--returns true if the circle and box are overlapping.
function CircleBoxOverlap(circle, box)
local closestX;
local closestY;
if circle.x < box.x then
closestX = box.x
elseif circle.x > box.x + box.w then
closestX = box.x + box.w
else
closestX = circle.x
end
if circle.y < box.y then
closestY = box.y
elseif circle.y > box.y + box.h then
closestY = box.y + box.h
else
closestY = circle.y
end
return Distance(closestX, closestY, circle.x, circle.y) < circle.radius;
end
|
#!/usr/bin/env lua
local mk = require "mk"
local json = require "mk.json"
local app = mk.new()
app:all(json.filter)
app:get(
"/",
function(req, res)
return 200, [[
<html>
<head><title>Hello World</title></head>
<body><h1>Hello World!</h1></body>
</html>
]]
end
)
app:get(
"/json",
function(req, res)
res:json()
return 200, {foo = "bar", items = {1, 2, 3, 4}}
end
)
app:get(
"/error",
function(req, res)
error("route error")
end
)
app:post(
"/json",
function (req, res)
local json = req:json()
res:json()
return 200, { item = json.array }
end
)
app:run(os.getenv("PORT") or 8080)
|
local ZipWriter = require 'ZipWriter'
local path = require 'lib.path'
---@class Zip
---@field file any
---@field fp string
local Zip = {}
Zip.__index = Zip
local READER_DESC = {
istext = true,
isfile = true,
isdir = false,
exattrib = {
ZipWriter.NIX_FILE_ATTR.IFREG, ZipWriter.NIX_FILE_ATTR.IRUSR,
ZipWriter.NIX_FILE_ATTR.IWUSR, ZipWriter.NIX_FILE_ATTR.IRGRP,
ZipWriter.DOS_FILE_ATTR.ARCH
}
}
--- Creates a new .zip file in the specified filepath.
--- Returns nil and an error message if it's unable to open the file.
--- @param fp string file path
--- @return Zip?
--- @return string? errmsg
function Zip.new(fp)
local zipfile = ZipWriter.new()
local f, errmsg = io.open(fp, 'w+b')
if not f then
return nil, errmsg
end
zipfile:open_stream(f, true)
return setmetatable({fp = fp, file = zipfile}, Zip)
end
local function reader(fp)
local f, errmsg = io.open(fp, 'rb')
if not f then
return nil, errmsg
end
return function()
local chunk = f:read(1024)
if chunk then return chunk end
f:close()
end
end
--- Adds a source file to a destination path inside the zip.
--- @param src_fp string source file path
--- @param dst_fp string destination file path
--- @return boolean
--- @return string? errmsg
function Zip:add(src_fp, dst_fp)
if path.isfile(src_fp) then
local r, errmsg = reader(src_fp)
if not r then
return false, errmsg
end
self.file:write(dst_fp, READER_DESC, r)
return true
elseif path.isdir(src_fp) then
for nfp in path.each(src_fp .. path.DIR_SEP) do
local ok, e = self:add(nfp, path.join(dst_fp, path.basename(nfp)))
if not ok then return ok, e end
end
return true
else
return false
end
end
---Closes the zip file
---@return number
function Zip:close()
return self.file:close()
end
return Zip
|
function sleep(n)
local t0 = os.clock()
while os.clock() - t0 <= n do end
end
function onTrigger(context, session)
log:info('Sleeping forever')
while true do
sleep(1)
end
end
|
fx_version 'cerulean'
games { 'gta5' }
author 'MOXHA'
server_only 'yes'
server_scripts {
'@mysql-async/lib/MySQL.lua',
'server.lua',
'bot.js'
}
|
local activityData = {
{ factor=0, name="Выберите в/звание"},
{ factor=5000, name="рядовой"},
{ factor=5500, name="ефрейтор"},
{ factor=6000, name="младший сержант"},
{ factor=6500, name="сержант"},
{ factor=7000, name="старший сержант"},
{ factor=7500, name="старшина"},
{ factor=8000, name="прапорщик"},
{ factor=8500, name="старший прапорщик" },
{ factor=9500, name="младший лейтенант"},
{ factor=10000, name="лейтенант" },
{ factor=10500, name="старший лейтенант" },
{ factor=11000, name="капитан"},
{ factor=11500, name="майор"},
{ factor=12000, name="подполковник"},
{ factor=13000, name="полковник" },
{ factor=20000, name="генерал-майор" },
{ factor=22000, name="генерал-лейтенант" },
{ factor=25000, name="генерал-полковник"},
{ factor=27000, name="генерал армии" },
{ factor=30000, name="маршал РФ"},
}
return activityData;
|
--━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━--
--━━━━━━━━━━━━━━━━━━━❰ Configs ❱━━━━━━━━━━━━━━━━━━━--
-- List of patterns(file or folder) which describes a directory as project root li
vim.g.rooter_pattern = { '.__project__', '.git', 'Makefile', '_darcs', '.hg', '.bzr', '.svn', 'node_modules', 'CMakeLists.txt' }
-- Whether to change directory to outermost root directory or not
vim.g.outermost_root = false
--━━━━━━━━━━━━━━━━━❰ end of Configs ❱━━━━━━━━━━━━━━━━━--
--━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━--
|
return {
eng_mode = 'mqconsole',
on_boot = {
ntp_sync = false,
script = 'boot'
},
cron = {
cycle = 500,
dsleep = false,
cycle_cell = 21,
watchdog_interval = 5000,
},
--[[crontab = {
{every = 1, job = 'color_upd'},
{every = 20, job = 'random'},
}]]
}
|
--[[
Get Jobs by filter criteria
Input:
KEYS[1] Queue / Name Set Key
ARGV[1] Key Prefix
ARGV[2] filter criteria as a json encoded string
ARGV[3] cursor
ARGV[4] count
]]
local ADMIN_KEYS = {
['wait'] = 1,
['waiting'] = 1,
['events'] = 1,
['meta'] = 1,
['active'] = 1,
['completed'] = 1,
['failed'] = 1,
['stalled'] = 1,
['delayed'] = 1,
['paused'] = 1,
['repeat'] = 1,
['id'] = 1,
}
local JsType = {
NULL = 'nil',
STRING = 'string',
BOOLEAN = 'boolean',
NUMBER = 'number',
FUNCTION = 'function',
OBJECT = 'object',
ARRAY = 'array'
}
-- no array, object, or function types
local JS_SIMPLE_TYPES = {
['string'] = true,
['null'] = true,
['nil'] = true,
['boolean'] = true,
['number'] = true,
}
--- UTILITY -----------------------------------------------------------------------------
--- https://lua.programmingpedia.net/en/tutorial/5829/pattern-matching
local IDENTIFIER_PATTERN = "[%a_]+[%a%d_]*"
local OPERATOR_NAME_PATTERN = "^$" .. IDENTIFIER_PATTERN
-- Check whether the given name passes for an operator. We assume any field name
-- starting with '$' is an operator. This is cheap and safe to do since keys beginning
-- with '$' should be reserved for internal use.
-- @param {String} name
local function isOperator(name)
return string.match(name, OPERATOR_NAME_PATTERN) ~= nil
end
local function isString(val)
return type(val) == 'string'
end
local function isNil(val)
return type(val) == 'nil' or val == cjson.null
end
local function isNumber(val)
return type(val) == 'number'
end
local function isFunction(val)
return type(val) == 'function'
end
local function isObject(val)
return type(val) == 'table'
end
local function isArray(t)
if (type(t) ~= 'table') then
return false
end
local i = 0
for _ in pairs(t) do
i = i + 1
-- note: explicitly check against nil here !!!
-- for arrays coming from JSON, we can have cjson.null, which we
-- want to support
if (t[i] == nil) then
return false
end
end
return true
end
local function isEqual(o1, o2, ignore_mt)
local ty1 = type(o1)
local ty2 = type(o2)
if ty1 ~= ty2 then
-- special case handling of nil
if (isNil(o1) and isNil(o2)) then
return true
end
return false
end
-- non-table types can be directly compared
if ty1 ~= 'table' then
return o1 == o2
end
-- as well as tables which have the metamethod __eq
local mt = getmetatable(o1)
if not ignore_mt and mt and mt.__eq then
return o1 == o2
end
for k1, v1 in pairs(o1) do
local v2 = o2[k1]
if isNil(v2) or not isEqual(v1, v2, ignore_mt) then
return false
end
end
for k2, v2 in pairs(o2) do
local v1 = o1[k2]
if isNil(v1) then
return false
end
end
return true
end
local function getType(val)
if (val == cjson.null) then
return JsType.NULL
end
local t = type(val)
if (t == 'table') then
return isArray(val) and JsType.ARRAY or JsType.OBJECT
end
return t
end
local function keys(obj)
local res = {}
for k, v in pairs(obj) do
res[#res + 1] = k
end
return res
end
-- Create a new table of values by mapping each value in table through a transformation function
-- @param obj {table}
-- @param callback {function}
-- @return {*}
local function map(obj, callback)
assert(isObject(obj), 'expected an array in map')
local accumulator = {}
for _, current in ipairs(obj) do
table.insert(accumulator, callback(current, _))
end
return accumulator
end
local function slice(array, start, stop)
start = start or 1
stop = stop or #array
local t = {}
for i = start, stop do
t[i - start + 1] = array[i]
end
return t
end
---- Casting --------------------------------------------------
local function tonum(value, ...)
local num = 0
local t = type(value)
if t == 'string' then
local ok = pcall(function()
num = value + 0
end)
if not ok then
num = math.huge
end
elseif (t == 'boolean') then
num = value and 1 or 0
elseif (t == 'number') then
num = value
elseif (t == 'function') then
num = tonum(value(...))
end
return num
end
local dblQuote = function(v)
return '"' .. v .. '"'
end
local function tostr(value, ...)
local str = '';
local t = type(value)
-- local v;
if (t == 'string') then
return value
elseif (t == 'boolean') then
return (value and 'true' or 'false')
elseif isNil(value) then
return 'nil'
elseif (t == 'number') then
return value .. ''
elseif (t == 'function') then
return tostr(value(...))
elseif (t == 'table') then
local delims = { '{', '}' }
if isArray(value) then
delims = { '[', ']' }
end
str = delims[1]
for k, v in pairs(value) do
v = isString(v) and dblQuote(v) or tostr(v, ...)
if isNumber(k) then
str = str .. v .. ', '
else
str = str .. dblQuote(k) .. ': ' .. v .. ', '
end
end
str = str:sub(0, #str - 2) .. delims[2]
end
return str
end
local function debug(msg)
redis.call('rpush', 'search-debug', tostr(msg))
end
-- raw value should be a kv table [name, value, name, value ...]
-- convert to an associative array
local function to_hash(value)
local len, result = #value, {}
for k = 1, len, 2 do
result[value[k]] = value[k + 1]
end
return result
end
--
-- Resolve the value of the field (dot separated) on the given object
-- @param obj {Object} the object context
-- @param selector {String} dot separated path to field
-- @param {ResolveOptions} options
-- @returns {*}
--
local function resolve(obj, segments, unwrapArray)
local depth = 0
--
-- Unwrap a single element array to specified depth
-- @param {Array} arr
-- @param {Number} depth
--
local function unwrap(arr, depth)
if (depth < 1) then
return arr
end
while (depth > 0 and #arr == 1) do
arr = arr[1]
depth = depth - 1
end
return arr
end
local function resolve2(o, path)
local value = o
local index = 1
-- debug('resolving path ' .. tostr(path) .. ' in object ' .. tostr(o))
while (index <= #path) do
local field = path[index]
if (type(value) == 'table') then
local numIndex = tonumber(field)
if (isArray(value)) then
-- handle instances like
-- value: { grades: [ { score: 10, max: 100 }, { score:5, max: 10 } ] }
-- path: 'score'
if (numIndex == nil) then
-- On the first iteration, we check if we received a stop flag.
-- If so, we stop to prevent iterating over a nested array value
-- on consecutive object keys in the selector.
if (index == 1 and depth > 0) then
break
end
depth = depth + 1
path = slice(path, index)
local acc = {}
for _, item in ipairs(value) do
local v = resolve2(item, path)
if not isNil(v) then
acc[#acc + 1] = v
end
end
value = acc
break
else
field = (numIndex + 1)
end
end
value = value[field]
else
value = nil
end
-- debug(field .. ':' .. tostr(value) .. ', ' .. tostr(index) .. '/' .. tostr(#path))
index = index + 1
if isNil(value) then
break
end
end
return value
end
local t = type(obj)
if (t == 'table') then
obj = resolve2(obj, segments, 1)
if (unwrapArray) then
obj = unwrap(obj, depth)
end
end
return obj
end
-- Returns a predicate function that matches
-- *all* of the given predicate functions.
local function join_AND(predicates)
if (#predicates == 1) then
return predicates[1]
end
return function(s)
for _, func in ipairs(predicates) do
if not func(s) then
return false
end
end
return true
end
end
---- PREDICATES ------------------------------------------------------------------------
local Predicates = {}
Predicates.__index = Predicates
---- QUERY OPERATORS -------------------------------------------------------------------
--
-- Simplify expression for easy evaluation with query operators map
-- @param expr
-- @returns {*}
local function normalize(expr)
-- normalized primitives
local t = getType(expr)
if (JS_SIMPLE_TYPES[t]) then
return { ['$eq'] = expr }
end
-- normalize object expression
if (isObject(expr)) then
local hasOperator = false
for k, _ in pairs(expr) do
if (isOperator(k)) then
hasOperator = true
break
end
end
-- no valid query operator found, so we do simple comparison
if (not hasOperator) then
return { ['$eq'] = expr }
end
end
return expr
end
local QueryOperators = {}
QueryOperators.__index = QueryOperators
local function compileQuery(criteria)
assert(type(criteria) == 'table', 'query criteria must be an object')
local compiled = {}
local function processOperator(field, operator, value)
local operatorFn = QueryOperators[operator]
assert(operatorFn ~= nil, 'invalid query operator "' .. operator .. '" found');
compiled[#compiled + 1] = operatorFn(field, value)
end
local function parse(criteria)
for field, expr in pairs(criteria) do
if ('$expr' == field) then
processOperator(field, field, expr);
elseif (field == '$and' or field == '$or' or field == '$nor') then
processOperator(field, field, expr)
else
--- normalize expression
local expr = normalize(expr)
for op, val in pairs(expr) do
assert(isOperator(op), 'unknown top level operator: "' .. op .. '"')
processOperator(field, op, val)
end
end
end
assert(#compiled > 0, 'empty criteria: ' .. tostr(criteria))
return join_AND(compiled)
end
return parse(criteria)
end
local function split (str, sep)
local sep, fields = sep or ".", {}
local pattern = string.format("([^%s]+)", sep)
str:gsub(pattern, function(c)
fields[#fields + 1] = c
end)
return field
end
local fieldHandlers = {}
local referencedFields = {}
local function getFieldResolver(field)
local handler = fieldHandlers[field]
if (handler == nil) then
local path = split(field, '.')
local segment = #path > 0 and path[1] or field
referencedFields[segment] = true
handler = function(obj)
local val = resolve(obj, path)
-- debug('value: ' .. tostr(val))
return isnum and tonumber(val) or val
end
end
fieldHandlers[field] = handler
return handler
end
--- EXPRESSION OPERATORS -------------------------------------------------------------
local ExprOperators = {}
ExprOperators.__index = ExprOperators
--
-- Parses an expression and returns a function which returns
-- the actual value of the expression using a given object as context
--
-- @param {table} expr the expression for the given field
-- @param {string} operator the operator to resolve the field with
-- @returns {function}
--
local function parseExpression(expr, operator)
-- debug('parsing ' .. tostr(expr))
local function parseArray()
local compiled = {}
for _, item in ipairs(expr) do
compiled[#compiled + 1] = parseExpression(item)
end
return function(obj)
local result = {}
for _, fn in ipairs(compiled) do
local v = fn(obj)
result[#result + 1] = (v == nil) and cjson.null or v
end
return result
end
end
local function parseObject()
local compiled = {}
for key, val in pairs(expr) do
compiled[key] = parseExpression(val, key)
-- must run ONLY one aggregate operator per expression
-- if so, return result of the computed value
if (ExprOperators[key] ~= nil) then
-- there should be only one operator
local _keys = keys(expr)
-- debug('key: ' .. key.. ', Keys: ' .. tostr(_keys))
assert(#_keys == 1, 'Invalid aggregation expression "' .. tostr(expr) .. '".')
compiled = compiled[_keys[1]]
end
end
if (isFunction(compiled)) then
return compiled
end
return function(obj)
local result = {}
for key, fn in pairs(compiled) do
local v = fn(obj)
result[key] = (v == nil) and cjson.null or v
end
return result
end
end
-- if the field of the object is a valid operator
if (operator and ExprOperators[operator] ~= nil) then
return ExprOperators[operator](expr);
end
-- if expr is a variable for an object field
if (isString(expr) and #expr > 1 and expr:sub(1, 1) == '$') then
local field = expr:sub(2)
return getFieldResolver(field)
end
if type(expr) == 'table' then
if (isArray(expr)) then
return parseArray()
else
return parseObject()
end
else
return function()
return expr
end
end
end
--------------- Conditional Operators --------------------------------------------------------------
local function trim(input, chars, left, right)
assert(isObject(args), 'trim expects an array or object')
if (input == cjson.null) then return nil end
assert(isString(input), 'trim: missing input')
if (#input == 0) then return '' end
if (isNil(chars)) then
if (left and right) then
return (input:gsub("^%s*(.-)%s*$", "%1"))
elseif left then
return (input:gsub("^%s*", ""))
elseif right then
local n = #input
while n > 0 and input:find("^%s", n) do n = n - 1 end
return input:sub(1, n)
end
return input
else
assert(isString(chars), 'chars should be a string')
local len = #input
local codepoints = {}
for i = 1, #chars do
local ch = chars:sub(i, i)
codepoints[ch] = true
end
--- debug('chars = ' .. chars .. ', codepoints = ' .. tostr(codepoints))
local i = 1
local j = len
local s = input
while (left and i < j and codepoints[s:sub(i,i)]) do
i = i + 1
end
while (right and j > i and codepoints[s:sub(j,j)]) do
j = j - 1
end
return s:sub(i, j)
end
end
local function prepJsonField(job, name)
if referencedFields[name] then
local saved = job[name]
local success, res = pcall(cjson.decode, saved)
if (success) then
job[name] = res
else
-- todo: throw
end
return saved
end
end
local function getIdPart(key, prefix)
local sub = key:sub(#prefix + 1)
if sub:find(':') == nil and not ADMIN_KEYS[sub] then
return sub
end
return nil
end
local function prepareJobHash(id, jobHash)
local job = to_hash(jobHash)
job['id'] = id
prepJsonField(job, 'data')
return job
end
local function search(key, keyPrefix, criteria, cursor, count)
count = count or 20
local scanResult = {}
local predicate = compileQuery(criteria)
local match = keyPrefix .. '*'
local fullScan = false
local keyType = ''
if (key ~= nil and #key > 0) then
keyType = redis.call("TYPE", key)
if type(keyType) ~= 'string' then
keyType = keyType["ok"]
end
end
if (keyType == 'zset') then
scanResult = redis.call('zscan', key, cursor, "COUNT", count, 'MATCH', match)
elseif keyType == 'set' then
scanResult = redis.call('sscan', key, cursor, "COUNT", count, 'MATCH', match)
elseif keyType == 'hash' then
scanResult = redis.call('hscan', key, cursor, "COUNT", count, 'MATCH', match)
else
fullScan = true
--- todo: check version, and if > 6.0 uset the TYPE option
--- https://redis.io/commands/scan#the-type-option
scanResult = redis.call('scan', cursor, "COUNT", count, 'MATCH', match)
end
local newCursor = scanResult[1]
local scannedJobIds = scanResult[2]
if (fullScan) then
-- does a keyspace as opposed to list scan. Filter out non-ids
local filteredIds = {}
local i = 0
for _, key in ipairs(scannedJobIds) do
local id = getIdPart(key, keyPrefix)
if (id ~= nil) then
i = i + 1
filteredIds[i] = id
end
scannedJobIds = filteredIds
end
elseif (keyType == 'zset') then
-- strip out score
scannedJobIds = map(scannedJobIds, function(val)
return val[1]
end)
end
local result = { newCursor }
for _, jobId in pairs(scannedJobIds) do
local jobIdKey = keyPrefix .. jobId
local jobHash = redis.pcall('HGETALL', jobIdKey)
if (isObject(jobHash) and #jobHash) then
local job = prepareJobHash(jobId, jobHash)
if (predicate(job)) then
table.insert(result, "jobId")
table.insert(result, jobId)
for _, value in pairs(jobHash) do
table.insert(result, value)
end
end
end
end
return result
end
local key = KEYS[1]
local prefix = assert(ARGV[1], 'Key prefix not specified')
local criteria = assert(cjson.decode(ARGV[2]), 'Invalid filter criteria. Expected a JSON encoded string')
local cursor = ARGV[3]
local count = ARGV[4] or 10
return search(key, prefix, criteria, cursor, count)
-- TODO: validate expression
|
-- This is a "stub" file. It's a little start on your solution.
-- It's not a complete solution though; you have to write some code.
-- Table to be returned by the hello-world module.
local hello_world = {}
-- Add the hello() function to the table returned by this module.
function hello_world.hello()
-- Write some code here to pass the test suite.
return 'Hello, World!'
end
-- Return the hello_world table to make it accessible as a module.
return hello_world
|
local plugin_name = 'linux.memory'
local every = 60
local function collect()
local jsonb = {}
for line in io.lines(HOST_PROC_DIR .. "/meminfo") do
local key, value = line:match("(%S+)%:%s+%d+%s+kB"), line:match("%S%:%s+(%d+)%s+kB")
if key and value then
jsonb[key] = tonumber(value * 1024)
end
end
local jsonb, err = json.encode(jsonb)
if err then error(err) end
storage_insert_metric({ plugin = plugin_name, json = jsonb })
end
run_every(collect, every)
|
modifier_slark_essence_shift_lua_stack = class({})
--------------------------------------------------------------------------------
-- Classifications
function modifier_slark_essence_shift_lua_stack:IsHidden()
return true
end
function modifier_slark_essence_shift_lua_stack:IsPurgable()
return false
end
function modifier_slark_essence_shift_lua_stack:GetAttributes()
return MODIFIER_ATTRIBUTE_MULTIPLE
end
--------------------------------------------------------------------------------
-- Initializations
function modifier_slark_essence_shift_lua_stack:OnCreated( kv )
end
function modifier_slark_essence_shift_lua_stack:OnRemoved()
if IsServer() then
self.modifier:RemoveStack()
end
end
|
-------------------------
-- Civ 6 Map Utilities --
-------------------------
include "MapEnums.lua"
-- Computes IsAdjacentToLand from plotTypes table (when Map not yet filled in)
function IsAdjacentToLand(plotTypes, iX, iY)
local adjacentPlot;
local iW, iH = Map.GetGridSize();
for direction = 0, DirectionTypes.NUM_DIRECTION_TYPES - 1, 1 do
adjacentPlot = Map.GetAdjacentPlot(iX, iY, direction);
if (adjacentPlot ~= nil) then
local i = adjacentPlot:GetY() * iW + adjacentPlot:GetX();
if (plotTypes[i] ~= g_PLOT_TYPE_OCEAN) then
return true;
end
end
end
return false;
end
------------------------------------------------------------------------------
function IsAdjacentToLandPlot(x, y)
-- Computes IsAdjacentToLand from the plot
local plot = Map.GetPlot(x, y);
if plot ~= nil then
for direction = 0, DirectionTypes.NUM_DIRECTION_TYPES - 1, 1 do
local testPlot = Map.GetAdjacentPlot(x, y, direction);
if testPlot ~= nil then
if testPlot:IsWater() == false then -- Adjacent plot is land
return true
end
end
end
end
return false
end
-- Computes IsAdjacentToIce to check if there are any adjacent river plots
function IsAdjacentToRiver(iX, iY)
local adjacentPlot;
local iW, iH = Map.GetGridSize();
if (Map.GetPlot(x, y) == nil) then
return false;
end
if (Map.GetPlot(x, y):IsRiver() == true) then
return true;
end
for direction = 0, DirectionTypes.NUM_DIRECTION_TYPES - 1, 1 do
adjacentPlot = Map.GetAdjacentPlot(iX, iY, direction);
if (adjacentPlot ~= nil) then
if (adjacentPlot:IsRiver()) then
return true;
end
end
end
return false;
end
-- Computes IsAdjacentToIce to check if there is ice
function IsAdjacentToIce(iX, iY)
local adjacentPlot;
local iW, iH = Map.GetGridSize();
for direction = 0, DirectionTypes.NUM_DIRECTION_TYPES - 1, 1 do
adjacentPlot = Map.GetAdjacentPlot(iX, iY, direction);
if (adjacentPlot ~= nil) then
local featureType = adjacentPlot:GetFeatureType();
if (featureType ~= nil and featureType == g_FEATURE_ICE) then
return true;
end
end
end
return false;
end
-- Computes IsAdjacentToShallowWater from terrainTypes table (when Map not yet filled in)
function IsAdjacentToShallowWater(terrainTypes, iX, iY)
local adjacentPlot;
local iW, iH = Map.GetGridSize();
for direction = 0, DirectionTypes.NUM_DIRECTION_TYPES - 1, 1 do
adjacentPlot = Map.GetAdjacentPlot(iX, iY, direction);
if (adjacentPlot ~= nil) then
local i = adjacentPlot:GetY() * iW + adjacentPlot:GetX();
if (terrainTypes[i] == g_TERRAIN_TYPE_COAST) then
return true;
end
end
end
return false;
end
-- Computes IsAdjacentToDesert from terrainTypes table
function IsAdjacentToDesert(terrainTypes, iX, iY)
local adjacentPlot;
local iW, iH = Map.GetGridSize();
for direction = 0, DirectionTypes.NUM_DIRECTION_TYPES - 1, 1 do
adjacentPlot = Map.GetAdjacentPlot(iX, iY, direction);
if (adjacentPlot ~= nil) then
local i = adjacentPlot:GetY() * iW + adjacentPlot:GetX();
if (terrainTypes[i] == g_TERRAIN_TYPE_DESERT) then
return true;
end
end
end
return false;
end
------------------------------------------------------------------------------
function AdjacentToWater(x, y, plotTypes)
-- Checks a plot (x, y) to see if it is any type of land adjacent to at least one body of salt water.
local plot = Map.GetPlot(x, y);
local iW, iH = Map.GetGridSize();
local index = y * iW + x + 1;
if plotTypes[index] ~= g_PLOT_TYPE_OCEAN then -- This plot is land, process it.
for direction = 0, DirectionTypes.NUM_DIRECTION_TYPES - 1, 1 do
local testPlot = Map.GetAdjacentPlot(x, y, direction);
if testPlot ~= nil then
local newIndex = testPlot:GetIndex();
if plotTypes[newIndex] == g_PLOT_TYPE_OCEAN then --Ocean
return true;
end
end
end
end
-- Current plot is itself water, or else no salt water found among adjacent plots.
return false
end
------------------------------------------------------------------------------
function AdjacentToSaltWater(x, y)
-- Checks a plot (x, y) to see if it is any type of land adjacent to at least one body of salt water.
local plot = Map.GetPlot(x, y);
if not plot:IsWater() then -- This plot is land, process it.
for direction = 0, DirectionTypes.NUM_DIRECTION_TYPES - 1, 1 do
local testPlot = Map.GetAdjacentPlot(x, y, direction);
if testPlot ~= nil then
if testPlot:IsWater() then -- Adjacent plot is water! Check if ocean or lake.
if testPlot:IsLake() == false then -- Adjacent plot is salt water!
return true
end
end
end
end
end
-- Current plot is itself water, or else no salt water found among adjacent plots.
return false
end
------------------------------------------------------------------------------
function AdjacentToMountain(x, y)
-- Checks a plot (x, y) to see if it is any type of land adjacent to at least one mountain.
local plot = Map.GetPlot(x, y);
if not plot:IsWater() then -- This plot is land, process it.
for direction = 0, DirectionTypes.NUM_DIRECTION_TYPES - 1, 1 do
local testPlot = Map.GetAdjacentPlot(x, y, direction);
if testPlot ~= nil then
if testPlot:IsMountain() then -- Adjacent plot is mountain!
return true
end
end
end
end
-- Current plot is itself water, or else no salt water found among adjacent plots.
return false
end
-------------------------------------------------------------------------------------------
-- FUNCTIONS TO SHIFT LANDMASSES (i.e. to better center them)
-------------------------------------------------------------------------------------------
function ShiftPlotTypes(plotTypes)
local shift_x = 0;
local shift_y = 0;
shift_x = DetermineXShift(plotTypes);
shift_y = DetermineYShift(plotTypes);
--print ("shift_x: ", shift_x);
--print ("shift_y: ", shift_y);
ShiftPlotTypesBy(plotTypes, shift_x, shift_y);
end
-------------------------------------------------------------------------------------------
function ShiftPlotTypesBy(plotTypes, xshift, yshift)
local g_iW, g_iH = Map.GetGridSize();
if(xshift > 0 or yshift > 0) then
local iWH = g_iW * g_iH;
local buf = {};
for i = 0, iWH do
buf[i] = plotTypes[i];
end
for iDestY = 0, g_iH do
for iDestX = 0, g_iW do
local iDestI = g_iW * iDestY + iDestX;
local iSourceX = (iDestX + xshift) % g_iW;
local iSourceY = (iDestY + yshift) % g_iH;
local iSourceI = g_iW * iSourceY + iSourceX
plotTypes[iDestI] = buf[iSourceI]
end
end
end
end
-------------------------------------------------------------------------------------------
function DetermineXShift(plotTypes)
--[[ This function will align the most water-heavy vertical portion of the map with the
vertical map edge. This is a form of centering the landmasses, but it emphasizes the
edge not the middle. If there are columns completely empty of land, these will tend to
be chosen as the new map edge, but it is possible for a narrow column between two large
continents to be passed over in favor of the thinnest section of a continent, because
the operation looks at a group of columns not just a single column, then picks the
center of the most water heavy group of columns to be the new vertical map edge. ]]--
local g_iW, g_iH = Map.GetGridSize();
-- First loop through the map columns and record land plots in each column.
local land_totals = {};
for x = 0, g_iW - 1 do
local current_column = 0;
for y = 0, g_iH - 1 do
local i = y * g_iW + x + 1;
if (plotTypes[i] ~= g_PLOT_TYPE_OCEAN) then
current_column = current_column + 1;
end
end
table.insert(land_totals, current_column);
end
-- Now evaluate column groups, each record applying to the center column of the group.
local column_groups = {};
-- Determine the group size in relation to map width.
local group_radius = math.floor(g_iW / 10);
-- Measure the groups.
for column_index = 1, g_iW do
local current_group_total = 0;
for current_column = column_index - group_radius, column_index + group_radius do
local current_index = current_column % g_iW;
if current_index == 0 then -- Modulo of the last column will be zero; this repairs the issue.
current_index = g_iW;
end
current_group_total = current_group_total + land_totals[current_index];
end
table.insert(column_groups, current_group_total);
end
-- Identify the group with the least amount of land in it.
local best_value = g_iH * (2 * group_radius + 1); -- Set initial value to max possible.
local best_group = 1; -- Set initial best group as current map edge.
for column_index, group_land_plots in ipairs(column_groups) do
if group_land_plots < best_value then
best_value = group_land_plots;
best_group = column_index;
end
end
-- Determine X Shift
local x_shift = best_group - 1;
return x_shift;
end
-------------------------------------------------------------------------------------------
function DetermineYShift(plotTypes)
-- Counterpart to DetermineXShift()
local g_iW, g_iH = Map.GetGridSize();
-- First loop through the map rows and record land plots in each row.
local land_totals = {};
for y = 0, g_iH - 1 do
local current_row = 0;
for x = 0, g_iW - 1 do
local i = y * g_iW + x + 1;
if (plotTypes[i] ~= g_PLOT_TYPE_OCEAN) then
current_row = current_row + 1;
end
end
table.insert(land_totals, current_row);
end
-- Now evaluate row groups, each record applying to the center row of the group.
local row_groups = {};
-- Determine the group size in relation to map height.
local group_radius = math.floor(g_iH / 15);
-- Measure the groups.
for row_index = 1, g_iH do
local current_group_total = 0;
for current_row = row_index - group_radius, row_index + group_radius do
local current_index = current_row % g_iH;
if current_index == 0 then -- Modulo of the last row will be zero; this repairs the issue.
current_index = g_iH;
end
current_group_total = current_group_total + land_totals[current_index];
end
table.insert(row_groups, current_group_total);
end
-- Identify the group with the least amount of land in it.
local best_value = g_iW * (2 * group_radius + 1); -- Set initial value to max possible.
local best_group = 1; -- Set initial best group as current map edge.
for row_index, group_land_plots in ipairs(row_groups) do
if group_land_plots < best_value then
best_value = group_land_plots;
best_group = row_index;
end
end
-- Determine Y Shift
local y_shift = best_group - 1;
return y_shift;
end
-------------------------------------------------------------------------------------------
-- LATITUDE LOOKUP
----------------------------------------------------------------------------------
function GetLatitudeAtPlot(variationFrac, iX, iY)
local g_iW, g_iH = Map.GetGridSize();
-- Terrain bands are governed by latitude.
-- Returns a latitude value between 0.0 (tropical) and 1.0 (polar).
local lat = math.abs((g_iH / 2) - iY) / (g_iH / 2);
-- Adjust latitude using variation fractal, to roughen the border between bands:
lat = lat + (128 - variationFrac:GetHeight(iX, iY))/(255.0 * 5.0);
-- Limit to the range [0, 1]:
lat = math.clamp(lat, 0, 1);
return lat;
end
------------------------------------------------------------------------------
-- From former "MapmakerUtilites.lua"
------------------------------------------------------------------------------
function ObtainLandmassBoundaries(iAreaID)
local iW, iH = Map.GetGridSize();
-- Set up variables that will be returned by this function.
local wrapsX = false;
local wrapsY = false;
local iWestX, iEastX, iSouthY, iNorthY, iWidth, iHeight;
if Map:IsWrapX() then -- Check to see if landmass Wraps X.
local foundFirstColumn = false;
local foundLastColumn = false;
for y = 0, iH - 1 do
local plotFirst = Map.GetPlot(0, y);
local plotLast = Map.GetPlot(iW - 1, y);
local area = plotFirst:GetArea():GetID();
if area == iAreaID then -- Found a plot belonging to iAreaID in first column.
foundFirstColumn = true;
end
area = plotLast:GetArea():GetID();
if area == iAreaID then -- Found a plot belonging to iAreaID in last column.
foundLastColumn = true;
end
end
if foundFirstColumn and foundLastColumn then -- Plot on both sides of map edge.
wrapsX = true;
end
end
if Map:IsWrapY() then -- Check to see if landmass Wraps Y.
local foundFirstRow = false;
local foundLastRow = false;
for y = 0, iH - 1 do
local plotFirst = Map.GetPlot(x, 0);
local plotLast = Map.GetPlot(x, iH - 1);
local area = plotFirst:GetArea():GetID();
if area == iAreaID then -- Found a plot belonging to iAreaID in first row.
foundFirstRow = true;
end
area = plotLast:GetArea():GetID();
if area == iAreaID then -- Found a plot belonging to iAreaID in last row.
foundLastRow = true;
end
end
if foundFirstRow and foundLastRow then -- Plot on both sides of map edge.
wrapsY = true;
end
end
-- Find West and East edges of this landmass.
if not wrapsX then -- no X wrap
for x = 0, iW - 1 do -- Check for any area membership one column at a time, left to right.
local foundAreaInColumn = false;
for y = 0, iH - 1 do -- Checking column.
local plot = Map.GetPlot(x, y);
local area = plot:GetArea():GetID();
if area == iAreaID then -- Found a plot belonging to iAreaID, set WestX to this column.
foundAreaInColumn = true;
iWestX = x;
break
end
end
if foundAreaInColumn then -- Found WestX, done looking.
break
end
end
for x = iW - 1, 0, -1 do -- Check for any area membership one column at a time, right to left.
local foundAreaInColumn = false;
for y = 0, iH - 1 do -- Checking column.
local plot = Map.GetPlot(x, y);
local area = plot:GetArea():GetID();
if area == iAreaID then -- Found a plot belonging to iAreaID, set EastX to this column.
foundAreaInColumn = true;
iEastX = x;
break
end
end
if foundAreaInColumn then -- Found EastX, done looking.
break
end
end
else -- Landmass Xwraps.
local landmassSpansEntireWorldX = true;
for x = iW - 2, 1, -1 do -- Check for end of area membership one column at a time, right to left.
local foundAreaInColumn = false;
for y = 0, iH - 1 do -- Checking column.
local plot = Map.GetPlot(x, y);
local area = plot:GetArea():GetID();
if area == iAreaID then -- Found a plot belonging to iAreaID, will have to check the next column too.
foundAreaInColumn = true;
end
end
if not foundAreaInColumn then -- Found empty column, which is just west of WestX.
iWestX = x + 1;
landmassSpansEntireWorldX = false;
break
end
end
for x = 1, iW - 2 do -- Check for end of area membership one column at a time, left to right.
local foundAreaInColumn = false;
for y = 0, iH - 1 do -- Checking column.
local plot = Map.GetPlot(x, y);
local area = plot:GetArea():GetID();
if area == iAreaID then -- Found a plot belonging to iAreaID, will have to check the next column too.
foundAreaInColumn = true;
end
end
if not foundAreaInColumn then -- Found empty column, which is just east of EastX.
iEastX = x - 1;
landmassSpansEntireWorldX = false;
break
end
end
-- If landmass spans entire world, we'll treat it as if it does not wrap.
if landmassSpansEntireWorldX then
wrapsX = false;
iWestX = 0;
iEastX = iW - 1;
end
end
-- Find South and North edges of this landmass.
if not wrapsY then -- no Y wrap
for y = 0, iH - 1 do -- Check for any area membership one row at a time, bottom to top.
local foundAreaInRow = false;
for x = 0, iW - 1 do -- Checking row.
local plot = Map.GetPlot(x, y);
local area = plot:GetArea():GetID();
if area == iAreaID then -- Found a plot belonging to iAreaID, set SouthY to this row.
foundAreaInRow = true;
iSouthY = y;
break
end
end
if foundAreaInRow then -- Found SouthY, done looking.
break
end
end
for y = iH - 1, 0, -1 do -- Check for any area membership one row at a time, top to bottom.
local foundAreaInRow = false;
for x = 0, iW - 1 do -- Checking row.
local plot = Map.GetPlot(x, y);
local area = plot:GetArea():GetID();
if area == iAreaID then -- Found a plot belonging to iAreaID, set NorthY to this row.
foundAreaInRow = true;
iNorthY = y;
break
end
end
if foundAreaInRow then -- Found NorthY, done looking.
break
end
end
else -- Landmass Ywraps.
local landmassSpansEntireWorldY = true;
for y = iH - 2, 1, -1 do -- Check for end of area membership one row at a time, top to bottom.
local foundAreaInRow = false;
for x = 0, iW - 1 do -- Checking row.
local plot = Map.GetPlot(x, y);
local area = plot:GetArea():GetID();
if area == iAreaID then -- Found a plot belonging to iAreaID, will have to check the next row too.
foundAreaInRow = true;
end
end
if not foundAreaInRow then -- Found empty row, which is just south of southY.
iSouthY = y + 1;
landmassSpansEntireWorldY = false;
break
end
end
for y = 1, iH - 2 do -- Check for end of area membership one row at a time, bottom to top.
local foundAreaInRow = false;
for x = 0, iW - 1 do -- Checking row.
local plot = Map.GetPlot(x, y);
local area = plot:GetArea():GetID();
if area == iAreaID then -- Found a plot belonging to iAreaID, will have to check the next row too.
foundAreaInRow = true;
end
end
if not foundAreaInRow then -- Found empty column, which is just north of NorthY.
iNorthY = y - 1;
landmassSpansEntireWorldY = false;
break
end
end
-- If landmass spans entire world, we'll treat it as if it does not wrap.
if landmassSpansEntireWorldY then
wrapsY = false;
iSouthY = 0;
iNorthY = iH - 1;
end
end
-- Convert EastX and NorthY into width and height.
if wrapsX then
iWidth = (iEastX + iW) - iWestX + 1;
else
iWidth = iEastX - iWestX + 1;
end
if wrapsY then
iHeight = (iNorthY + iH) - iSouthY + 1;
else
iHeight = iNorthY - iSouthY + 1;
end
--[[ Log dump for debug purposes only, disable otherwise.
print("--- Landmass Boundary Readout ---");
print("West X:", iWestX, "East X:", iEastX);
print("South Y:", iSouthY, "North Y:", iNorthY);
print("Width:", iWidth, "Height:", iHeight);
local plotTotal = iWidth * iHeight;
print("Total Plots in 'landmass rectangle':", plotTotal);
print("- - - - - - - - - - - - - - - - -");
]]--
-- Insert data into table, then return the table.
local data = {iWestX, iSouthY, iEastX, iNorthY, iWidth, iHeight, wrapsX, wrapsY};
return data
end
------------------------------------------------------------------------------
function GenerateCoastalLandDataTable()
local iW, iH = Map.GetGridSize();
print ("Calling GenerateCoastalLandDataTable");
print ("iW, iH: " .. tostring(iW) .. ", " .. tostring(iH));
local plotDataIsCoastal = table.fill( false, iW * iH);
-- When generating a plot data table incrementally, process Y first so that plots go row by row.
-- Keeping plot data table indices consistent with the main plot database could save you enormous grief.
-- In this case, accessing by plot index, it doesn't matter.
for x = 0, iW - 1 do
for y = 0, iH - 1 do
local plotIsAdjacent = AdjacentToSaltWater(x, y)
if plotIsAdjacent then
local i = iW * y + x + 1;
plotDataIsCoastal[i] = true;
end
end
end
-- returns table
return plotDataIsCoastal
end
------------------------------------------------------------------------------
function GenerateNextToCoastalLandDataTables()
-- Set up data table for IsCoastal
local plotDataIsCoastal = GenerateCoastalLandDataTable()
-- Set up data table for IsNextToCoast
local iW, iH = Map.GetGridSize();
local plotDataIsNextToCoast = table.fill(false, iW * iH);
-- When generating a plot data table incrementally, process Y first so that plots go row by row.
-- Keeping plot data table indices consistent with the main plot database could save you enormous grief.
-- In this case, accessing an existing table by plot index, it doesn't matter.
for x = 0, iW - 1 do
for y = 0, iH - 1 do
local i = iW * y + x + 1;
local plot = Map.GetPlot(x, y);
if plotDataIsCoastal[i] == false and not plot:IsWater() then -- plot is not itself on the coast or in the water.
for direction = 0, DirectionTypes.NUM_DIRECTION_TYPES - 1, 1 do
local testPlot = Map.GetAdjacentPlot(x, y, direction);
if testPlot ~= nil then
local adjX = testPlot:GetX();
local adjY = testPlot:GetY();
local adjI = iW * adjY + adjX + 1;
if plotDataIsCoastal[adjI] == true then
-- The current loop plot is not itself on the coast but is next to a plot that is on the coast.
plotDataIsNextToCoast[i] = true;
end
end
end
end
end
end
-- returns table, table
return plotDataIsCoastal, plotDataIsNextToCoast
end
------------------------------------------------------------------------------
function TestMembership(table, value)
local testResult = false;
for index, data in pairs(table) do
if data == value then
testResult = true;
break
end
end
return testResult
end
------------------------------------------------------------------------------
function GetShuffledCopyOfTable(incoming_table)
-- Designed to operate on tables with no gaps. Does not affect original table.
local len = table.maxn(incoming_table);
local copy = {};
local shuffledVersion = {};
-- Make copy of table.
for loop = 1, len do
copy[loop] = incoming_table[loop];
end
-- One at a time, choose a random index from Copy to insert in to final table, then remove it from the copy.
local left_to_do = table.maxn(copy);
for loop = 1, len do
local random_index = 1 + TerrainBuilder.GetRandomNumber(left_to_do, "Shuffling table entry - Lua");
table.insert(shuffledVersion, copy[random_index]);
table.remove(copy, random_index);
left_to_do = left_to_do - 1;
end
return shuffledVersion
end
------------------------------------------------------------------------------
function IdentifyTableIndex(incoming_table, value)
-- Purpose of this function is to make it easy to remove a data entry from
-- a list (table) when the index of the entry is unknown.
local bFoundValue = false;
local iNumTimesFoundValue = 0;
local table_of_indices = {};
for loop, test_value in pairs(incoming_table) do
if test_value == value then
bFoundValue = true;
iNumTimesFoundValue = iNumTimesFoundValue + 1;
table.insert(table_of_indices, loop);
end
end
return bFoundValue, iNumTimesFoundValue, table_of_indices;
end
------------------------------------------------------------------------------
function PrintContentsOfTable(incoming_table) -- For debugging purposes. LOT of table data being handled here.
print("--------------------------------------------------");
print("Table printout for table ID:", table);
for index, data in pairs(incoming_table) do
print("Table index:", index, "Table entry:", data);
end
print("- - - - - - - - - - - - - - - - - - - - - - - - - -");
end
function CanPlaceGoodyAt(improvement, plot)
local improvementID = improvement.RowId - 1;
local NO_TEAM = -1;
local NO_RESOURCE = -1;
local NO_IMPROVEMENT = -1;
if (plot:IsWater()) then
return false;
end
if (not ImprovementBuilder.CanHaveImprovement(plot, improvementID, NO_TEAM)) then
return false;
end
if (plot:GetImprovementType() ~= NO_IMPROVEMENT) then
return false;
end
if (plot:GetResourceType() ~= NO_RESOURCE) then
return false;
end
if (plot:IsImpassable()) then
return false;
end
if (plot:IsMountain()) then
return false;
end
-- Don't allow on tiny islands.
-- local numTiles = plot:GetArea().GetPlotCount();
-- if (numTiles < 3) then
-- return false;
-- end
-- Check for being too close to another of this goody type.
local uniqueRange = improvement.GoodyRange;
local plotX = plot:GetX();
local plotY = plot:GetY();
for dx = -uniqueRange, uniqueRange - 1, 1 do
for dy = -uniqueRange, uniqueRange - 1, 1 do
local otherPlot = Map.GetPlotXYWithRangeCheck(plotX, plotY, dx, dy, uniqueRange);
if(otherPlot and otherPlot:GetImprovementType() == improvementID) then
return false;
end
end
end
-- Check for being too close to a civ start.
for dx = -3, 3 do
for dy = -3, 3 do
local otherPlot = Map.GetPlotXYWithRangeCheck(plotX, plotY, dx, dy, 4);
if(otherPlot) then
if otherPlot:IsStartingPlot() then -- Loop through all ever-alive major civs, check if their start plot matches "otherPlot"
for player_num = 0, PlayerManager.GetWasEverAliveCount() - 1 do
local player = Players[player_num];
if player:WasEverAlive() then
-- Need to compare otherPlot with this civ's start plot and return false if a match.
local playerStartPlot = player:GetStartingPlot();
if otherPlot == playerStartPlot then
return false;
end
end
end
end
end
end
end
return true;
end
function AddGoodies(iW, iH)
local NO_PLAYER = -1;
print("-------------------------------");
print("Map Generation - Adding Goodies");
--If advanced setting wants no goodies, don't place any.
local bNoGoodies = GameConfiguration.GetValue("GAME_NO_GOODY_HUTS");
if (bNoGoodies == true) then
print("** The game specified NO GOODY HUTS");
return false;
end
-- Check XML for any and all Improvements flagged as "Goody" and distribute them.
local iImprovements = 0;
local iTiles = 0;
for improvement in GameInfo.Improvements() do
local improvementID = improvement.RowId - 1;
if(improvement.Goody and not (improvement.TilesPerGoody == nil)) then
for x = 0, iW - 1 do
for y = 0, iH - 1 do
local i = y * iW + x;
local pPlot = Map.GetPlotByIndex(i);
local bGoody = CanPlaceGoodyAt(improvement, pPlot);
if (bGoody) then
if (iImprovements == 0 or (improvement.TilesPerGoody < iTiles / iImprovements)) then
local goody_dice = TerrainBuilder.GetRandomNumber(2, "Goody Hut - LUA Goody Hut");
if(goody_dice == 1) then
ImprovementBuilder.SetImprovementType(pPlot, improvementID, NO_PLAYER);
iImprovements = iImprovements + 1;
end
end
end
iTiles = iTiles + 1;
end
end
end
end
print("-------------------------------");
end
|
local MakeGoblinsNeutral = class()
function MakeGoblinsNeutral:initialize()
self._sv.ctx = nil
end
function MakeGoblinsNeutral:restore()
end
function MakeGoblinsNeutral:activate()
if self._sv.ctx then
end
end
--Makes the goblins neutral to everyone
function MakeGoblinsNeutral:start(ctx, data)
self._sv.ctx = ctx
stonehearth.player:set_neutral_to_everyone(ctx.npc_player_id, data.make_neutral)
end
function MakeGoblinsNeutral:get_out_edge(out_edge)
end
return MakeGoblinsNeutral
|
require 'ros-nvim'.setup {
-- path to your catkin workspace
catkin_ws_path = "~/catkin_ws",
-- terminal height for build / test
terminal_height = 8
}
|
local eventtap = require('hs.eventtap')
local events = eventtap.event.types
local modal={}
-- Return an object whose behavior is inspired by hs.hotkey.modal. In this case,
-- the modal state is entered when the specified modifier key is tapped (i.e.,
-- pressed and then released in quick succession).
modal.new = function(modifier)
local instance = {
modifier = modifier,
modalStateTimeoutInSeconds = 1.0,
modalKeybindings = {},
inModalState = false,
reset = function(self)
-- Keep track of the three most recent events.
self.eventHistory = {
-- Serialize the event and push it into the history
push = function(self, event)
self[3] = self[2]
self[2] = self[1]
self[1] = event:asData()
end,
-- Fetch the event (if any) at the given index
fetch = function(self, index)
if self[index] then
return eventtap.event.newEventFromData(self[index])
end
end
}
return self
end,
-- Enable the modal
--
-- Mimics hs.modal:enable()
enable = function(self)
self.watcher:start()
end,
-- Disable the modal
--
-- Mimics hs.modal:disable()
disable = function(self)
self.watcher:stop()
self.watcher:reset()
end,
-- Temporarily enter the modal state in which the modal's hotkeys are
-- active. The modal state will terminate after `modalStateTimeoutInSeconds`
-- or after the first keydown event, whichever comes first.
--
-- Mimics hs.modal.modal:enter()
enter = function(self)
self.inModalState = true
self:entered()
self.autoExitTimer:setNextTrigger(self.modalStateTimeoutInSeconds)
end,
-- Exit the modal state in which the modal's hotkey are active
--
-- Mimics hs.modal.modal:exit()
exit = function(self)
if not self.inModalState then return end
self.autoExitTimer:stop()
self.inModalState = false
self:reset()
self:exited()
end,
-- Optional callback for when modal state is entered
--
-- Mimics hs.modal.modal:entered()
entered = function(self) end,
-- Optional callback for when modal state is exited
--
-- Mimics hs.modal.modal:exited()
exited = function(self) end,
-- Bind hotkey that will be enabled/disabled as modal state is
-- entered/exited
bind = function(self, key, fn)
self.modalKeybindings[key] = fn
end,
}
isNoModifiers = function(flags)
local isFalsey = function(value)
return not value
end
return hs.fnutils.every(flags, isFalsey)
end
isOnlyModifier = function(flags)
isPrimaryModiferDown = flags[modifier]
areOtherModifiersDown = hs.fnutils.some(flags, function(isDown, modifierName)
local isPrimaryModifier = modifierName == modifier
return isDown and not isPrimaryModifier
end)
return isPrimaryModiferDown and not areOtherModifiersDown
end
isFlagsChangedEvent = function(event)
return event and event:getType() == events.flagsChanged
end
isFlagsChangedEventWithNoModifiers = function(event)
return isFlagsChangedEvent(event) and isNoModifiers(event:getFlags())
end
isFlagsChangedEventWithOnlyModifier = function(event)
return isFlagsChangedEvent(event) and isOnlyModifier(event:getFlags())
end
instance.autoExitTimer = hs.timer.new(0, function() instance:exit() end)
instance.watcher = eventtap.new({events.flagsChanged, events.keyDown},
function(event)
-- If we're in the modal state, and we got a keydown event, then trigger
-- the function associated with the key.
if (event:getType() == events.keyDown and instance.inModalState) then
local fn = instance.modalKeybindings[event:getCharacters():lower()]
-- Some actions may take a while to perform (e.g., opening Slack when
-- it's not yet running). We don't want to keep the modal state active
-- while we wait for a long-running action to complete. So, we schedule
-- the action to run in the background so that we can exit the modal
-- state and let the user go on about their business.
local delayInSeconds = 0.001 -- 1 millisecond
hs.timer.doAfter(delayInSeconds, function()
if fn then fn() end
end)
instance:exit()
-- Delete the event so that we're the sole consumer of it
return true
end
-- Otherwise, determine if this event should cause us to enter the modal
-- state.
local currentEvent = event
local lastEvent = instance.eventHistory:fetch(1)
local secondToLastEvent = instance.eventHistory:fetch(2)
instance.eventHistory:push(currentEvent)
-- If we've observed the following sequence of events, then enter the
-- modal state:
--
-- 1. No modifiers are down
-- 2. Modifiers changed, and now only the primary modifier is down
-- 3. Modifiers changed, and now no modifiers are down
if (secondToLastEvent == nil or isNoModifiers(secondToLastEvent:getFlags())) and
isFlagsChangedEventWithOnlyModifier(lastEvent) and
isFlagsChangedEventWithNoModifiers(currentEvent) then
instance:enter()
end
-- Let the event propagate
return false
end
)
return instance:reset()
end
return modal
|
-- BeforeLoadingNextCourseSongMessageCommand
-- StartCommand
-- ChangeCourseSongInMessageCommand
-- ChangeCourseSongOutMessageCommand
-- FinishCommand
local sStage = GAMESTATE:GetCurrentStage();
local tRemap = {
Stage_1st = 1,
Stage_2nd = 2,
Stage_3rd = 3,
Stage_4th = 4,
Stage_5th = 5,
Stage_6th = 6,
};
if tRemap[sStage] == PREFSMAN:GetPreference("SongsPerPlay") then
sStage = "Stage_Final";
else
sStage = sStage;
end;
return Def.ActorFrame {
LoadActor(("failed"))..{
ChangeCourseSongInMessageCommand=cmd(queuecommand,("Play"));
PlayCommand=cmd(play;);
};
LoadActor(THEME:GetPathB("","_doors"), "_newer door", 0.2, true, true );
LoadActor(THEME:GetPathG("","ScreenEvaluation bannerframe (doubleres)"))..{
InitCommand=cmd(CenterX;y,SCREEN_CENTER_Y-124);
ChangeCourseSongInMessageCommand=cmd(zoomy,0;sleep,0.099;sleep,0.396;linear,0.099;zoomy,1;);
FinishCommand=cmd(sleep,2;linear,0.099;zoomy,0);
};
Def.Sprite{
InitCommand=cmd(CenterX;y,SCREEN_CENTER_Y-130;scaletoclipped,256,80);
BeforeLoadingNextCourseSongMessageCommand=function(self)
self:LoadFromSongBanner( SCREENMAN:GetTopScreen():GetNextCourseSong() )
end;
StartCommand=function(self)
self:zoomy(0):sleep(0.099):sleep(0.396):linear(0.099):zoomy(1)
end;
FinishCommand=cmd(sleep,2;linear,0.099;zoomy,0);
};
LoadActor("ScreenStageInformation in/bottom_stage")..{
InitCommand=cmd(CenterX;y,SCREEN_BOTTOM+27);
ChangeCourseSongInMessageCommand=cmd(finishtweening;sleep,0.396;linear,0.198;addy,-54);
FinishCommand=cmd(sleep,2;linear,0.198;addy,54);
};
LoadActor("ScreenStageInformation in/top_stage")..{
InitCommand=cmd(CenterX;y,SCREEN_TOP-66);
ChangeCourseSongInMessageCommand=cmd(finishtweening;sleep,0.396;linear,0.198;addy,104);
FinishCommand=cmd(sleep,2;linear,0.198;addy,-104);
};
LoadActor( THEME:GetPathG("_Stages/ScreenStageInformation", "Stage " .. ToEnumShortString(sStage) ) ) .. {
InitCommand=cmd(x,SCREEN_CENTER_X;y,SCREEN_CENTER_Y);
ChangeCourseSongInMessageCommand=cmd(diffusealpha,0;sleep,0.396;diffusealpha,1);
FinishCommand=cmd(sleep,2;diffusealpha,0);
};
-- Ready
LoadActor(THEME:GetPathB("ScreenGameplay","ready/ready")) .. {
InitCommand=cmd(x,SCREEN_CENTER_X;y,SCREEN_CENTER_Y;diffusealpha,0);
ChangeCourseSongInMessageCommand=cmd(diffusealpha,0;);
FinishCommand = cmd(sleep,2.2;diffusealpha,0;zoomx,4;zoomy,0;accelerate,0.09;zoomx,1;zoomy,1;diffusealpha,1;sleep,1;accelerate,0.132;zoomx,4;zoomy,0;diffusealpha,0);
};
--go
LoadActor(THEME:GetPathB("ScreenGameplay","go/go")) .. {
InitCommand=cmd(x,SCREEN_CENTER_X;y,SCREEN_CENTER_Y;diffusealpha,0);
ChangeCourseSongInMessageCommand=cmd(diffusealpha,0;);
FinishCommand = cmd(sleep,3.5;diffusealpha,0;zoomx,4;zoomy,0;accelerate,0.132;zoomx,1;zoomy,1;diffusealpha,1;sleep,1;accelerate,0.132;zoomx,4;zoomy,0;diffusealpha,0);
};
};
|
local CONF = require "conf"
local world_mod = require "src.world"
local Input = require "src.input"
local Gen = require "src.genetics"
require "src.data"
local Trainer = (require "src.trainer").Trainer
local Stats = (require "src.stats").Stats
local World = world_mod.World
local Wall = world_mod.Wall
local Population = Gen.Population
local world
local input
local pop
local trainer
local pop_stats
local gen_stats
local ui_font
local fitness_font
function love.load()
math.randomseed(os.time())
world = World.new()
local wall1 = Wall.new(-20, -20, 840, 20)
local wall2 = Wall.new(-20, 600, 840, 20)
local wall3 = Wall.new(-20, 0, 20, 600)
local wall4 = Wall.new(800, 0, 20, 600)
world:add_entity(wall1)
world:add_entity(wall2)
world:add_entity(wall3)
world:add_entity(wall4)
input = Input:new()
if CONF.LOAD_FILE == "" then
pop = Population.new()
pop:create_genomes(CONF.POPULATION_SIZE, 16, 8)
else
pop = Population.load(CONF.LOAD_FILE)
end
pop_stats = Stats.new()
gen_stats = Stats.new()
trainer = Trainer.new(pop, world, input)
trainer:initialize_training()
love.graphics.setBackgroundColor(CONF.BACK_COLOR)
ui_font = love.graphics.newFont(24)
fitness_font = love.graphics.newFont(32)
end
function love.keypressed(key)
input:keydown(key)
end
function love.keyreleased(key)
input:keyup(key)
end
function love.update(dt)
if love.keyboard.isDown "escape" then
love.event.quit()
end
if love.keyboard.isDown "z" then
trainer:change_speed(-1)
end
if love.keyboard.isDown "x" then
trainer:change_speed(1)
end
trainer:update(dt, pop_stats, gen_stats)
--world:update(dt, input)
end
local function plot_fitness(x, y, scale)
love.graphics.push()
love.graphics.translate(x, y)
love.graphics.scale(scale, scale)
love.graphics.setColor(0, 0, 0, 0.4)
love.graphics.rectangle("fill", -20, -20, 680, 340)
love.graphics.setFont(fitness_font)
love.graphics.setColor(CONF.FONT_COLOR)
love.graphics.printf("Average fitness: " .. math.floor(pop.avg_fitness), 0, 0, 640, "left")
love.graphics.printf("Highest fitness: " .. math.floor(pop.high_fitness), 0, 32, 640, "left")
local points = pop_stats:get_points(0, 120, 640, 200)
love.graphics.setColor(0, 0, 1)
for _, v in ipairs(points) do
love.graphics.circle("fill", v[1], v[2], 8)
end
love.graphics.pop()
end
local function plot_generation(x, y, scale)
love.graphics.push()
love.graphics.translate(x, y)
love.graphics.scale(scale, scale)
love.graphics.setColor(0, 0, 0, 0.4)
love.graphics.rectangle("fill", -20, -20, 680, 340)
love.graphics.setFont(fitness_font)
love.graphics.setColor(CONF.FONT_COLOR)
love.graphics.printf("Fitness over Genome", 0, 0, 640, "left")
local points = gen_stats:get_points(0, 60, 640, 260)
love.graphics.setColor(1, 0, 0)
for _, v in ipairs(points) do
love.graphics.circle("fill", v[1], v[2], 8)
end
love.graphics.pop()
end
local function draw_network(net, x, y, scale)
if net == nil then return end
love.graphics.push()
love.graphics.translate(x, y)
love.graphics.scale(scale, scale)
love.graphics.setColor(0, 0, 0, 0.4)
love.graphics.rectangle("fill", -20, -20, 680, 600)
for _, v in pairs(net.neurons) do
local c = v.value
local r = c < 0 and -c or 0
local b = c > 0 and c or 0
local g = 0
if v.value == 0 then
r = 0.3
g = 0.3
b = 0.3
end
love.graphics.setColor(r, g, b)
love.graphics.rectangle("fill", v.x, v.y, 24, 24)
end
for _, neuron in pairs(net.neurons) do
local ins = neuron.inputs
local x1 = neuron.x + 12
local y1 = neuron.y + 12
for _, conn in pairs(ins) do
local other = net.neurons[conn.from]
local x2 = other.x + 12
local y2 = other.y + 12
local col = { 1, 0, 0 }
if conn.weight * other.value> 0 then
col = { 0, 0, 1 }
end
local mag = math.abs(other.value)
col[1] = col[1] * mag
col[2] = col[2] * mag
col[3] = col[3] * mag
love.graphics.setColor(col)
love.graphics.setLineWidth(math.sigmoid(conn.weight) * 2)
love.graphics.line(x1, y1, x2, y2)
end
end
love.graphics.setLineWidth(2)
love.graphics.pop()
end
function love.draw()
love.graphics.setScissor(0, 0, 820, 620)
world:draw()
love.graphics.setScissor()
love.graphics.setColor(CONF.FONT_COLOR)
love.graphics.setFont(ui_font)
love.graphics.printf(tostring(love.timer.getFPS()) .. " FPS", 16, 640, 800, "left")
love.graphics.printf("Generation: " .. pop.generation, 16, 640 + 32, 800, "left")
love.graphics.printf("Genome: " .. pop.current_genome, 16, 640 + 64, 800, "left")
if pop.genomes[pop.current_genome] ~= nil then
love.graphics.printf("Fitness: " .. math.floor(pop.genomes[pop.current_genome].fitness), 16, 640 + 96, 800, "left")
draw_network(pop.genomes[pop.current_genome].network, 1200 - 350, 32, 1 / 2)
end
plot_fitness(1200 - 350, 352, 1 / 2)
plot_generation(1200 - 350, 600, 1 / 2)
end
|
RegisterNetEvent("FRP:ME:DisplayAboveHeadText")
AddEventHandler(
"FRP:ME:DisplayAboveHeadText",
function(text, targetServerId)
local playerPed = PlayerPedId()
local targetPlayerPed = GetPlayerPed(GetPlayerFromServerId(targetServerId))
if DoesEntityExist(targetPlayerPed) then
local dist = #(GetEntityCoords(playerPed) - GetEntityCoords(targetPlayerPed))
if dist <= 100.0 then
local shouldDisplay = true
Citizen.CreateThread(
function()
Citizen.Wait(7000)
shouldDisplay = false
end
)
Citizen.CreateThread(
function()
while shouldDisplay do
Citizen.Wait(0)
targetPlayerPed = GetPlayerPed(targetPlayer)
if DoesEntityExist(targetPlayerPed) then
local bonePosition = GetPedBoneCoords(targetPlayerPed, 21030, 0, 0, 0)
DrawText3D(bonePosition.x, bonePosition.y, bonePosition.z + 0.30, text)
else
break
end
end
end
)
end
end
end
)
function DrawText3D(x, y, z, text)
local onScreen, _x, _y = GetScreenCoordFromWorldCoord(x, y, z)
local px, py, pz = table.unpack(GetGameplayCamCoord())
local dist = GetDistanceBetweenCoords(px, py, pz, x, y, z, 1)
local str = CreateVarString(10, "LITERAL_STRING", text, Citizen.ResultAsLong())
if onScreen then
SetTextScale(0.25, 0.25)
SetTextFontForCurrentCommand(1)
SetTextColor(255, 255, 255, 215)
SetTextCentre(1)
-- shouldDisplayText(str, _x, _y)
local factor = (string.len(text)) / 225
--DrawSprite("feeds", "hud_menu_4a", _x, _y+0.0125,0.015+ factor, 0.03, 0.1, 35, 35, 35, 190, 0)
DrawSprite("feeds", "toast_bg", _x, _y + 0.0125, 0.015 + factor, 0.03, 0.1, 100, 1, 1, 190, 0)
end
end
|
--
-- (C) 2015 Kriss@XIXs.com
--
local coroutine,package,string,table,math,io,os,debug,assert,dofile,error,_G,getfenv,getmetatable,ipairs,load,loadfile,loadstring,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,_VERSION,xpcall,module,require=coroutine,package,string,table,math,io,os,debug,assert,dofile,error,_G,getfenv,getmetatable,ipairs,load,loadfile,loadstring,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,_VERSION,xpcall,module,require
local wgrd=require('wetgenes.grd')
local wpack=require("wetgenes.pack")
local wzips=require("wetgenes.zips")
--module
local M={ modname=(...) } ; package.loaded[M.modname]=M
function M.bake(oven,wtiles)
wtiles=wtiles or {}
local gl=oven.gl
local cake=oven.cake
local canvas=cake.canvas
local flat=canvas.flat
wtiles.loads=function()
local filename="lua/"..(M.modname):gsub("%.","/")..".glsl"
gl.shader_sources( assert(wzips.readfile(filename),"file not found: "..filename) , filename )
local bfontgrd=require("wetgenes.gamecake.fun.bitdown_font").build_grd(8,16,"r")
local g=wgrd.create(wgrd.FMT_U8_RGBA_PREMULT,8*256,16*1,1)
for i=0,255 do -- setup base textures for 7bit ascii
local dx=math.floor((i)%256)*8
local dy=math.floor((i)/256)*16
g:pixels(dx,dy,8,16,bfontgrd:pixels(i*8,0,8,16,"")) -- splat into grid
end
wtiles.grdfont8x16=g
return wtiles
end
function wtiles.update(widget)
-- if widget.data then
-- widget.text=widget.data.str
-- end
return widget.meta.update(widget)
end
--function wtiles.draw(widget)
-- return widget.meta.draw(widget)
--end
function wtiles.render_lines(widget,lines)
local g=widget.tilemap_grd
g:clear(widget.background_tile or 0x00000000)
for i,v in ipairs(lines) do
local s=v.s
if s then
g:pixels(0,i-1,#s/4,1,s)
end
end
end
function wtiles.skin(widget)
wtiles.render_lines(widget,widget.lines or {} )
local x,y,hx,hy=widget.px,widget.py,widget.hx,widget.hy -- it.window_px+dl.dx , it.window_py+dl.dy , it.window_hx , it.window_hy
local u,v,hu,hv=0,0,hx/8,hy/16 -- it.px/it.tile_hx , it.py/it.tile_hy , hx/it.tile_hx , hy/it.tile_hy
local ta=gl.apply_modelview( {x ,y+hy ,0,1} )
local tb=gl.apply_modelview( {x ,y ,0,1} )
local tc=gl.apply_modelview( {x+hx ,y+hy ,0,1} )
local td=gl.apply_modelview( {x+hx ,y ,0,1} )
local t={
ta[1], ta[2], ta[3], u, v+hv,
tb[1], tb[2], tb[3], u, v,
tc[1], tc[2], tc[3], u+hu, v+hv,
td[1], td[2], td[3], u+hu, v,
}
return function()
--print("FONt DRAW")
--font
gl.BindTexture( gl.TEXTURE_2D , widget.bitmap_tex )
gl.TexImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
wtiles.grdfont8x16.width,
wtiles.grdfont8x16.height,
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
wtiles.grdfont8x16.data )
--display
gl.BindTexture( gl.TEXTURE_2D , widget.tilemap_tex )
gl.TexImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
widget.tilemap_grd.width,
widget.tilemap_grd.height,
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
widget.tilemap_grd.data )
--colors
gl.BindTexture( gl.TEXTURE_2D , widget.colormap_tex )
gl.TexImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
256,
1,
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
widget.colormap_grd.data )
gl.Color(1,1,1,1)
-- local dl={ color={1,1,1,1} , dx=0 , dy=0 }
flat.tristrip("rawuv",t,"widget_draw_texteditor_tilemap",function(p)
-- gl.Uniform2f( p:uniform("projection_zxy"), it.screen.zx,it.screen.zy)
gl.ActiveTexture( gl.TEXTURE0 + gl.NEXT_UNIFORM_TEXTURE )
gl.Uniform1i( p:uniform("tex_tile"), gl.NEXT_UNIFORM_TEXTURE )
gl.BindTexture( gl.TEXTURE_2D , widget.bitmap_tex )
gl.NEXT_UNIFORM_TEXTURE=gl.NEXT_UNIFORM_TEXTURE+1
gl.ActiveTexture( gl.TEXTURE0 + gl.NEXT_UNIFORM_TEXTURE )
gl.Uniform1i( p:uniform("tex_map"), gl.NEXT_UNIFORM_TEXTURE )
gl.BindTexture( gl.TEXTURE_2D , widget.tilemap_tex )
gl.NEXT_UNIFORM_TEXTURE=gl.NEXT_UNIFORM_TEXTURE+1
gl.ActiveTexture( gl.TEXTURE0 + gl.NEXT_UNIFORM_TEXTURE )
gl.Uniform1i( p:uniform("tex_cmap"), gl.NEXT_UNIFORM_TEXTURE )
gl.BindTexture( gl.TEXTURE_2D , widget.colormap_tex )
gl.NEXT_UNIFORM_TEXTURE=gl.NEXT_UNIFORM_TEXTURE+1
gl.ActiveTexture( gl.TEXTURE0 )
gl.Uniform4f( p:uniform("tile_info"), 8,
16,
256*8,
1*16 )
gl.Uniform4f( p:uniform("map_info"), 0,0,512,256 )
--[[
for i,v in ipairs{
0xff336622, 0xff66aa33, 0xff66cccc, 0xff5577cc,
0xff333366, 0xff442233, 0xff884433, 0xffeeaa99,
0xffcc3333, 0xffdd7733, 0xffdddd44, 0xff000000,
0xff444444, 0xff666666, 0xffaaaaaa, 0xffffffff,
} do
local n=("0123456789ABCDEF"):sub(i,i)
gl.Uniform4f( p:uniform("colors_"..n), gl.C8(v) )
end
]]
end)
end
end
function wtiles.setup(widget,def)
-- local it={}
-- widget.button=it
widget.class="tiles"
widget.pan_px=0
widget.pan_py=0
widget.hx_max=widget.hx
widget.hy_max=widget.hy
widget.key=wtiles.key
widget.mouse=wtiles.mouse
widget.update=wtiles.update
widget.draw=wtiles.draw
widget.skin=wtiles.skin
widget.color=widget.color or 0 -- presume we want to be visible
widget.bitmap_tex=gl.GenTexture()
widget.tilemap_tex=gl.GenTexture()
widget.colormap_tex=gl.GenTexture()
gl.BindTexture( gl.TEXTURE_2D , widget.bitmap_tex )
gl.TexParameter(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST)
gl.TexParameter(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST)
gl.TexParameter(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
gl.TexParameter(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
gl.BindTexture( gl.TEXTURE_2D , widget.tilemap_tex )
gl.TexParameter(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST)
gl.TexParameter(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST)
gl.TexParameter(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
gl.TexParameter(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
gl.BindTexture( gl.TEXTURE_2D , widget.colormap_tex )
gl.TexParameter(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST)
gl.TexParameter(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST)
gl.TexParameter(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
gl.TexParameter(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
widget.lines={}
widget.tilemap_grd=wgrd.create(wgrd.FMT_U8_RGBA,512,256,1)
widget.colormap_grd=wgrd.create(wgrd.FMT_U8_RGBA,256,1,1)
widget.colormap_grd:pixels(0,0,256,1,require("wetgenes.gamecake.fun.bitdown").cmap_swanky32.grd) -- copy swanky32
return widget
end
return wtiles
end
|
erratic_swirl_prong = Creature:new {
objectName = "@mob/creature_names:erratic_swirl_prong",
socialGroup = "prong",
faction = "",
level = 27,
chanceHit = 0.36,
damageMin = 240,
damageMax = 250,
baseXp = 2730,
baseHAM = 7200,
baseHAMmax = 8800,
armor = 0,
resists = {125,135,15,150,150,-1,-1,-1,-1},
meatType = "meat_herbivore",
meatAmount = 150,
hideType = "hide_leathery",
hideAmount = 110,
boneType = "bone_mammal",
boneAmount = 95,
milk = 0,
tamingChance = 0.25,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + HERD,
optionsBitmask = AIENABLED,
diet = HERBIVORE,
templates = {"object/mobile/swirl_prong_hue.iff"},
hues = { 8, 9, 10, 11, 12, 13, 14, 15 },
scale = 1.05,
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {
{"posturedownattack",""},
{"intimidationattack",""}
}
}
CreatureTemplates:addCreatureTemplate(erratic_swirl_prong, "erratic_swirl_prong")
|
--- /$$$$$$$ /$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$$
---| $$__ $$ /$$__ $$ /$$__ $$| $$ | $$ /$$__ $$| $$__ $$
---| $$ \ $$| $$ \__/ | $$ \__/| $$ | $$| $$ \ $$| $$ \ $$
---| $$ | $$| $$ | $$$$$$ | $$$$$$$$| $$ | $$| $$$$$$$/
---| $$ | $$| $$ \____ $$| $$__ $$| $$ | $$| $$____/
---| $$ | $$| $$ $$ /$$ \ $$| $$ | $$| $$ | $$| $$
---| $$$$$$$/| $$$$$$/ | $$$$$$/| $$ | $$| $$$$$$/| $$
---|_______/ \______/ /$$$$$$ \______/ |__/ |__/ \______/ |__/
--- |______/
Config = {}
-- Configuracion de las ubicacion del coche
Config.coche = {
["cogercoche"] = {
coords = vector3(164.3442, -886.853, 30.499),
},
["spawn"] = {
coords = vector3(160.2872, -891.059, 30.306),
},
["llevar"] = {
coords = vector3(95.67826, -976.490, 29.314),
},
}
-- Configuracion del dinero que da por coche entregado
Config.money = {
["max"] = 10000,
["min"] = 5000,
}
|
local objects =
{
--Maxime
createObject(8231,554.7999900,2645.1001000,10.0000000,0.0000000,0.0000000,0.0000000,10), --object(vgsbikeschl05,10), (1,10),
createObject(8231,559.2999900,2653.3999000,10.0000000,0.0000000,0.0000000,270.0000000,10), --object(vgsbikeschl05,10), (2,10),
createObject(6037,532.5996100,2635.5000000,-1.4000000,90.0000000,0.0000000,179.9950000,10), --object(filler02_law,10), (1,10),
createObject(1745,553.4000200,2640.1001000,8.3000000,0.0000000,0.0000000,270.0000000,10), --object(med_bed_3,10), (1,10),
createObject(1726,557.7000100,2637.6999500,8.3000000,0.0000000,0.0000000,90.0000000,10), --object(mrk_seating2,10), (1,10),
createObject(8231,548.4600200,2628.5000000,10.0000000,0.0000000,0.0000000,90.0000000,10), --object(vgsbikeschl05,10), (3,10),
createObject(2297,563.5000000,2639.3994100,8.3000000,0.0000000,0.0000000,225.0000000,10), --object(tv_unit_2,10), (1,10),
createObject(2229,563.4000200,2636.6999500,8.3000000,0.0000000,0.0000000,255.0000000,10), --object(swank_speaker,10), (1,10),
createObject(1742,560.5999800,2636.5300300,8.3000000,0.0000000,0.0000000,180.0000000,10), --object(med_bookshelf,10), (1,10),
createObject(2141,560.2000100,2644.0000000,8.3000000,0.0000000,0.0000000,0.0000000,10), --object(cj_kitch2_l,10), (1,10),
createObject(2341,563.1992200,2644.0000000,8.3000000,0.0000000,0.0000000,0.0000000,10), --object(cj_kitch2_corner,10), (1,10),
createObject(2133,563.2001300,2643.0400400,8.3000000,0.0000000,0.0000000,270.0000000,10), --object(cj_kitch2_r,10), (2,10),
createObject(15038,553.0000000,2643.8999000,8.9000000,0.0000000,0.0000000,0.0000000,10), --object(plant_pot_3_sv,10), (1,10),
createObject(14762,552.5999800,2638.8999000,10.2000000,0.0000000,0.0000000,0.0000000,10), --object(arsewinows,10), (1,10),
createObject(2596,552.7998000,2637.5000000,10.5000000,10.9970000,358.9950000,129.9960000,10), --object(cj_sex_tv,10), (1,10),
createObject(2132,561.2000100,2644.0000000,8.3000000,0.0000000,0.0000000,0.0000000,10), --object(cj_kitch2_sink,10), (1,10),
createObject(1536,563.7000100,2640.6001000,8.3000000,0.0000000,0.0000000,90.0000000,10), --object(gen_doorext15,10), (1,10),
createObject(3440,553.0000000,2643.9394500,6.2200000,0.0000000,0.0000000,0.0000000,10), --object(arptpillar01_lvs,10), (1,10),
createObject(6037,550.7000100,2646.5000000,-1.4000000,90.0000000,0.0000000,90.0000000,10), --object(filler02_law,10), (2,10),
createObject(6037,550.7000100,2646.3999000,-1.4000000,90.0000000,0.0000000,0.0000000,10), --object(filler02_law,10), (3,10),
createObject(3942,553.0000000,2636.6999500,16.4440000,0.0000000,0.0000000,0.0000000,10), --object(bistrobar,10), (2,10),
createObject(2262,557.5999800,2638.0000000,10.1000000,0.0000000,0.0000000,90.0000000,10), --object(frame_slim_3,10), (1,10),
createObject(948,557.5999800,2640.5000000,8.3000000,0.0000000,0.0000000,0.0000000,10), --object(plant_pot_10,10), (1,10),
createObject(2261,557.6008900,2639.5000000,10.0000000,0.0000000,0.0000000,90.0000000,10), --object(frame_slim_2,10), (1,10),
createObject(2239,554.7999900,2644.1999500,8.3000000,0.0000000,0.0000000,0.0000000,10), --object(cj_mlight16,10), (1,10),
createObject(6037,538.0000000,2646.8999000,-1.4000000,90.0000000,0.0000000,90.0000000,10), --object(filler02_law,10), (4,10),
}
local col = createColSphere(563.11963, 2641.35791, 9.29688 , 20)
local function watchChanges( )
if getElementDimension( getLocalPlayer( ) ) > 0 and getElementDimension( getLocalPlayer( ) ) ~= getElementDimension( objects[1] ) and getElementInterior( getLocalPlayer( ) ) == getElementInterior( objects[1] ) then
for key, value in pairs( objects ) do
setElementDimension( value, getElementDimension( getLocalPlayer( ) ) )
end
elseif getElementDimension( getLocalPlayer( ) ) == 0 and getElementDimension( objects[1] ) ~= 65535 then
for key, value in pairs( objects ) do
setElementDimension( value, 65535 )
end
end
end
addEventHandler( "onClientColShapeHit", col,
function( element )
if element == getLocalPlayer( ) then
addEventHandler( "onClientRender", root, watchChanges )
end
end
)
addEventHandler( "onClientColShapeLeave", col,
function( element )
if element == getLocalPlayer( ) then
removeEventHandler( "onClientRender", root, watchChanges )
end
end
)
-- Put them standby for now.
for key, value in pairs( objects ) do
setElementDimension( value, 65535 )
end
for index, object in ipairs ( objects ) do
setElementDoubleSided ( object, true )
--setElementCollisionsEnabled ( object, true )
end
|
-- © 2008-2013 David Given.
-- WordGrinder is licensed under the MIT open source license. See the COPYING
-- file in this distribution for the full text.
local ITALIC = wg.ITALIC
local UNDERLINE = wg.UNDERLINE
local BOLD = wg.BOLD
local ParseWord = wg.parseword
local WriteU8 = wg.writeu8
local bitand = bit32.band
local bitor = bit32.bor
local bitxor = bit32.bxor
local bit = bit32.btest
local string_char = string.char
local string_find = string.find
local string_sub = string.sub
local table_concat = table.concat
-----------------------------------------------------------------------------
-- The importer itself.
function Cmd.ImportHTMLFileFromStream(fp)
local data = fp:read("*a")
-- Collapse whitespace; this makes things far easier to parse.
data = data:gsub("[\t\f]", " ")
data = data:gsub("\r\n", "\n")
-- Canonicalise the string, making it valid UTF-8.
data = CanonicaliseString(data)
-- Collapse complex elements.
data = data:gsub("< ?(%w+) ?[^>]*(/?)>", "<%1%2>")
-- Helper function for reading tokens from the HTML stream.
local pos = 1
local len = data:len()
local function tokens()
if (pos >= len) then
return nil
end
local s, e, t
s, e, t = string_find(data, "^([ \n])", pos)
if s then pos = e+1 return t end
if string_find(data, "^%c") then
pos = pos + 1
return tokens()
end
s, e, t = string_find(data, "^(<[^>]*>)", pos)
if s then pos = e+1 return t:lower() end
s, e, t = string_find(data, "^(&[^;]-;)", pos)
if s then pos = e+1 return t end
s, e, t = string_find(data, "^([^ <&\n]+)", pos)
if s then pos = e+1 return t end
t = string_sub(data, pos, pos+1)
pos = pos + 1
return t
end
-- Skip tokens until we hit a <body>.
for t in tokens do
if (t == "<body>") then
break
end
end
-- Define the element look-up table.
local document = CreateDocument()
local importer = CreateImporter(document)
local style = "P"
local liststyle = "LB"
local pre = false
local function flush()
importer:flushparagraph(style)
style = "P"
end
local function flushword()
importer:flushword(pre)
end
local function flushpre()
flush()
if pre then
style = "PRE"
end
end
local elements =
{
[" "] = flushword,
["<p>"] = flush,
["<br>"] = flushpre,
["<br/>"] = flushpre,
["</h1>"] = flush,
["</h2>"] = flush,
["</h3>"] = flush,
["</h4>"] = flush,
["<h1>"] = function() flush() style = "H1" end,
["<h2>"] = function() flush() style = "H2" end,
["<h3>"] = function() flush() style = "H3" end,
["<h4>"] = function() flush() style = "H4" end,
["<ol>"] = function() liststyle = "LN" end,
["<ul>"] = function() liststyle = "LB" end,
["<li>"] = function() flush() style = liststyle end,
["<i>"] = function() importer:style_on(ITALIC) end,
["</i>"] = function() importer:style_off(ITALIC) end,
["<em>"] = function() importer:style_on(ITALIC) end,
["</em>"] = function() importer:style_off(ITALIC) end,
["<u>"] = function() importer:style_on(UNDERLINE) end,
["</u>"] = function() importer:style_off(UNDERLINE) end,
["<b>"] = function() importer:style_on(BOLD) end,
["</b>"] = function() importer:style_off(BOLD) end,
["<pre>"] = function() flush() style = "PRE" pre = true end,
["</pre>"] = function() flush() pre = false end,
["\n"] = function() if pre then flush() style = "PRE" else flushword() end end
}
-- Actually do the parsing.
importer:reset()
for t in tokens do
local e = elements[t]
if e then
e()
elseif string_find(t, "^<") then
-- do nothing
elseif string_find(t, "^&") then
e = DecodeHTMLEntity(t)
if e then
importer:text(e)
end
else
importer:text(t)
end
end
flush()
-- Remove the blank paragraph at the beginning of the document.
if (#document > 1) then
document:deleteParagraphAt(1)
end
return document
end
function Cmd.ImportHTMLFile(filename)
return ImportFileWithUI(filename, "Import HTML File", Cmd.ImportHTMLFileFromStream)
end
|
assert(Skada, "Skada not found!")
local CCSpells = {
[118] = true, -- Polymorph (rank 1)
[12824] = true, -- Polymorph (rank 2)
[12825] = true, -- Polymorph (rank 3)
[12826] = true, -- Polymorph (rank 4)
[28272] = true, -- Polymorph (rank 1:pig)
[28271] = true, -- Polymorph (rank 1:turtle)
[3355] = 16, -- Freezing Trap Effect (rank 1)
[14308] = 16, -- Freezing Trap Effect (rank 2)
[14309] = 16, -- Freezing Trap Effect (rank 3)
[6770] = 1, -- Sap (rank 1)
[2070] = 1, -- Sap (rank 2)
[11297] = 1, -- Sap (rank 3)
[6358] = 32, -- Seduction (succubus)
[60210] = 16, -- Freezing Arrow (rank 1)
[45524] = 16, -- Chains of Ice
[33786] = 8, -- Cyclone
[53308] = 8, -- Entangling Roots
[2637] = 8, -- Hibernate (rank 1)
[18657] = 8, -- Hibernate (rank 2)
[18658] = 8, -- Hibernate (rank 3)
[20066] = 2, -- Repentance
[9484] = 2, -- Shackle Undead (rank 1)
[9485] = 2, -- Shackle Undead (rank 2)
[10955] = 2, -- Shackle Undead (rank 3)
[51722] = 1, -- Dismantle
[710] = 32, -- Banish (Rank 1)
[18647] = 32, -- Banish (Rank 2)
[12809] = 1, -- Concussion Blow
[676] = 1 -- Disarm
}
-- extended CC list for only CC Done and CC Taken modules
local ExtraCCSpells = {
-- Death Knight
[47476] = 32, -- Strangulate
[49203] = 16, -- Hungering Cold
[47481] = 1, -- Gnaw
[49560] = 1, -- Death Grip
-- Druid
[339] = 8, -- Entangling Roots (rank 1)
[1062] = 8, -- Entangling Roots (rank 2)
[5195] = 8, -- Entangling Roots (rank 3)
[5196] = 8, -- Entangling Roots (rank 4)
[9852] = 8, -- Entangling Roots (rank 5)
[9853] = 8, -- Entangling Roots (rank 6)
[26989] = 8, -- Entangling Roots (rank 7)
[19975] = 8, -- Entangling Roots (Nature's Grasp rank 1)
[19974] = 8, -- Entangling Roots (Nature's Grasp rank 2)
[19973] = 8, -- Entangling Roots (Nature's Grasp rank 3)
[19972] = 8, -- Entangling Roots (Nature's Grasp rank 4)
[19971] = 8, -- Entangling Roots (Nature's Grasp rank 5)
[19970] = 8, -- Entangling Roots (Nature's Grasp rank 6)
[27010] = 8, -- Entangling Roots (Nature's Grasp rank 7)
[53313] = 8, -- Entangling Roots (Nature's Grasp)
[66070] = 8, -- Entangling Roots (Force of Nature)
[8983] = 1, -- Bash
[16979] = 1, -- Feral Charge - Bear
[45334] = 1, -- Feral Charge Effect
[22570] = 1, -- Maim (rank 1)
[49802] = 1, -- Maim (rank 2)
[49803] = 1, -- Pounce
-- Hunter
[19503] = 1, -- Scatter Shot
[19386] = 8, -- Wyvern Sting (rank 1)
[24132] = 8, -- Wyvern Sting (rank 2)
[24133] = 8, -- Wyvern Sting (rank 3)
[27068] = 8, -- Wyvern Sting (rank 4)
[49011] = 8, -- Wyvern Sting (rank 5)
[49012] = 8, -- Wyvern Sting (rank 6)
[53548] = 1, -- Pin (Crab)
[4167] = 1, -- Web (Spider)
[55509] = 8, -- Venom Web Spray (Silithid)
[24394] = 1, -- Intimidation
[19577] = 8, -- Intimidation (stun)
[53568] = 8, -- Sonic Blast (Bat)
[53543] = 1, -- Snatch (Bird of Prey)
[50541] = 1, -- Clench (Scorpid)
[55492] = true, -- Froststorm Breath (Chimaera)
[26090] = 8, -- Pummel (Gorilla)
[53575] = 1, -- Tendon Rip (Hyena)
[53589] = 32, -- Nether Shock (Nether Ray)
[53562] = 1, -- Ravage (Ravager)
[1513] = 8, -- Scare Beast
[64803] = 1, -- Entrapment
-- Mage
[61305] = true, -- Polymorph Cat
[61721] = true, -- Polymorph Rabbit
[61780] = true, -- Polymorph Turkey
[31661] = true, -- Dragon's Breath
[44572] = 16, -- Deep Freeze
[122] = 16, -- Frost Nova (rank 1)
[865] = 16, -- Frost Nova (rank 2)
[6131] = 16, -- Frost Nova (rank 3)
[10230] = 16, -- Frost Nova (rank 4)
[27088] = 16, -- Frost Nova (rank 5)
[42917] = 16, -- Frost Nova (rank 6)
[33395] = 33395, -- Freeze (Frost Water Elemental)
[55021] = true, -- Silenced - Improved Counterspell
-- Paladin
[853] = 2, -- Hammer of Justice (rank 1)
[5588] = 2, -- Hammer of Justice (rank 2)
[5589] = 2, -- Hammer of Justice (rank 3)
[10308] = 2, -- Hammer of Justice (rank 4)
[10326] = 2, -- Turn Evil
[2812] = 2, -- Holy Wrath (rank 1)
[10318] = 2, -- Holy Wrath (rank 2)
[27319] = 2, -- Holy Wrath (rank 3)
[48816] = 2, -- Holy Wrath (rank 4)
[48817] = 2, -- Holy Wrath (rank 5)
[31935] = 2, -- Avengers Shield
-- Priest
[8122] = 32, -- Psychic Scream (rank 1)
[8124] = 32, -- Psychic Scream (rank 2)
[10888] = 32, -- Psychic Scream (rank 3)
[10890] = 32, -- Psychic Scream (rank 4)
[605] = 32, -- Dominate Mind (Mind Control)
[15487] = 32, -- Silence
[64044] = 32, -- Psychic Horror
-- Rogue
[51724] = 1, -- Sap
[408] = 1, -- Kidney Shot (rank 1)
[8643] = 1, -- Kidney Shot (rank 2)
[2094] = 1, -- Blind
[1833] = 1, -- Cheap Shot
[1776] = 1, -- Gouge
[1330] = 1, -- Garrote - Silence
-- Shaman
[51514] = 8, -- Hex
[8056] = 16, -- Frost Shock (rank 1)
[8058] = 16, -- Frost Shock (rank 2)
[10472] = 16, -- Frost Shock (rank 3)
[10473] = 16, -- Frost Shock (rank 4)
[25464] = 16, -- Frost Shock (rank 5)
[49235] = 16, -- Frost Shock (rank 6)
[49236] = 16, -- Frost Shock (rank 7)
[64695] = 8, -- Earthgrab (Earthbind Totem with Storm, Earth and Fire talent)
[3600] = 8, -- Earthbind (Earthbind Totem)
[39796] = 1, -- Stoneclaw Stun (Stoneclaw Totem)
[8034] = 16, -- Frostbrand Weapon (rank 1)
[8037] = 16, -- Frostbrand Weapon (rank 2)
[10458] = 16, -- Frostbrand Weapon (rank 3)
[16352] = 16, -- Frostbrand Weapon (rank 4)
[16353] = 16, -- Frostbrand Weapon (rank 5)
[25501] = 16, -- Frostbrand Weapon (rank 6)
[58797] = 16, -- Frostbrand Weapon (rank 7)
[58798] = 16, -- Frostbrand Weapon (rank 8)
[58799] = 16, -- Frostbrand Weapon (rank 9)
-- Warlock
[6215] = 32, -- Fear
[5484] = 32, -- Howl of Terror
[30283] = 32, -- Shadowfury
[22703] = 4, -- Infernal Awakening
[6789] = 32, -- Death Coil (rank 1)
[17925] = 32, -- Death Coil (rank 2)
[17926] = 32, -- Death Coil (rank 3)
[27223] = 32, -- Death Coil (rank 4)
[47859] = 32, -- Death Coil (rank 5)
[47860] = 32, -- Death Coil (rank 6)
[24259] = 32, -- Spell Lock
-- Warrior
[5246] = 1, -- Initmidating Shout
[46968] = 1, -- Shockwave
[6552] = 1, -- Pummel
[58357] = 1, -- Heroic Throw silence
[7922] = 1, -- Charge
[47995] = 1, -- Intercept (Stun)--needs review
[12323] = 1, -- Piercing Howl
-- Racials
[20549] = 1, -- War Stomp (Tauren)
[28730] = true, -- Arcane Torrent (Bloodelf)
[47779] = true, -- Arcane Torrent (Bloodelf)
[50613] = true, -- Arcane Torrent (Bloodelf)
-- Engineering
[67890] = 4 -- Cobalt Frag Bomb
}
local pairs, ipairs, select = pairs, ipairs, select
local tostring, format = tostring, string.format
local getSpellInfo = Skada.getSpellInfo or GetSpellInfo
local getSpellLink = Skada.getSpellLink or GetSpellLink
local _
local function GetSpellSchool(spellid)
if CCSpells[spellid] and CCSpells[spellid] ~= true then
return CCSpells[spellid]
end
if ExtraCCSpells[spellid] and ExtraCCSpells[spellid] ~= true then
return ExtraCCSpells[spellid]
end
end
-- ======= --
-- CC Done --
-- ======= --
Skada:AddLoadableModule("CC Done", function(Skada, L)
if Skada:IsDisabled("CC Done") then return end
local mod = Skada:NewModule(L["CC Done"])
local playermod = mod:NewModule(L["CC Done spells"])
local targetmod = mod:NewModule(L["CC Done targets"])
local function log_ccdone(set, cc)
local player = Skada:get_player(set, cc.playerid, cc.playername, cc.playerflags)
if player then
-- increment the count.
player.ccdone = (player.ccdone or 0) + 1
set.ccdone = (set.ccdone or 0) + 1
-- record the spell and its targets.
player.ccdone_spells = player.ccdone_spells or {}
player.ccdone_spells[cc.spellid] = (player.ccdone_spells[cc.spellid] or 0) + 1
-- saving this to total set may become a memory hog deluxe.
if set == Skada.current and cc.dstName then
player.ccdone_targets = player.ccdone_targets or {}
player.ccdone_targets[cc.dstName] = (player.ccdone_targets[cc.dstName] or 0) + 1
end
end
end
local data = {}
local function AuraApplied(ts, event, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags, ...)
local spellid = ...
if CCSpells[spellid] or ExtraCCSpells[spellid] then
data.playerid, data.playername = Skada:FixMyPets(srcGUID, srcName, srcFlags)
data.playerflags = srcFlags
data.dstGUID = dstGUID
data.dstName = dstName
data.spellid = spellid
log_ccdone(Skada.current, data)
log_ccdone(Skada.total, data)
end
end
function playermod:Enter(win, id, label)
win.playerid, win.playername = id, label
win.title = format(L["%s's CC Done spells"], label)
end
function playermod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's CC Done spells"], player.name)
local total = player.ccdone or 0
if total > 0 and player.ccdone_spells then
local maxvalue, nr = 0, 1
for spellid, count in pairs(player.ccdone_spells) do
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = spellid
d.spellid = spellid
d.label, _, d.icon = getSpellInfo(spellid)
d.spellschool = GetSpellSchool(spellid)
d.value = count
d.valuetext = Skada:FormatValueText(
d.value,
mod.metadata.columns.Count,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
win.metadata.maxvalue = maxvalue
end
end
end
function targetmod:Enter(win, id, label)
win.playerid, win.playername = id, label
win.title = format(L["%s's CC Done targets"], label)
end
function targetmod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's CC Done targets"], player.name)
local total = player.ccdone or 0
if total > 0 and player.ccdone_targets then
local maxvalue, nr = 0, 1
for targetname, count in pairs(player.ccdone_targets) do
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = targetname
d.label = targetname
d.value = count
d.valuetext = Skada:FormatValueText(
d.value,
mod.metadata.columns.Count,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
win.metadata.maxvalue = maxvalue
end
end
end
function mod:Update(win, set)
win.title = L["CC Done"]
local total = set.ccdone or 0
if total > 0 then
local maxvalue, nr = 0, 1
for _, player in ipairs(set.players) do
if (player.ccdone or 0) > 0 then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = player.id
d.label = player.name
d.text = Skada:FormatName(player.name, player.id)
d.class = player.class
d.role = player.role
d.spec = player.spec
d.value = player.ccdone
d.valuetext = Skada:FormatValueText(
d.value,
self.metadata.columns.Count,
Skada:FormatPercent(d.value, total),
self.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
end
win.metadata.maxvalue = maxvalue
end
end
function mod:OnEnable()
self.metadata = {
showspots = true,
ordersort = true,
click1 = playermod,
click2 = targetmod,
nototalclick = {targetmod},
columns = {Count = true, Percent = false},
icon = "Interface\\Icons\\spell_frost_chainsofice"
}
Skada:RegisterForCL(AuraApplied, "SPELL_AURA_APPLIED", {src_is_interesting = true})
Skada:RegisterForCL(AuraApplied, "SPELL_AURA_REFRESH", {src_is_interesting = true})
Skada:AddMode(self, L["CC Tracker"])
end
function mod:OnDisable()
Skada:RemoveMode(self)
end
function mod:AddToTooltip(set, tooltip)
if (set.ccdone or 0) > 0 then
tooltip:AddDoubleLine(L["CC Done"], set.ccdone, 1, 1, 1)
end
end
function mod:GetSetSummary(set)
return tostring(set.ccdone or 0), set.ccdone or 0
end
end)
-- ======== --
-- CC Taken --
-- ======== --
Skada:AddLoadableModule("CC Taken", function(Skada, L)
if Skada:IsDisabled("CC Taken") then return end
local mod = Skada:NewModule(L["CC Taken"])
local playermod = mod:NewModule(L["CC Taken spells"])
local sourcemod = mod:NewModule(L["CC Taken sources"])
local function log_cctaken(set, cc)
local player = Skada:get_player(set, cc.playerid, cc.playername, cc.playerflags)
if player then
-- increment the count.
player.cctaken = (player.cctaken or 0) + 1
set.cctaken = (set.cctaken or 0) + 1
-- record the spell and its sources.
player.cctaken_spells = player.cctaken_spells or {}
player.cctaken_spells[cc.spellid] = (player.cctaken_spells[cc.spellid] or 0) + 1
-- saving this to total set may become a memory hog deluxe.
if set == Skada.current and cc.srcName then
player.cctaken_sources = player.cctaken_sources or {}
player.cctaken_sources[cc.srcName] = (player.cctaken_sources[cc.srcName] or 0) + 1
end
end
end
local data = {}
local function AuraApplied(ts, event, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags, ...)
local spellid = ...
if CCSpells[spellid] or ExtraCCSpells[spellid] then
data.srcGUID = srcGUID
data.srcName = srcName
data.playerid = dstGUID
data.playername = dstName
data.playerflags = dstFlags
data.spellid = spellid
log_cctaken(Skada.current, data)
log_cctaken(Skada.total, data)
end
end
function playermod:Enter(win, id, label)
win.playerid, win.playername = id, label
win.title = format(L["%s's CC Taken spells"], label)
end
function playermod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's CC Taken spells"], player.name)
local total = player.cctaken or 0
if total > 0 and player.cctaken_spells then
local maxvalue, nr = 0, 1
for spellid, count in pairs(player.cctaken_spells) do
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = spellid
d.spellid = spellid
d.label, _, d.icon = getSpellInfo(spellid)
d.spellschool = GetSpellSchool(spellid)
d.value = count
d.valuetext = Skada:FormatValueText(
d.value,
mod.metadata.columns.Count,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
win.metadata.maxvalue = maxvalue
end
end
end
function sourcemod:Enter(win, id, label)
win.playerid, win.playername = id, label
win.title = format(L["%s's CC Taken sources"], label)
end
function sourcemod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's CC Taken sources"], player.name)
local total = player.cctaken or 0
if total > 0 and player.cctaken_sources then
local maxvalue, nr = 0, 1
for sourcename, count in pairs(player.cctaken_sources) do
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = sourcename
d.label = sourcename
d.value = count
d.valuetext = Skada:FormatValueText(
d.value,
mod.metadata.columns.Count,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
win.metadata.maxvalue = maxvalue
end
end
end
function mod:Update(win, set)
win.title = L["CC Taken"]
local total = set.cctaken or 0
if total > 0 then
local maxvalue, nr = 0, 1
for _, player in ipairs(set.players) do
if (player.cctaken or 0) > 0 then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = player.id
d.label = player.name
d.text = Skada:FormatName(player.name, player.id)
d.class = player.class
d.role = player.role
d.spec = player.spec
d.value = player.cctaken
d.valuetext = Skada:FormatValueText(
d.value,
self.metadata.columns.Count,
Skada:FormatPercent(d.value, total),
self.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
end
win.metadata.maxvalue = maxvalue
end
end
function mod:OnEnable()
self.metadata = {
showspots = true,
ordersort = true,
click1 = playermod,
click2 = sourcemod,
nototalclick = {sourcemod},
columns = {Count = true, Percent = false},
icon = "Interface\\Icons\\spell_magic_polymorphrabbit"
}
Skada:RegisterForCL(AuraApplied, "SPELL_AURA_APPLIED", {dst_is_interesting = true})
Skada:RegisterForCL(AuraApplied, "SPELL_AURA_REFRESH", {dst_is_interesting = true})
Skada:AddMode(self, L["CC Tracker"])
end
function mod:OnDisable()
Skada:RemoveMode(self)
end
function mod:AddToTooltip(set, tooltip)
if (set.cctaken or 0) > 0 then
tooltip:AddDoubleLine(L["CC Taken"], set.cctaken, 1, 1, 1)
end
end
function mod:GetSetSummary(set)
return tostring(set.cctaken or 0), set.cctaken or 0
end
end)
-- =========== --
-- CC Breakers --
-- =========== --
Skada:AddLoadableModule("CC Breakers", function(Skada, L)
if Skada:IsDisabled("CC Breakers") then return end
local mod = Skada:NewModule(L["CC Breakers"])
local playermod = mod:NewModule(L["CC Break spells"])
local targetmod = mod:NewModule(L["CC Break targets"])
local UnitExists, UnitName, IsInRaid = UnitExists, UnitName, Skada.IsInRaid
local GetNumRaidMembers, GetPartyAssignment = GetNumRaidMembers, GetPartyAssignment
local IsInInstance, UnitInRaid = IsInInstance, UnitInRaid
local function log_ccbreak(set, cc)
local player = Skada:get_player(set, cc.playerid, cc.playername)
if player then
-- increment the count.
player.ccbreak = (player.ccbreak or 0) + 1
set.ccbreak = (set.ccbreak or 0) + 1
-- record the spell and its targets.
player.ccbreak_spells = player.ccbreak_spells or {}
player.ccbreak_spells[cc.spellid] = (player.ccbreak_spells[cc.spellid] or 0) + 1
-- saving this to total set may become a memory hog deluxe.
if set == Skada.current and cc.dstName then
player.ccbreak_targets = player.ccbreak_targets or {}
player.ccbreak_targets[cc.dstName] = (player.ccbreak_targets[cc.dstName] or 0) + 1
end
end
end
local data = {}
local function AuraBroken(ts, event, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags, ...)
local spellid, spellname, _, extraspellid, extraspellname, _, auratype = ...
if not CCSpells[spellid] then return end
local petid, petname = srcGUID, srcName
local srcGUID_modified, srcName_modified = Skada:FixMyPets(srcGUID, srcName, srcFlags)
data.playerid = srcGUID_modified or srcGUID
data.playername = srcName_modified or srcName
data.playerflags = srcFlags
data.dstGUID = dstGUID
data.dstName = dstName
data.dstFlags = dstFlags
data.spellid = spellid
data.extraspellid = extraspellid
log_ccbreak(Skada.current, data)
log_ccbreak(Skada.total, data)
-- Optional announce
srcName = srcName_modified or srcName
if Skada.db.profile.modules.ccannounce and IsInRaid() and UnitInRaid(srcName) then
if select(2, IsInInstance()) == "pvp" then return end
-- Ignore main tanks and main assist?
if Skada.db.profile.modules.ccignoremaintanks then
-- Loop through our raid and return if src is a main tank.
for i = 1, GetNumRaidMembers() do
local unit = "raid" .. tostring(i)
if UnitExists(unit) and UnitName(unit) == srcName then
if GetPartyAssignment("MAINTANK", unit) or GetPartyAssignment("MAINASSIST", unit) then
return
end
break
end
end
end
-- Prettify pets.
if petid ~= srcGUID_modified then
srcName = petname .. " (" .. srcName .. ")"
end
-- Go ahead and announce it.
if extraspellname then
Skada:SendChat(format(L["%s on %s removed by %s's %s"], spellname, dstName, srcName, getSpellLink(extraspellid)), "RAID", "preset")
else
Skada:SendChat(format(L["%s on %s removed by %s"], spellname, dstName, srcName), "RAID", "preset")
end
end
end
function playermod:Enter(win, id, label)
win.playerid, win.playername = id, label
win.title = format(L["%s's CC Break spells"], label)
end
function playermod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's CC Break spells"], player.name)
local total = player.ccbreak or 0
if total > 0 and player.ccbreak_spells then
local maxvalue, nr = 0, 1
for spellid, count in pairs(player.ccbreak_spells) do
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = spellid
d.spellid = spellid
d.label, _, d.icon = getSpellInfo(spellid)
d.spellschool = GetSpellSchool(spellid)
d.value = count
d.valuetext = Skada:FormatValueText(
d.value,
mod.metadata.columns.Count,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
win.metadata.maxvalue = maxvalue
end
end
end
function targetmod:Enter(win, id, label)
win.playerid, win.playername = id, label
win.title = format(L["%s's CC Break targets"], label)
end
function targetmod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's CC Break targets"], player.name)
local total = player.ccbreak or 0
if total > 0 and player.ccbreak_targets then
local maxvalue, nr = 0, 1
for targetname, count in pairs(player.ccbreak_targets) do
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = targetname
d.label = targetname
d.value = count
d.valuetext = Skada:FormatValueText(
d.value,
mod.metadata.columns.Count,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
win.metadata.maxvalue = maxvalue
end
end
end
function mod:Update(win, set)
win.title = L["CC Breakers"]
local total = set.ccbreak or 0
if total > 0 then
local maxvalue, nr = 0, 1
for _, player in ipairs(set.players) do
if (player.ccbreak or 0) > 0 then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = player.id
d.label = player.name
d.text = Skada:FormatName(player.name, player.id)
d.class = player.class
d.role = player.role
d.spec = player.spec
d.value = player.ccbreak
d.valuetext = Skada:FormatValueText(
d.value,
self.metadata.columns.Count,
Skada:FormatPercent(d.value, total),
self.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
end
win.metadata.maxvalue = maxvalue
end
end
function mod:OnEnable()
self.metadata = {
showspots = true,
ordersort = true,
click1 = playermod,
click2 = targetmod,
nototalclick = {targetmod},
columns = {Count = true, Percent = false},
icon = "Interface\\Icons\\spell_holy_sealofvalor"
}
Skada:RegisterForCL(AuraBroken, "SPELL_AURA_BROKEN", {src_is_interesting = true})
Skada:RegisterForCL(AuraBroken, "SPELL_AURA_BROKEN_SPELL", {src_is_interesting = true})
Skada:AddMode(self, L["CC Tracker"])
end
function mod:OnDisable()
Skada:RemoveMode(self)
end
function mod:AddToTooltip(set, tooltip)
if (set.ccbreak or 0) > 0 then
tooltip:AddDoubleLine(L["CC Breaks"], set.ccbreak, 1, 1, 1)
end
end
function mod:GetSetSummary(set)
return tostring(set.ccbreak or 0), set.ccbreak or 0
end
function mod:OnInitialize()
Skada.options.args.modules.args.ccoptions = {
type = "group",
name = self.moduleName,
desc = format(L["Options for %s."], self.moduleName),
get = function(i)
return Skada.db.profile.modules[i[#i]]
end,
set = function(i, val)
Skada.db.profile.modules[i[#i]] = val
end,
args = {
ccannounce = {
type = "toggle",
name = L["Announce CC breaking to party"],
order = 1,
width = "double"
},
ccignoremaintanks = {
type = "toggle",
name = L["Ignore Main Tanks"],
order = 2,
width = "double"
}
}
}
end
end)
|
object_tangible_npe_npe_generic_uniform_box = object_tangible_npe_shared_npe_generic_uniform_box:new {
}
ObjectTemplates:addTemplate(object_tangible_npe_npe_generic_uniform_box, "object/tangible/npe/npe_generic_uniform_box.iff")
|
local U = require("us4l").U
local UTF8 = require("us4l.Encodings").UTF8
local TS = require "us4l.TextSegmentation"
local mul_sign, div_sign = U[[\N{MULTIPLICATION SIGN}]]:ToUtf8(), U[[\N{DIVISION_SIGN}]]:ToUtf8()
local line_num = 0
for line in io.lines( [[..\UCD\auxiliary\SentenceBreakTest.txt]] ) do
line_num = line_num + 1
--Discard comment-only lines
if not(#line == 0 or line:sub(1,1) == "#") then
repeat
line = line:sub(3,-1):match("^([^#]+)")
local line_cps = {}
for cp_str in line:gmatch("%x+") do
line_cps[ #line_cps + 1 ] = tonumber( cp_str, 16 )
end
local succ, in_line = pcall( U, line_cps )
if not succ then
print( "Failed to create string on line " .. tostring(line_num) )
break
end
local seqs = {}
local cur_str_cps = {}
for token in line:gmatch("%S+") do
if token == mul_sign then
--Do nothing
elseif token == div_sign then
seqs[ #seqs+1 ] = U( cur_str_cps )
cur_str_cps = {}
else
cur_str_cps[ #cur_str_cps + 1 ] = tonumber( token, 16 )
end
end
local out_seqs = {}
for sentence in TS.Sentences( in_line ) do
out_seqs[ #out_seqs+1 ] = sentence
end
for i = 1, math.max( #seqs, #out_seqs ) do
if seqs[i] ~= out_seqs[i] then
print( ("="):rep(10) )
print( string.format( "Failed test from line #%i:", line_num ) )
print( " Input string:" )
print( " " .. in_line:PrettyPrint():gsub( "\n", "\n " ) )
print( " Expected sentences:" )
for i,str in ipairs( seqs ) do
print( string.format( " Sentence #%i:", i ) )
print( " " .. str:PrettyPrint():gsub( "\n", "\n " ) )
end
print( " Output sentences:" )
for i,str in ipairs( out_seqs ) do
print( string.format( " Sentence #%i:", i ) )
print( " " .. str:PrettyPrint():gsub( "\n", "\n " ) )
end
print( ("="):rep(10) )
print()
break
end
print( string.format( "Passed test from line #%i", line_num ) )
end
until true
end
end
|
vim.cmd [[
let @d = 'oimport ipdb; ipdb.set_trace()jk'
]]
|
local K, C = unpack(select(2, ...))
local Module = K:NewModule("MicroBar", "AceHook-3.0", "AceEvent-3.0")
local _G = _G
local assert = assert
local C_StorePublic_IsEnabled = _G.C_StorePublic.IsEnabled
local UpdateMicroButtonsParent = _G.UpdateMicroButtonsParent
local function onLeave()
if C["ActionBar"].MicroBarMouseover then
K.UIFrameFadeOut(KkthnxUI_MicroBar, 0.2, KkthnxUI_MicroBar:GetAlpha(), 0.25)
end
end
local watcher = 0
local function onUpdate(self, elapsed)
if watcher > 0.1 then
if not self:IsMouseOver() then
self.IsMouseOvered = nil
self:SetScript("OnUpdate", nil)
onLeave()
end
watcher = 0
else
watcher = watcher + elapsed
end
end
local function onEnter()
if C["ActionBar"].MicroBarMouseover and not KkthnxUI_MicroBar.IsMouseOvered then
KkthnxUI_MicroBar.IsMouseOvered = true
KkthnxUI_MicroBar:SetScript("OnUpdate", onUpdate)
K.UIFrameFadeIn(KkthnxUI_MicroBar, 0.2, KkthnxUI_MicroBar:GetAlpha(), 1)
end
end
function Module:HandleMicroButton(button)
assert(button, "Invalid micro button name.")
local pushed = button:GetPushedTexture()
local normal = button:GetNormalTexture()
local disabled = button:GetDisabledTexture()
local f = CreateFrame("Frame", nil, button)
K.CreateBorder(f)
f:SetOutside(button)
button.backdrop = f
button:SetParent(KkthnxUI_MicroBar)
button:GetHighlightTexture():Kill()
button:HookScript("OnEnter", onEnter)
button:SetHitRectInsets(0, 0, 0, 0)
if button.Flash then
button.Flash:SetInside()
button.Flash:SetTexture(nil)
end
pushed:SetTexCoord(0.22, 0.81, 0.26, 0.82)
pushed:SetInside(f)
normal:SetTexCoord(0.22, 0.81, 0.21, 0.82)
normal:SetInside(f)
if disabled then
disabled:SetTexCoord(0.22, 0.81, 0.21, 0.82)
disabled:SetInside(f)
end
end
function Module:MainMenuMicroButton_SetNormal()
MainMenuBarPerformanceBar:SetPoint("TOPLEFT", MainMenuMicroButton, "TOPLEFT", 9, -36)
end
function Module:MainMenuMicroButton_SetPushed()
MainMenuBarPerformanceBar:SetPoint("TOPLEFT", MainMenuMicroButton, "TOPLEFT", 8, -37)
end
function Module:UpdateMicroButtonsParent()
for i = 1, #MICRO_BUTTONS do
_G[MICRO_BUTTONS[i]]:SetParent(KkthnxUI_MicroBar)
end
end
-- we use this table to sort the micro buttons on our bar to match Blizzard"s button placements.
local __buttonIndex = {
[8] = "CollectionsMicroButton",
[9] = "EJMicroButton",
[10] = (not C_StorePublic_IsEnabled() and GetCurrentRegionName() == "CN") and "HelpMicroButton" or "StoreMicroButton",
[11] = "MainMenuMicroButton"
}
function Module:UpdateMicroPositionDimensions()
if not KkthnxUI_MicroBar then
return
end
local numRows = 1
local prevButton = KkthnxUI_MicroBar
local offset = 4
local spacing = offset + 2
for i = 1, #MICRO_BUTTONS-1 do
local button = _G[__buttonIndex[i]] or _G[MICRO_BUTTONS[i]]
local lastColumnButton = i - 11
lastColumnButton = _G[__buttonIndex[lastColumnButton]] or _G[MICRO_BUTTONS[lastColumnButton]]
button:SetSize(20, 20 * 1.4)
button:ClearAllPoints()
if prevButton == KkthnxUI_MicroBar then
button:SetPoint("TOPLEFT", prevButton, "TOPLEFT", offset, -offset)
else
button:SetPoint("LEFT", prevButton, "RIGHT", spacing, 0)
end
prevButton = button
end
if C["ActionBar"].MicroBarMouseover and not KkthnxUI_MicroBar:IsMouseOver() then
KkthnxUI_MicroBar:SetAlpha(0.25)
else
KkthnxUI_MicroBar:SetAlpha(1)
end
Module.MicroWidth = (((_G["CharacterMicroButton"]:GetWidth() + spacing) * 11) - spacing) + (offset * 2)
Module.MicroHeight = (((_G["CharacterMicroButton"]:GetHeight() + spacing) * numRows) - spacing) + (offset * 2)
KkthnxUI_MicroBar:SetSize(Module.MicroWidth, Module.MicroHeight)
end
function Module:UpdateMicroButtons()
GuildMicroButtonTabard:SetInside(GuildMicroButton)
GuildMicroButtonTabard.background:SetInside(GuildMicroButton)
GuildMicroButtonTabard.background:SetTexCoord(0.17, 0.87, 0.5, 0.908)
GuildMicroButtonTabard.emblem:ClearAllPoints()
GuildMicroButtonTabard.emblem:SetPoint("TOPLEFT", GuildMicroButton, "TOPLEFT", 4, -4)
GuildMicroButtonTabard.emblem:SetPoint("BOTTOMRIGHT", GuildMicroButton, "BOTTOMRIGHT", -4, 8)
self:UpdateMicroPositionDimensions()
end
function Module:OnEnable()
if C["ActionBar"].MicroBar ~= true then
return
end
local microBar = CreateFrame("Frame", "KkthnxUI_MicroBar", UIParent)
microBar:SetPoint("TOP", UIParent, "TOP", 0, 0)
microBar:EnableMouse(false)
for i = 1, #MICRO_BUTTONS do
self:HandleMicroButton(_G[MICRO_BUTTONS[i]])
end
MicroButtonPortrait:SetInside(CharacterMicroButton.backdrop)
self:SecureHook("MainMenuMicroButton_SetPushed")
self:SecureHook("MainMenuMicroButton_SetNormal")
self:SecureHook("UpdateMicroButtonsParent")
self:SecureHook("MoveMicroButtons", "UpdateMicroPositionDimensions")
self:SecureHook("UpdateMicroButtons")
UpdateMicroButtonsParent(microBar)
self:MainMenuMicroButton_SetNormal()
self:UpdateMicroPositionDimensions()
if MainMenuBarPerformanceBar then
MainMenuBarPerformanceBar:SetTexture(nil)
MainMenuBarPerformanceBar:SetVertexColor(0, 0, 0, 0)
MainMenuBarPerformanceBar:Hide()
end
K.Movers:RegisterFrame(microBar)
end
|
-- RP Tags
-- by Oraibi, Moon Guard (US) server
-- ------------------------------------------------------------------------------
-- This work is licensed under the Creative Commons Attribution 4.0 International
-- (CC BY 4.0) license.
local RPTAGS = RPTAGS;
local addOnName, ns = ...;
RPTAGS.queue:NewModule(addOnName, "rpClient");
-- this doesn't do anything! Except it load and such if you have XRP.
|
CuiVersion = "1.6.2"
LastUpdate = "2020-10-12"
VersionDetail = "Concise UI - " .. CuiVersion .. "[NEWLINE]" .. "Last Update: " .. LastUpdate
|
local GUI = LibStub('NetEaseGUI-2.0')
local View = GUI:NewEmbed('TabPanel', 4)
if not View then
return
end
View._PanelList = View._PanelList or setmetatable({}, {__index = function(t, k)
t[k] = {}
return t[k]
end})
local _PanelList = View._PanelList
function View:EnableTabFrame(flag)
self.noTab = not flag or nil
if self.TabFrame then
self.TabFrame:Hide()
end
end
function View:GetPanelList()
return _PanelList[self]
end
function View:UpdateTab()
if not self.noTab then
if self.selectTab then
self:GetTabFrame():SetSelected(self.selectTab)
self.selectTab = nil
end
self:GetTabFrame():Refresh()
else
local data = _PanelList[self][1]
if data then
data.panel:Show()
if self.Inset2 then
self.Inset:SetShown(not data.noInset)
self.Inset2:SetShown(data.noInset)
elseif self.Inset then
self.Inset:Show()
end
end
end
end
local function parseArgs(panel, opts, ...)
if type(opts) ~= 'table' then
opts = {
padding = opts,
}
opts.topHeight, opts.bottomHeight, opts.noInset = ...
end
if panel.InjectPanelArgs then
local default = panel:InjectPanelArgs()
if default then
for k, v in pairs(default) do
if opts[k] == nil then
opts[k] = v
end
end
end
end
return opts
end
function View:RegisterPanel(name, panel, ...)
if self.noTab then
if #_PanelList[self] > 0 then
error([[Can register only one panel into notab container.]], 2)
end
end
if self:IsPanelRegistered(name) then
error([[Cannot register panel (same name)]], 2)
end
GUI:Embed(panel, 'Owner')
local opts = parseArgs(panel, ...)
local data = {
name = name,
panel = panel,
topHeight = opts.topHeight or self.GetTopHeight and self:GetTopHeight() or 0,
bottomHeight = opts.bottomHeight or self.GetBottomHeight and self:GetBottomHeight() or 0,
noInset = opts.noInset,
}
local offset
if opts.before then
local i, v = self:IsPanelRegistered(opts.before)
if i then
offset = i
end
elseif opts.after then
local i, v = self:IsPanelRegistered(opts.after)
if i then
offset = i + 1
end
end
if offset then
tinsert(_PanelList[self], offset, data)
local selectTab = self:GetSelectedTab()
if selectTab and selectTab >= offset then
self:SelectTab(selectTab + 1)
end
else
tinsert(_PanelList[self], data)
end
local padding = opts.padding or 10
panel:Hide()
panel:SetOwner(self)
panel:SetParent(opts.noInset and self.Inset2 or self.Inset)
panel:ClearAllPoints()
panel:SetPoint('TOPLEFT', padding, -padding)
panel:SetPoint('BOTTOMRIGHT', -padding, padding)
panel:SetFrameLevel(self.Inset:GetFrameLevel()+1)
self:UpdateTab()
if self.PortraitFrame then
self.PortraitFrame:SetFrameLevel(max(panel:GetFrameLevel()+1, self.PortraitFrame:GetFrameLevel()))
end
return data
end
function View:UnregisterPanel(name)
local i, v = self:IsPanelRegistered(name)
if i then
tremove(_PanelList[self], i)
v.panel:Hide()
v.panel:ClearAllPoints()
v.panel:SetParent(nil)
end
end
function View:IsPanelRegistered(name)
for i, v in ipairs(_PanelList[self]) do
if v.name == name then
return i, v
end
end
end
function View:UnregisterAllPanels()
for i, v in ipairs(_PanelList[self]) do
v.panel:Hide()
v.panel:ClearAllPoints()
v.panel:SetParent(nil)
end
wipe(_PanelList[self])
end
function View:EnableTab(index)
local tabframe = self:GetTabFrame()
if tabframe then
tabframe:EnableTab(index)
end
end
function View:DisableTab(index)
local tabframe = self:GetTabFrame()
if tabframe then
tabframe:DisableTab(index)
end
end
function View:SetTabEnabled(index, flag)
local tabframe = self:GetTabFrame()
if tabframe then
tabframe:SetTabEnabled(index, flag)
end
end
function View:SelectTab(index)
self.selectTab = index
local tabframe = self:GetTabFrame()
if tabframe then
tabframe:SetSelected(index)
end
end
function View:SetTabText(index, text)
local tabframe = self:GetTabFrame()
if not tabframe then
return
end
if _PanelList[self] and _PanelList[self][index] then
_PanelList[self][index].name = text
end
tabframe:Refresh()
end
function View:GetPanelIndex(panel)
for i, v in ipairs(_PanelList[self]) do
if v.panel == panel then
return i
end
end
end
function View:SelectPanel(panel)
local index = self:GetPanelIndex(panel)
if index then
self:SelectTab(index)
end
end
function View:EnablePanel(panel)
local index = self:GetPanelIndex(panel)
if index then
self:EnableTab(index)
end
end
function View:DisablePanel(panel)
local index = self:GetPanelIndex(panel)
if index then
self:DisableTab(index)
end
end
function View:SetPanelEnabled(panel, flag)
local index = self:GetPanelIndex(panel)
if index then
self:SetTabEnabled(index, flag)
end
end
function View:SetPanelText(panel, text)
local index = self:GetPanelIndex(panel)
if index then
self:SetTabText(index, text)
end
end
function View:GetSelectedTab()
local tabframe = self:GetTabFrame()
if tabframe then
return tabframe:GetSelected()
end
end
function View:GetSelectedPanel()
local index = self:GetSelectedTab()
return _PanelList[self][index] and _PanelList[self][index].panel
end
function View:GetPanelByIndex(index)
return _PanelList[self][index] and _PanelList[self][index].panel
end
function View:FlashTab(index, flag)
local tabframe = self:GetTabFrame()
if tabframe then
return tabframe:FlashTab(index, flag)
end
end
function View:FlashTabByPanel(panel, flag)
local index = self:GetPanelIndex(panel)
if index then
return self:FlashTab(index, flag)
end
end
|
local Button = require 'lbutton'
local RadioB = require 'lradiobutton'
local Skillpane = require 'skillpane'
local MIN_AUTOSELECT_STRENGTH = 4
local function makeButtons(ranks)
local t = {back = Button.new(0,
love.window.getHeight() - 35,
_G.quads.buttons.back),
signals = Button.new(love.window.getWidth() - 110,
100,
_G.quads.buttons.signals),
}
for i=1, #ranks do
local b = RadioB.new(110, (i-1)*40 + 15,
_G.quads.buttons.box_unselected,
_G.quads.buttons.box_selected)
if ranks[i] >= MIN_AUTOSELECT_STRENGTH then
b:toggle()
end
t[i] = b
end
return t
end
local P = {}
P.enter = function(self)
local ranks = _G.profile:getSkillRanks()
self.buttons = self.buttons or makeButtons(ranks)
self.skillpane = Skillpane.new(150,11, ranks)
end
P.receiveClick = function(self, mx, my)
if not self.hot then return end
if self.hot == 'back' then
_G.setMode()
elseif type(self.hot) == 'number' then
local b = self.buttons[self.hot]
assert(b)
b:toggle()
elseif self.hot == 'signals' then
local opts = {}
for i=1, #self.buttons do
opts[i] = self.buttons[i]:isSelected()
end
_G.tetrisOpts = opts
_G.setMode('tetrisplay')
end
end
P.receiveKeypress = function(self, key)
if key == 'escape' then
_G.setMode()
end
end
P.update = function(self, dt)
local hot
local mx, my = love.mouse.getPosition()
for k,b in pairs(self.buttons) do
if b:isMouseOver(mx,my) then
hot = k
break
end
end
self.hot = hot or self.skillpane:getMousedOverElem(mx, my)
end
P.draw = function(self)
love.graphics.setColor(0xff, 0xff, 0xff)
local batlas = _G.atlases.buttons
local hatlas = _G.atlases.hot
for k,b in pairs(self.buttons) do
if self.hot == k then
b:draw(hatlas)
else
b:draw(batlas)
end
end
self.skillpane:draw()
end
return P
|
--- wrapper accepts encoder and decoder objects
--- It combines them into one pipeline and output the picture and the message
-- -- Wrapping encoder and decoder
-- Input format {original image, message}
local wrapper = nn.Sequential()
local blank_plus_encoder = nn.ConcatTable()
blank_plus_encoder:add(nn.SelectTable(1))
blank_plus_encoder:add(encoder)
wrapper:add(blank_plus_encoder)
-- input format {original, changed}
local encoded_plus_transmitted = nn.ConcatTable()
encoded_plus_transmitted:add(nn.SelectTable(2))
encoded_plus_transmitted:add(transmitter)
wrapper:add(encoded_plus_transmitted)
local blank_plus_decoder = nn.ParallelTable()
blank_plus_decoder:add(nn.Identity())
blank_plus_decoder:add(decoder)
wrapper:add(blank_plus_decoder)
--- Reformatting input
return wrapper
|
local rawmulti = angelsmods.marathon.rawmulti
if not clowns.special_vanilla then
data:extend(
{
{
type = "recipe",
name = "clowns-resource1-sluicing",
category = "sluicing",
enabled = false,
icon = "__Clowns-Extended-Minerals__/graphics/icons/clowns-resource1.png",
icon_size = 32,
ingredients =
{
{type="item", name="clowns-resource1", amount=10},
{type="fluid", name="water", amount=10}
},
results =
{
{type="fluid", name="water-saline", amount=10},
{type="item", name="iron-ore", amount=1, probability = 0.2,},
{type="item", name="tin-ore", amount=1, probability = 0.1,},
{type="item", name="crystal-dust", amount=1, probability = 0.1,},
{type="item", name="gold-ore", amount=1, probability = 0.05,},
{type="item", name="chrome-ore", amount=1, probability = 0.01,},
{type="item", name="platinum-ore", amount=1, probability = 0.01,}
--Rare earth metals, zirconium
},
energy_required = 5,
subgroup = "water-washing",
order = "k-b-a",
},
{
type = "recipe",
name = "clowns-resource1-sluicing-advanced",
category = "sluicing",
enabled = false,
icon = "__Clowns-Extended-Minerals__/graphics/icons/clowns-resource1.png",
icon_size = 32,
ingredients =
{
{type="item", name="clowns-resource1", amount=10},
{type="fluid", name="water", amount=10}
},
results =
{
{type="fluid", name="water-saline", amount=10},
{type="item", name="gold-ore", amount=1, probability = 0.1,},
{type="item", name="chrome-ore", amount=1, probability = 0.03,},
{type="item", name="rutile-ore", amount=1, probability = 0.03,},
{type="item", name="platinum-ore", amount=1, probability = 0.03,},
{type="item", name="uranium-ore", amount=1, probability = 0.01,},
{type="item", name="thorium-ore", amount=1, probability = 0.01,},
},
energy_required = 5,
subgroup = "water-washing",
order = "k-b-b",
}
}
)
end
|
------------------------------------------------------------
--------------------- yrp_scoreboard -----------------------
------------------------------------------------------------
--------------------- Created by Flap ----------------------
------------------------------------------------------------
----------------- YourRolePlay Development -----------------
----------- Thank you for using this scoreboard ------------
----- Regular updates and lots of interesting scripts ------
--------- discord -> https://discord.gg/hqZEXc8FSE ---------
------------------------------------------------------------
local Keys = {
["ESC"] = 322, ["F1"] = 288, ["F2"] = 289, ["F3"] = 170, ["F5"] = 166, ["F6"] = 167, ["F7"] = 168, ["F8"] = 169, ["F9"] = 56, ["F10"] = 57,
["~"] = 243, ["1"] = 157, ["2"] = 158, ["3"] = 160, ["4"] = 164, ["5"] = 165, ["6"] = 159, ["7"] = 161, ["8"] = 162, ["9"] = 163, ["-"] = 84, ["="] = 83, ["BACKSPACE"] = 177,
["TAB"] = 37, ["Q"] = 44, ["W"] = 32, ["E"] = 38, ["R"] = 45, ["T"] = 245, ["Y"] = 246, ["U"] = 303, ["P"] = 199, ["["] = 39, ["]"] = 40, ["ENTER"] = 18,
["CAPS"] = 137, ["A"] = 34, ["S"] = 8, ["D"] = 9, ["F"] = 23, ["G"] = 47, ["H"] = 74, ["K"] = 311, ["L"] = 182,
["LEFTSHIFT"] = 21, ["Z"] = 20, ["X"] = 73, ["C"] = 26, ["V"] = 0, ["B"] = 29, ["N"] = 249, ["M"] = 244, [","] = 82, ["."] = 81,
["LEFTCTRL"] = 36, ["LEFTALT"] = 19, ["SPACE"] = 22, ["RIGHTCTRL"] = 70,
["HOME"] = 213, ["PAGEUP"] = 10, ["PAGEDOWN"] = 11, ["DELETE"] = 178,
["LEFT"] = 174, ["RIGHT"] = 175, ["TOP"] = 27, ["DOWN"] = 173,
["NENTER"] = 201, ["N4"] = 108, ["N5"] = 60, ["N6"] = 107, ["N+"] = 96, ["N-"] = 97, ["N7"] = 117, ["N8"] = 61, ["N9"] = 118
}
local idVisable = true
ESX = nil
Citizen.CreateThread(function()
while ESX == nil do
TriggerEvent(Config.general_config_settings.es_extended, function(obj) ESX = obj end)
Citizen.Wait(10)
end
Citizen.Wait(128)
ESX.TriggerServerCallback('yrp_scoreboard:getConnectedPlayers', function(connectedPlayers)
UpdatePlayerTable(connectedPlayers)
end)
end)
RegisterNetEvent('yrp_scoreboard:retrieveData')
AddEventHandler('yrp_scoreboard:retrieveData', function(data)
if Config.general_config_settings.job_grade_players then
SendNUIMessage({
action = 'updateJobGradeAndName',
name = data.name,
jobName = data.jobName,
jobGrade = data.jobGrade
})
end
end)
Citizen.CreateThread(function()
Citizen.Wait(3000)
SendNUIMessage({
action = 'updateServerInfo',
maxPlayers = GetConvarInt('sv_maxclients', 64),
uptime = 'unknown',
playTime = '00h 00m',
})
TriggerServerEvent('yrp_scoreboard:retrieveData')
end)
RegisterNetEvent('yrp_scoreboard:updateConnectedPlayers')
AddEventHandler('yrp_scoreboard:updateConnectedPlayers', function(connectedPlayers)
UpdatePlayerTable(connectedPlayers)
end)
RegisterNetEvent('yrp_scoreboard:updatePing')
AddEventHandler('yrp_scoreboard:updatePing', function(connectedPlayers)
SendNUIMessage({
action = 'updatePing',
players = connectedPlayers
})
end)
RegisterNetEvent('yrp_scoreboard:toggleID')
AddEventHandler('yrp_scoreboard:toggleID', function(state)
if state then
idVisable = state
else
idVisable = not idVisable
end
SendNUIMessage({
action = 'toggleID',
state = idVisable
})
end)
RegisterNetEvent('uptime:tick')
AddEventHandler('uptime:tick', function(uptime)
SendNUIMessage({
action = 'updateServerInfo',
uptime = uptime
})
end)
function UpdatePlayerTable(connectedPlayers)
local formattedPlayerList, num = {}, 1
local players = 0
for k,v in pairs(connectedPlayers) do
if num == 1 then
table.insert(formattedPlayerList, ('<tr><td>%s</td><td>%s</td><td>%s</td>'):format(v.name, v.id, v.ping))
num = 2
elseif num == 2 then
table.insert(formattedPlayerList, ('<td>%s</td><td>%s</td><td>%s</td>'):format(v.name, v.id, v.ping))
num = 3
elseif num == 3 then
table.insert(formattedPlayerList, ('<td>%s</td><td>%s</td><td>%s</td>'):format(v.name, v.id, v.ping))
num = 4
elseif num == 4 then
table.insert(formattedPlayerList, ('<td>%s</td><td>%s</td><td>%s</td></tr>'):format(v.name, v.id, v.ping))
num = 1
end
players = players + 1
if Config.general_config_settings.active_ems then
if v.job == 'ambulance' then
ems = "<i><div class='jobs ems fas fa-ambulance'></div></i>"
else
ems = ("<i><div class='jobsisnotonline ems fas fa-ambulance'></div></i>")
end
end
if Config.general_config_settings.active_police then
if v.job == 'police' then
police = "<i><div class='jobs pd fas fa-bullhorn'></i>"
else
police = ("<i><div class='jobsisnotonline pd fas fa-bullhorn'></div></i>")
end
end
if Config.general_config_settings.active_taxi then
if v.job == 'taxi' then
taxi = "<i><div class='jobs taxi fas fa-taxi'></div></i>"
else
taxi = ("<i><div class='jobsisnotonline taxi fas fa-taxi'></div></i>")
end
end
if Config.general_config_settings.active_mechanic then
if v.job == 'mechanic' or v.job == 'bennys' then
mechanic = "<i><div class='jobs mech fas fa-wrench'></div></i>"
else
mechanic = ("<i><div class='jobsisnotonline mech fas fa-wrench'></div></i>")
end
end
if Config.general_config_settings.active_miner then
if v.job == 'miner' then
miner = "<i><div class='jobs miner far fa-gem'></div></i>"
else
miner = ("<i><div class='jobsisnotonline miner far fa-gem'></div></i>")
end
end
if Config.general_config_settings.active_farmer then
if v.job == 'farmer' then
farmer = "<i><div class='jobs farmer fas fa-tractor'></div></i>"
else
farmer = ("<i><div class='jobsisnotonline farmer fas fa-tractor'></div></i>")
end
end
if Config.general_config_settings.active_fisherman then
if v.job == 'fisherman' then
fisherman = "<i><div class='jobs fisherman fas fa-fish'></div></i>"
else
fisherman = ("<i><div class='jobsisnotonline fisherman fas fa-fish'></div></i>")
end
end
if Config.general_config_settings.active_trucker then
if v.job == 'trucker' then
trucker = "<i><div class='jobs trucker fas fa-truck'></div></i>"
else
trucker = ("<i><div class='jobsisnotonline trucker fas fa-truck'></div></i>")
end
end
if Config.general_config_settings.illegal_actions then
if v.job == 'police' then
text = '<div class="illegal_actions"><h2> illegal actions are <i class="fas fa-check-circle"></i> </h2></div>'
else
text = '<div class="illegal_actions"><h2> illegal actions are <i class="fas fa-times-circle"></i> </h2></div>'
end
end
end
if num == 1 then
table.insert(formattedPlayerList, '</tr>')
end
SendNUIMessage({
action = 'updatePlayerList',
players = table.concat(formattedPlayerList)
})
SendNUIMessage({
action = 'updatePlayerJobs',
jobs = {ems = ems, police = police, taxi = taxi, mechanic = mechanic, miner = miner, farmer = farmer, fisherman = fisherman, trucker = trucker, player_count = players}
})
SendNUIMessage({
action = 'updateIllegalActions',
text = {text = text}
})
end
Citizen.CreateThread(function()
while true do
Citizen.Wait(1)
if IsControlJustReleased(0, Keys['DELETE']) and IsInputDisabled(0) then
ToggleScoreBoard()
Citizen.Wait(100)
-- D-pad up on controllers works, too!
elseif IsControlJustReleased(0, 172) and not IsInputDisabled(0) then
ToggleScoreBoard()
Citizen.Wait(200)
end
end
end)
-- Close scoreboard when game is paused
Citizen.CreateThread(function()
while true do
Citizen.Wait(500)
if IsPauseMenuActive() and not IsPaused then
IsPaused = true
SendNUIMessage({
action = 'close'
})
elseif not IsPauseMenuActive() and IsPaused then
IsPaused = false
end
end
end)
function ToggleScoreBoard()
SendNUIMessage({
action = 'toggle'
})
end
Citizen.CreateThread(function()
local playMinute, playHour = 0, 0
while true do
Citizen.Wait(2000 * 60) -- every minute
playMinute = playMinute + 1
if playMinute == 60 then
playMinute = 0
playHour = playHour + 1
end
SendNUIMessage({
action = 'updateServerInfo',
playTime = string.format("%02dh %02dm", playHour, playMinute)
})
end
end)
|
------------------------------------------------------------------------
-- brill.lua
-- Copyright 2021 Martin Sievers
--
-- This work may be distributed and/or modified under the
-- conditions of the LaTeX Project Public License, either version 1.3
-- of this license or (at your option) any later version.
-- The latest version of this license is in
-- http://www.latex-project.org/lppl.txt
-- and version 1.3 or later is part of all distributions of LaTeX
-- version 2005/12/01 or later.
--
-- This work has the LPPL maintenance status `maintained'.
--
-- The Current Maintainer of this work is Martin Sievers
--
-- This work consists of the files
-- brill.cls
-- brill.lua
-- CorpusAvesticum.tex
-- muya.bbx
-- muya.cbx
-- muya.dbx
-- muya.lua
-- xindex-brill.lua
-- xindex-muya.lua
-- xindex-muyaPassages.lua
--
-- 2021/06/20 v0.90.0
function my_upper ( str )
local z = ''
local sectioncmd = ''
local argument = ''
print ('AAA' .. str .. 'BBB')
sectioncmd, argument = string.match (str, "^([^{]-){(.+)}$")--$
print ('AAA' .. sectioncmd .. 'BBB')
-- First, replace all spaces within a pair of braces with \0 to differentiate
-- them from whitespace outside.
for s in argument:gsub("(%{.-%})", function(x) return x:gsub("%s+", "DDD") end):gmatch "%S+"
do
z = z .. s:gsub("%z+", " ")
end
-- First, uppercase all starting lowercase letters ('%l' in Lua jargon)
-- "starting": %l is preceded by whitespace, {, or [
-- z = z:gsub ( "[%s%[]%l" , string.upper )
-- z = z:gsub ( "%s%l" , string.upper )
-- Next, undo upper-casing for some words
-- z = z:gsub ( "\0 " , ' ')
z = z:gsub ( " A " , string.lower )
z = z:gsub ( " An " , string.lower )
z = z:gsub ( " The " , string.lower )
z = z:gsub ( " And " , string.lower )
z = z:gsub ( " As " , string.lower )
z = z:gsub ( " At " , string.lower )
z = z:gsub ( " But " , string.lower )
z = z:gsub ( " By " , string.lower )
z = z:gsub ( " For " , string.lower )
z = z:gsub ( " Or " , string.lower )
z = z:gsub ( " Nor " , string.lower )
z = z:gsub ( " Van " , string.lower )
z = z:gsub ( " De " , string.lower )
z = z:gsub ( " In " , string.lower )
z = z:gsub ( " on " , string.lower )
z = z:gsub ( " Of " , string.lower )
z = z:gsub ( " To " , string.lower )
-- z = sectioncmd .. "{" .. z .. "}"
return z
end
function do_titlecasing ( s )
s = s:gsub ( "\\chapter%*?%s*%b[]%s*%b{}", my_upper )
s = s:gsub ( "\\chapter%*?%s*%b{}", my_upper )
s = s:gsub ( "\\addchap%*?%s*%b[]%s*%b{}", my_upper )
s = s:gsub ( "\\section%*?%s*%b{}", my_upper )
s = s:gsub ( "\\section%*?%s*%b[]%s*%b{}", my_upper )
s = s:gsub ( "\\addsec%*?%s*%b{}", my_upper )
s = s:gsub ( "\\subsection%*?%s*%b[]%s*%b{}", my_upper )
s = s:gsub ( "\\subsection%*?%s*%b{}", my_upper )
s = s:gsub ( "\\addsubsec%*?%s*%b[]%s*%b{}", my_upper )
s = s:gsub ( "\\subsubsection%*?%s*%b[]%s*%b{}", my_upper )
s = s:gsub ( "\\subsubsection%*?%s*%b{}", my_upper )
s = s:gsub ( "\\addsubsubsec%*?%s*%b{}", my_upper )
s = s:gsub ( "\\subthreesection%*?%s*%b[]%s*%b{}", my_upper )
s = s:gsub ( "\\subthreesection%*?%s*%b{}", my_upper )
s = s:gsub ( "\\subfoursection%*?%s*%b[]%s*%b{}", my_upper )
s = s:gsub ( "\\subfoursection%*?%s*%b{}", my_upper )
s = s:gsub ( "\\subfivesection%*?%s*%b[]%s*%b{}", my_upper )
s = s:gsub ( "\\subfivesection%*?%s*%b{}", my_upper )
s = s:gsub ( "\\minisec%*?%s*%b{}", my_upper )
return s
end
|
local mail = require "resty.mail"
print("Start")
local mailer, err = mail.new({
host = "mail.codimeo.com",
port = 587,
starttls = true,
-- AUTH type ne fonctionne pas avec servage.net
--auth_type = 'login',
username = "nizar.ayed@codimeo.com",
password = "11Janvier1996",
})
if err then
print("mail.new error: " .. err)
ngx.log(ngx.ERR, "mail.new error: ", err)
return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
else
print(mailer.options.host)
end
local ok, err = mailer:send({
from = "Master Splinter <noreply@meo.codimeo.com>",
to = { "nizar.ayed@upgrade-code.org" },
subject = "Pizza is here!",
text = "There's pizza in the sewer.",
html = "<h1>There's pizza in the sewer.</h1>",
attachments = {
{
filename = "toppings.txt",
content_type = "text/plain",
content = "1. Cheese\n2. Pepperoni",
},
},
})
if err then
print("mail.send error: " .. err)
ngx.log(ngx.ERR, "mailer:send error: ", err)
return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
elseif ok then
print("email sent ")
end
|
shell.run("rm startup")
print("Arquivo \"startup\" deletado.")
print("Digite a chave do pastebin:")
inputTerm = read()
shell.run("pastebin get ",inputTerm," startup")
print("Reiniciando computador ...")
shell.run("reboot")
|
if not modules then modules = { } end modules ['mtx-youless'] = {
version = 1.002,
comment = "script to fetch data from kwh meter polling device",
author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright = "PRAGMA ADE",
license = "see context related readme files"
}
-- This script can fetch data from a youless device (http://www.youless.nl/) where data
-- is merged into a file. The data concerns energy consumption (current wattage as well
-- as kwh usage). There is an accompanying module to generate graphics.
require("util-you")
local formatters = string.formatters
-- the script
local helpinfo = [[
<?xml version="1.0"?>
<application>
<metadata>
<entry name="name">mtx-youless</entry>
<entry name="detail">youless Fetcher</entry>
<entry name="version">1.00</entry>
</metadata>
<flags>
<category name="basic">
<subcategory>
<flag name="collect"><short>collect data from device</short></flag>
<flag name="nobackup"><short>don't backup old datafile</short></flag>
<flag name="nofile"><short>don't write data to file (for checking)</short></flag>
<flag name="kwh"><short>summative kwh data</short></flag>
<flag name="watt"><short>collected watt data</short></flag>
<flag name="host"><short>ip address of device</short></flag>
</subcategory>
</category>
</flags>
<examples>
<category>
<title>Example</title>
<subcategory>
<example><command>mtxrun --script youless --collect --host=192.168.2.50 --kwh</command></example>
<example><command>mtxrun --script youless --collect --host=192.168.2.50 --watt somefile.lua</command></example>
</subcategory>
</category>
</examples>
</application>
]]
local application = logs.application {
name = "mtx-youless",
banner = "YouLess Fetcher 1.00",
helpinfo = helpinfo,
}
local report = application.report
scripts = scripts or { }
scripts.youless = scripts.youless or { }
function scripts.youless.collect()
local host = environment.arguments.host
local variant = environment.arguments.kwh and "kwh" or environment.arguments.watt and "watt"
local nobackup = environment.arguments.nobackup
local nofile = environment.arguments.nofile
local password = environment.arguments.password
local filename = environment.files[1]
if not variant then
report("provide variant --kwh or --watt")
return
else
report("using variant %a",variant)
end
if not host then
host = "192.168.2.50"
report("using default host %a",host)
else
report("using host %a",host)
end
if nobackup then
report("not backing up data file")
end
if not filename and not nofile then
filename = formatters["youless-%s.lua"](variant)
end
if filename ~= "" then
report("using file %a",filename)
end
local data = utilities.youless.collect {
filename = filename,
host = host,
variant = variant,
nobackup = nobackup,
password = password,
}
if type(data) ~= "table" then
report("no data collected")
elseif filename == "" then
report("data collected but not saved")
end
report("current time %a",os.now())
end
if environment.argument("collect") then
scripts.youless.collect()
elseif environment.argument("exporthelp") then
application.export(environment.argument("exporthelp"),environment.files[1])
else
application.help()
end
|
--------------------------------------------------------------------------------
-- Mob Framework Settings Mod by Sapier
--
-- You may copy, use, modify or do nearly anything except removing this
-- copyright notice.
-- And of course you are NOT allowed to pretend you have written it.
--
--! @file tab_restore_mobs.lua
--! @brief settings gui for mobf
--! @copyright Sapier
--! @author Sapier
--! @date 2014-05-30
--
-- Contact sapier a t gmx net
--------------------------------------------------------------------------------
local function get_formspec(tabview, name, tabdata)
if tabdata.selected_entry == nil then
tabdata.selected_entry = 0
end
local tablehead = "Mobtype,Reason,Owner,"
local content = ""
for n=1,#mobf.current_preserve_list, 1 do
if mobf.current_preserve_list[n].owner == tabdata.playername or
tabdata.is_admin then
content = content ..
mobf.current_preserve_list[n].modname .. ":" ..
mobf.current_preserve_list[n].name .. "," ..
mobf.current_preserve_list[n].reason .. "," ..
mobf.current_preserve_list[n].owner
if n ~= #mobf.current_preserve_list then
content = content .. ","
end
end
end
local retval =
"tablecolumns[text,width=16;text,width=25;text,width=6]" ..
"table[0.25,0.25;11.25,8;tbl_lost_and_found;" .. tablehead .. content .. ";"
.. tabdata.selected_entry .. "]"
if tabdata.selected_entry ~= 0 then
retval = retval ..
"button[0.25,8.5;3.75,0.5;btn_restore_mob;" .. fgettext("Take") .. "]"
end
return retval
end
local function handle_settings_buttons(self, fields, tabname, tabdata)
if fields["tbl_lost_and_found"] then
local event = core.explode_table_event(fields["tbl_lost_and_found"])
if event.type == "CHG" then
tabdata.selected_entry = event.row
end
return true;
end
if fields["btn_restore_mob"] then
local elementcount = 0
local player = core.get_player_by_name(tabdata.playername)
if not player then
return true
end
for i=1,#mobf.current_preserve_list,1 do
mobf_assert_backtrace(tabdata ~= nil)
mobf_assert_backtrace(mobf.current_preserve_list[i] ~= nil)
if mobf.current_preserve_list[i].owner == tabdata.playername or
tabdata.isadmin then
elementcount = elementcount +1
end
if elementcount == (tabdata.selected_entry-1) then
--ADD to inventory
local inventory_add_result = player:get_inventory():add_item("main",
mobf.current_preserve_list[i].modname ..":"..
mobf.current_preserve_list[i].name.." 1")
--remove from list
if inventory_add_result:is_empty() then
table.remove(mobf.current_preserve_list,i)
mobf_set_world_setting("mobf_preserve_mobs",
core.serialize(mobf.current_preserve_list))
end
return true
end
end
return true
end
return false
end
mobf_settings_tab_preserve = {
name = "preserve",
caption = fgettext("Lost mobs"),
cbf_formspec = get_formspec,
cbf_button_handler = handle_settings_buttons,
tabsize = {width=12,height=9}
}
|
local E, C, L = select(2, ...):unpack()
if not C.actionbar.bars.enable then return end
----------------------------------------------------------------------------------------
-- ActionBar (modified from ShestakUI)
----------------------------------------------------------------------------------------
local _G = _G
local CreateFrame = CreateFrame
local GetActionTexture = GetActionTexture
local RegisterStateDriver = RegisterStateDriver
local unpack = unpack
local UIParent = _G.UIParent
local cfg = C.actionbar.bars.bar1
local num = NUM_ACTIONBAR_BUTTONS
local bar = CreateFrame("Frame", "DarkUI_ActionBar1Holder", UIParent, "SecureHandlerStateTemplate")
bar:SetPoint(unpack(cfg.pos))
bar:SetHeight(cfg.button.size)
bar:SetWidth(num * cfg.button.size + (num - 1) * cfg.button.space)
for i = 1, num do
local button = _G["ActionButton" .. i]
button:SetSize(cfg.button.size, cfg.button.size)
button:ClearAllPoints()
button:SetParent(bar)
if i == 1 then
button:SetPoint("BOTTOMLEFT", bar, 0, 0)
else
local previous = _G["ActionButton" .. i - 1]
button:SetPoint("LEFT", previous, "RIGHT", cfg.button.space, 0)
end
end
local Page = {
["DRUID"] = "[bonusbar:1,nostealth] 7; [bonusbar:1,stealth] 8; [bonusbar:2] 8; [bonusbar:3] 9; [bonusbar:4] 10;",
["ROGUE"] = "[bonusbar:1] 7;",
["DEFAULT"] = "[possessbar] 12; [shapeshift] 13; [overridebar] 14; [vehicleui] 12; [bar:2] 2; [bar:3] 3; [bar:4] 4; [bar:5] 5; [bar:6] 6;",
}
local function GetBar()
local condition = Page["DEFAULT"]
local class = E.class
local page = Page[class]
if page then
condition = condition .. " " .. page
end
condition = condition .. " 1"
return condition
end
bar:RegisterEvent("PLAYER_LOGIN")
bar:RegisterEvent("UPDATE_VEHICLE_ACTIONBAR")
bar:RegisterEvent("UPDATE_OVERRIDE_ACTIONBAR")
bar:SetScript("OnEvent", function(self, event)
if event == "PLAYER_LOGIN" then
for i = 1, num do
local button = _G["ActionButton" .. i]
self:SetFrameRef("ActionButton" .. i, button)
end
self:Execute([[
buttons = table.new()
for i = 1, 12 do
table.insert(buttons, self:GetFrameRef("ActionButton"..i))
end
]])
self:SetAttribute("_onstate-page", [[
for i, button in ipairs(buttons) do
button:SetAttribute("actionpage", tonumber(newstate))
end
]])
RegisterStateDriver(self, "page", GetBar())
elseif event == "UPDATE_VEHICLE_ACTIONBAR" or event == "UPDATE_OVERRIDE_ACTIONBAR" then
for i = 1, num do
local button = _G["ActionButton" .. i]
local action = button.action
local icon = button.icon
if action >= 120 then
local texture = GetActionTexture(action)
if texture then
icon:SetTexture(texture)
icon:Show()
else
if icon:IsShown() then
icon:Hide()
end
end
end
end
end
end)
|
-- This file is subject to copyright - contact swampservers@gmail.com for more information.
-- INSTALL: CINEMA
SWEP.Base = "weapon_popcorn"
SWEP.PrintName = "Sandcorn"
|
local part = workspace.FloatingPart
local mass = part:GetMass()
local attachment = Instance.new("Attachment")
attachment.Parent = part
local vectorForce = Instance.new("VectorForce")
vectorForce.Force = Vector3.new(0,mass * workspace.Gravity,0)
vectorForce.Attachment0 = attachment
vectorForce.Parent = part
local part = workspace.TouchPart
part.Touched:Connect(function(hit)
print(hit)
end)
local part = workspace.TouchPart
local function printHitName(hit)
print(hit)
end
part.Touched:Connect(printHitName)
|
--[[
2020-2021 Xalalau Xubilozo. MIT License
https://xalalau.com/
--]]
-- Live reload the addon when a file is modified
-- Note: UNSAFE! BS will be rebuilt itself exposed to the common addons environment and there may come detoured functions
function BS:LiveReloading_Set()
local name = "BS_LiveReloading"
if self.devMode and not timer.Exists(name) then
timer.Create(name, 0.2, 0, function()
for k,v in pairs(self:Utils_GetFilesCreationTimes()) do
if v ~= self.filenames[k] then
MsgC(self.colors.reload, self.alert .. " Reloading...\n")
self:Detours_Remove()
self.reloaded = true
self.__G.BS_reloaded = true
timer.Simple(0.01, function()
include("bs/init.lua")
self.__G.BS_reloaded = nil
end)
timer.Remove(name)
end
end
end)
end
end
|
return { sharp = { 15, 9, 12, 20 }, sharpp = { 15, 9, 12, 31 } }
|
-- A util library for bgfx examples
local util = {}
local iup = require "iuplua"
local bgfx = require "bgfx"
local math3d = require "math3d"
local adapter = require "mathadapter"
local function save_ppm(filename, data, width, height, pitch)
local f = assert(io.open(filename, "wb"))
f:write(string.format("P3\n%d %d\n255\n",width, height))
local line = 0
for i = 0, height-1 do
for j = 0, width-1 do
local r,g,b,a = string.unpack("BBBB",data,i*pitch+j*4+1)
f:write(r," ",g," ",b," ")
line = line + 1
if line > 8 then
f:write "\n"
line = 0
end
end
end
f:close()
end
local function save_screenshot(filename)
local name , width, height, pitch, data = bgfx.get_screenshot()
if name then
local size = #data
if size < width * height * 4 then
-- not RGBA
return
end
print("Save screenshot to ", filename)
save_ppm(filename, data, width, height, pitch)
end
end
local shader_path
local function init_shader_path(caps)
local path = {
NOOP = "dx9",
DIRECT3D9 = "dx9",
DIRECT3D11 = "dx11",
DIRECT3D12 = "dx11",
GNM = "pssl",
METAL = "metal",
OPENGL = "glsl",
OPENGLES = "essl",
VULKAN = "spirv",
}
shader_path = "shaders/".. (assert(path[caps.rendererType])) .."/"
end
do
local function load_shader(name)
local filename = shader_path .. name .. ".bin"
local f = assert(io.open(filename, "rb"))
local data = f:read "a"
f:close()
local h = bgfx.create_shader(data)
bgfx.set_name(h, filename)
return h
end
local function load_shader_uniforms(name)
local h = load_shader(name)
local uniforms = bgfx.get_shader_uniforms(h)
return h, uniforms
end
local function uniform_info(uniforms, handles)
for _, h in ipairs(handles) do
local name, type, num = bgfx.get_uniform_info(h)
if uniforms[name] == nil then
uniforms[name] = { handle = h, name = name, type = type, num = num }
end
end
end
local function programLoadEx(vs,fs, uniform)
local vsid, u1 = load_shader_uniforms(vs)
local fsid, u2
if fs then
fsid, u2 = load_shader_uniforms(fs)
end
uniform_info(uniform, u1)
if u2 then
uniform_info(uniform, u2)
end
return bgfx.create_program(vsid, fsid, true), uniform
end
function util.programLoad(vs,fs, uniform)
if uniform then
return programLoadEx(vs,fs, uniform)
else
local vsid = load_shader(vs)
local fsid = fs and load_shader(fs)
return bgfx.create_program(vsid, fsid, true)
end
end
function util.computeLoad(cs)
local csid = load_shader(cs)
return bgfx.create_program(csid, true)
end
end
do
local mesh_decode = {}
local vb_header = "<" .. string.rep("f", 4+6+16)
-- local vb_data = { "!", "", nil, nil }
-- local ib_data = { "", nil, nil }
local function read_mesh_header(group, data, offset)
local tmp = { string.unpack(vb_header, data, offset) }
group.sphere = { table.unpack(tmp,1,4) }
group.aabb = { table.unpack(tmp,5,10) }
group.obb = { table.unpack(tmp,11,26) }
return tmp[27]
end
mesh_decode["VB \1"] = function(mesh, group, data, offset)
offset = read_mesh_header(mesh, data, offset)
local stride, numVertices
mesh.vdecl, stride, offset = bgfx.vertex_layout(data, offset)
numVertices, offset = string.unpack("<I2", data, offset)
local size = stride * numVertices
local vb_data = bgfx.memory_buffer(data, offset, size)
group.vb = bgfx.create_vertex_buffer(vb_data, mesh.vdecl)
return offset + size
end
mesh_decode["IB \0"] = function(mesh, group, data, offset)
local numIndices
numIndices, offset = string.unpack("<I4", data, offset)
local size = numIndices * 2
local ib_data = bgfx.memory_buffer(data, offset, size)
group.ib = bgfx.create_index_buffer(ib_data)
return offset + size
end
mesh_decode["IBC\0"] = function(mesh, group, data, offset)
error "Unsupport Compressed IB"
end
mesh_decode["PRI\0"] = function(mesh, group, data, offset)
local material, num
material, num, offset = string.unpack("<s2I2", data, offset) -- no used
group.prim = {}
for i=1,num do
local p = {}
p.name, p.startIndex, p.numIndices, p.startVertex, p.numVertices, offset = string.unpack("<s2I4I4I4I4", data, offset)
offset = read_mesh_header(p, data, offset)
table.insert(group.prim, p)
end
local tmp = {}
for k,v in pairs(group) do
group[k] = nil
tmp[k] = v
end
table.insert(mesh.group, tmp)
return offset
end
function util.meshLoad(filename)
local f = assert(io.open(filename,"rb"))
local data = f:read "a"
f:close()
local mesh = { group = {} }
local offset = 1
local group = {}
while true do
local tag = data:sub(offset, offset+3)
if tag == "" then
break
end
local decoder = mesh_decode[tag]
if not decoder then
error ("Invalid tag " .. tag)
end
offset = decoder(mesh, group, data, offset + 4)
end
return mesh
end
end
function util.meshUnload(mesh)
for _,group in ipairs(mesh.group) do
bgfx.destroy(group.ib)
bgfx.destroy(group.vb)
end
end
function util.meshSubmit(mesh, id, prog)
local g = mesh.group
local n = #g
for i=1,n do
local group = g[i]
bgfx.set_index_buffer(group.ib)
bgfx.set_vertex_buffer(group.vb)
bgfx.submit(id, prog, 0, i ~= n and "" or "ivs")
end
end
function util.meshSubmitState(mesh, state, mtx)
bgfx.set_transform(mtx)
bgfx.set_state(state.state)
for _, texture in ipairs(state.textures) do
bgfx.set_texture(texture.stage,texture.sampler,texture.texture,texture.flags)
end
local g = mesh.group
local n = #g
for i=1,n do
local group = g[i]
bgfx.set_index_buffer(group.ib)
bgfx.set_vertex_buffer(group.vb)
bgfx.submit(state.viewId, state.program, 0, i ~= n and "" or "ivs")
end
end
function util.textureLoad(filename, info)
local f = assert(io.open(filename, "rb"))
local imgdata = f:read "a"
f:close()
local h = bgfx.create_texture(imgdata, info)
bgfx.set_name(h, filename)
return h
end
local init_flag
function util.init(args)
local canvas = assert(args.canvas)
local function init()
bgfx.init {
renderer = args.renderer,
format = args.format,
width = args.width,
height = args.height,
reset = args.reset,
debug = args.debug,
profile = args.profile,
getlog = args.getlog,
numBackBuffers = args.numBackBuffers,
maxFrameLatency = args.maxFrameLatency,
-- platform data
ndt = args.ndt,
nwh = iup.GetAttributeData(canvas,"HWND"),
context = args.context,
backBuffer = args.backBuffer,
backBufferDS = args.backBufferDS,
}
util.caps = bgfx.get_caps()
math3d.set_homogeneous_depth(util.caps.homogeneousDepth)
init_shader_path(util.caps)
init_flag = true
bgfx.set_debug "T"
end
function canvas:resize_cb(w,h)
if init_flag == nil then
init()
if args.init then
args.init(w,h)
end
init_flag = true
end
if args.resize then
args.resize(w,h)
end
end
local debug
function canvas:keypress_cb(key, press)
if press == 0 then
return
end
if key == iup.K_F1 then
debug = not debug
bgfx.set_debug(debug and "ST" or "T")
elseif key == iup.K_F12 then
bgfx.request_screenshot()
end
end
end
function util.run(f)
iup.SetIdle(function ()
assert(init_flag)
save_screenshot "screenshot.ppm"
local ok , err = xpcall(f, debug.traceback)
if not ok then
print(err)
iup.SetIdle()
end
return iup.DEFAULT
end)
iup.MainLoop()
iup.Close()
if init_flag then
bgfx.shutdown()
end
end
return util
|
local Packages = script.Parent.Parent.Parent.Parent.Parent.Parent
local Roact = require(Packages.Roact)
local Core = Packages.UIBlox.Core
local withStyle = require(Core.Style.withStyle)
local App = Packages.UIBlox.App
local CheckboxList = require(App.InputButton.CheckboxList)
local MulitlineCheckboxDemo = Roact.PureComponent:extend("MulitlineCheckboxDemo")
function MulitlineCheckboxDemo:render()
return withStyle(function(style)
return Roact.createElement(CheckboxList, {
atMost = 3,
checkboxes = {
{
label = "Selected and Disabled",
isSelected = true,
isDisabled = true,
},
{
label = "Unselected and Disabled",
isSelected = false,
isDisabled = true,
},
{
label = "Selected and Enabled",
isSelected = true,
isDisabled = false,
},
"Unselected and Enabled",
"This is a checkbox that has an absurd amount of text in its label to demonstrate wrapping",
},
onActivated = function() end,
elementSize = UDim2.new(0, 400, 0, 60),
layoutOrder = 1,
})
end)
end
return {
summary = "This CheckboxList can have up to 3 boxes selected at a time",
story = MulitlineCheckboxDemo,
}
|
--
-- Created by IntelliJ IDEA.
-- User: Kunkka
-- Date: 7/20/17
-- Time: 09:37
-- To change this template use File | Settings | File Templates.
--
DEBUG = 2
-- use framework, will disable all deprecated API, false - use legacy API
CC_USE_FRAMEWORK = true
|
return {'eldorado','elders','eldorado','elders','eldering','elderhorst','elderson','elderkamp','elderman','eldorados'}
|
------------------------------------------------------------------------
-- muya.lua
-- Copyright 2018-2021 Martin Sievers
--
-- This work may be distributed and/or modified under the
-- conditions of the LaTeX Project Public License, either version 1.3
-- of this license or (at your option) any later version.
-- The latest version of this license is in
-- http://www.latex-project.org/lppl.txt
-- and version 1.3 or later is part of all distributions of LaTeX
-- version 2005/12/01 or later.
--
-- This work has the LPPL maintenance status `maintained'.
--
-- The Current Maintainer of this work is Martin Sievers
--
-- This work consists of the files
-- brill.cls
-- brill.lua
-- CorpusAvesticum.tex
-- muya.bbx
-- muya.cbx
-- muya.dbx
-- muya.lua
-- xindex-brill.lua
-- xindex-muya.lua
-- xindex-muyaPassages.lua
--
-- 2021/09/11 v0.95.0
local ustring = require( 'ustring' )
function modifySorting()
local match = ''
local n = 0
local g = io.open( "passages-mod.idx", "w+" )
-- for starred index macros like \Passages*
-- TODO: What about letters within the passage id?
for line in io.lines( "passages.idx" ) do
--texio.write_nl("Vorher: " .. line)
match, n = string.gsub( line,
"\\gls%s*{([^}]*)}\\nobreak%s*\\hspace%s*{\\fontdimen 2\\font%s*}([%-%.%d%a]+)@\\textup%s*{.+}|",
function(a,b) return get_sortentry_star( a, b ) end )
if n == 0 then
-- now for unstarred variant
match, n = string.gsub( line,
"\\gls%s*{([^}]*)}\\nobreak%s*\\hspace%s*{\\fontdimen 2\\font%s*}([%-%.%d%a]+)|",
function( a, b ) return get_sortentry( a, b ) end )
end
--texio.write_nl("Treffer: " .. n)
--texio.write_nl("Nachher: " .. match)
g:write(match .. "\n")
-- f:close()
end
g:close()
end
function get_sortentry( a, b )
-- we have to analyse b to get a correct sort string
local res = ""
if b:match( "^%d+$" ) then
res = res .. string.format( "%03d", b ) .. ".000"
else
for v, w in string.gmatch( b, "(%d+)([%-%.]*)" ) do
res = res .. string.format( "%03d%s", v, w )
end
for last in string.gmatch( b, ".+[%-%.]([^%-%.]+)$" ) do
if last:match( "^%d+$" ) then
res = res .. string.format( "%03d", last )
else
res = res .. last
end
end
end
return string.format( "%s%s@%s\\nobreak\\hspace{\\fontdimen 2\\font}%s|", a, res, a, b )
end
function get_sortentry_star( a, b )
-- we have to analyse b to get a correct sort string
local res = ""
if b:match( "^%d+$" ) then
res = res .. string.format( "%03d", b ) .. ".000"
else
for v, w in string.gmatch( b, "(%d+)([%-%.])" ) do
res = res .. string.format( "%03d%s", v, w )
end
for last in string.gmatch( b, ".+[%-%.]([^%-%.]+)$" ) do
if last:match( "^%d+$" ) then
res = res .. string.format( "%03d", last )
else
res = res .. last
end
end
end
return string.format( "%s%s@%s\\nobreak\\hspace{\\fontdimen 2\\font}\\textup{%s}|", a, res, a, b )
end
-- see if the file exists
function file_exists( file )
local f = io.open( file, "rb" )
if f then f:close() end
return f ~= nil
end
-- get all lines from a file, returns an empty
-- list/table if the file does not exist
function lines_from( file )
if not file_exists( file ) then return {} end
lines = {}
for line in io.lines( file ) do
lines[#lines + 1] = line
end
return lines
end
function sortGlossary( l )
-- tests the functions above
local file = status.filename
local outfile = 'dictionaryconv.tex'
if l == nil or l == '' then
texio.write_nl( "Glossary language must not be empty" )
else
glosslang = l
--texio.write_nl( "Found sorting language: " .. glosslang )
end
if not file_exists( file ) then return {} end
local lines = lines_from( file )
local text = ""
local sublemmatext = ""
local subsublemmatext = ""
local subsubsublemmatext = ""
--local str = ""
local prevlemma = ""
local prevsublemma = ""
local prevsublemmastar = ""
local prevsubsublemma = ""
local prevsubsublemmastar = ""
local prevsubsubsublemma = ""
local prevsubsubsublemmastar = ""
local lemma = ""
local sublemma = ""
local subsublemma = ""
local subsubsublemma = ""
local lemmacontent = ""
local sublemmacontent = ""
local sublemmastarcontent = ""
local subsublemmacontent = ""
local subsublemmastarcontent = ""
local subsubsublemmacontent = ""
local subsubsublemmastarcontent = ""
--
local result = {}
local sl = {}
local slstar = {}
local ssl = {}
local sslstar = {}
local sssl = {}
local ssslstar = {}
--
local is_sublemmastar = false
local is_subsublemmastar = false
local is_subsubsublemmastar = false
--
local newkeys = {}
local is_indictionary = false
local is_insublemmata = false
local is_insubsublemmata = false
local is_insubsubsublemmata = false
local f = assert( io.open(outfile, "w+") )
local hash = {}
local res = {}
-- we define a loop routine for each possible language
-- Gujarati
if glosslang == "Guj" then
for k, v in pairs( lines ) do
-- get line k and process it
local str = lines[k]
if string.match( str, "^%s*\\begin{Dictionary}" ) then
f:write( "\\begin{ModDictionary}" )
is_indictionary = true
elseif string.match( str, "^%s*\\begin{Sublemmata}" ) then
is_insublemmata = true
-- Write line to top-level structure
sublemmacontent = "\n\\begin{Sublemmata}\n"
-- define empty tables for sublemmata environment
sl = {}
slstar = {}
elseif string.match( str, "^%s*\\begin{Subsublemmata}" ) then
is_insubsublemmata = true
-- Write line to top-level structure
subsublemmacontent = "\n\\begin{Subsublemmata}\n"
-- define empty tables for sublemmata environment
ssl = {}
sslstar = {}
elseif string.match( str, "^%s*\\begin{Subsubsublemmata}" ) then
is_insubsubsublemmata = true
-- Write line to top-level structure
subsubsublemmacontent = "\n\\begin{Subsubsublemmata}\n"
-- define empty tables for sublemmata environment
sssl = {}
ssslstar = {}
elseif string.match( str, "^%s*\\end{Subsubsublemmata}" ) then
if next( ssslstar ) ~= nil then
subsubsublemmastarcontent = ''
local lastval = sssl[prevsubsubsublemma]
ssslstar[prevsubsubsublemma] = lastval
sssl[prevsubsubsublemma] = nil
newkeys = sortLemma( ssslstar )
local firstentry = true
for _, k in ipairs( newkeys ) do
if firstentry == true then
sssl[k] = ssslstar[k]
firstentry = false
prevsubsubsublemma = k
else
subsubsublemmastarcontent = subsubsublemmastarcontent .. "\n" ..
'\\Subsubsublemma*{' .. removesortid( k ) .. '}' .. ssslstar[k]
end
end
local lastval = sssl[prevsubsubsublemma]
sssl[prevsubsubsublemma] = lastval .. subsubsublemmastarcontent
-- Empty table ssslstar
ssslstar = {}
end
newkeys = sortLemma( sssl )
for _, k in ipairs( newkeys ) do
subsubsublemmacontent = subsubsublemmacontent ..
'\\Subsubsublemma{' .. removesortid( k ) .. '}' .. sssl[k] .. "\n"
end
local lastval = ssl[prevsubsublemma]
ssl[prevsubsublemma] = lastval .. subsubsublemmacontent .. "\n\\end{Subsubsublemmata}"
is_insubsubsublemmata = false
elseif string.match( str, "^%s*\\end{Subsublemmata}" ) then
if next( sslstar ) ~= nil then
subsublemmastarcontent = ''
local lastval = ssl[prevsubsublemma]
sslstar[prevsubsublemma] = lastval
ssl[prevsubsublemma] = nil
newkeys = sortLemma( sslstar )
local firstentry = true
for _, k in ipairs( newkeys ) do
if firstentry == true then
ssl[k] = sslstar[k]
firstentry = false
prevsubsublemma = k
else
subsublemmastarcontent = subsublemmastarcontent .. "\n" ..
'\\Subsublemma*{' .. removesortid( k ) .. '}' .. sslstar[k]
end
end
local lastval = ssl[prevsubsublemma]
ssl[prevsubsublemma] = lastval .. subsublemmastarcontent
-- Empty table slstar
sslstar = {}
end
newkeys = sortLemma( ssl )
for _, k in ipairs( newkeys ) do
subsublemmacontent = subsublemmacontent ..
'\\Subsublemma{' .. removesortid( k ) .. '}' .. ssl[k] .. "\n"
end
local lastval = sl[prevsublemma]
sl[prevsublemma] = lastval .. subsublemmacontent .. "\\end{Subsublemmata}"
is_insubsublemmata = false
elseif string.match( str, "^%s*\\end{Sublemmata}" ) then
--texio.write_nl("End sublemmata")
--[[
check whether last entry was a sublemma*.
Then we have to add slstar to the latest sublemma first
]]
if next( slstar ) ~= nil then
-- There are \Sublemma* to sort
sublemmastarcontent = ''
-- Add sublemma to table of sublemma* for sorting
local lastval = sl[prevsublemma]
slstar[prevsublemma] = lastval
-- Remove it from sublemma table
sl[prevsublemma] = nil
-- sort slstar
newkeys = sortLemma( slstar )
-- use the keys to retrieve the values in the sorted order
-- we write the sorted content to the top level structure
local firstentry = true
for _, k in ipairs( newkeys ) do
-- Put the first element back in sublemma table
if firstentry == true then
sl[k] = slstar[k]
firstentry = false
prevsublemma = k
-- All other elements are handeled as sublemma*
else
sublemmastarcontent = sublemmastarcontent .. "\n" ..
'\\Sublemma*{' .. removesortid( k ) .. '}' .. slstar[k]
end
end
-- put it into table with key of last \Sublemma
local lastval = sl[prevsublemma]
sl[prevsublemma] = lastval .. sublemmastarcontent
-- Empty table slstar
slstar = {}
end
-- now sort sublemma entries in sl table
newkeys = sortLemma( sl )
-- use the keys to retrieve the values in the sorted order
-- we write the sorted content to the top level structure
for _, k in ipairs( newkeys ) do
sublemmacontent = sublemmacontent ..
'\\Sublemma{' .. removesortid( k ) .. '}' .. sl[k] .. "\n"
end
lemmacontent = lemmacontent .. sublemmacontent .. "\\end{Sublemmata}"
is_insublemmata = false
elseif string.match( str, "^%s*\\end{Dictionary}" ) then
-- we reached the end of the dictionary
-- write last lemma to file
if prevlemma and prevlemma ~= '' then
result[prevlemma] = lemmacontent
end
-- start sorting process
newkeys = sortLemma( result )
-- use the keys to retrieve the values in the sorted order
for _, k in ipairs( newkeys ) do
f:write( '\n\\Lemma{' .. removesortid( k ) .. '}' .. result[k] )
-- get the first letter of the lemma
local first = ustring.sub( removesortid( k ), 1, 1 )
--texio.write_nl(first)
-- check whether the letter is already known and not -
if not hash[first] and first ~= "-" then
res[#res+1] = first
hash[first] = true
end
end
-- if lines follow they should be processed as well
f:write( '\n\\end{ModDictionary}', "\n" )
local sequenceofletters = ""
for k, v in pairs( res ) do
if sequenceofletters == "" then
sequenceofletters = v
else
sequenceofletters = sequenceofletters .. ", " .. v
end
end
tex.sprint( [[\makeatletter\immediate\write\@mainaux{\string\ifltxcounter{numberofglossaries}
{}{\string\newcounter{numberofglossaries}}\string\stepcounter{numberofglossaries}}\makeatother]] )
tex.sprint( [[\makeatletter\write\@mainaux{\string\csxdef{@sequenceofletters\arabic{numberofglossaries}}{]],sequenceofletters,"}}",[[\makeatother]] )
is_indictionary = false
else -- lines in-between environments
if is_indictionary == false then
else
if is_insubsubsublemmata == true then
subsubsublemma, subsubsublemmatext =
string.match( str, "^%s*\\Subsubsublemma%*(%b{})(.*)$" )--$
is_subsubsublemmastar = true
if not subsubsublemma or subsubsublemma == '' then
-- we check for unstarred version
subsubsublemma, subsubsublemmatext =
string.match( str, "^%s*\\Subsubsublemma(%b{})(.*)$" )--$
is_subsubsublemmastar = false
end
if subsubsublemma and subsubsublemma ~= '' then
-- we found a new subsubsublemma
subsubsublemma = string.match( subsubsublemma, "{(.*)}" )
if is_subsubsublemmastar == true then
-- \Subsubsublemma* found -> put it into table
ssslstar[subsubsublemma] = subsubsublemmatext
-- store for potential additional text lines
prevsubsubsublemmastar = subsubsublemma
else
if next( ssslstar ) ~= nil then
-- There are \Subsubsublemma* to sort
subsubsublemmastarcontent = ''
local lastval = sssl[prevsubsubsublemma]
texio.write_nl("Vorgänger: " .. prevsubsubsublemma .. " mit Wert " .. lastval)
ssslstar[prevsubsubsublemma] = lastval
sssl[prevsubsubsublemma] = nil
newkeys = sortLemma( ssslstar )
local firstentry = true
for _, k in ipairs( newkeys ) do
if firstentry == true then
sssl[k] = ssslstar[k]
firstentry = false
prevsubsubsublemma = k
else
subsubsublemmastarcontent = subsubsublemmastarcontent .. "\n" ..
'\\Subsubsublemma*{' .. removesortid( k ) .. '}' .. ssslstar[k]
end
end
-- put it into table with key of last \Sublemma
local lastval = sssl[prevsubsubsublemma]
sssl[prevsubsubsublemma] = lastval .. subsubsublemmastarcontent
-- Empty table slstar
ssslstar = {}
end
-- add sublemma to table and save it for possible sublemma*
sssl[subsubsublemma] = subsubsublemmatext
prevsubsubsublemma = subsubsublemma
end
else
if next( ssslstar ) ~= nil then
local lastval = ssslstar[prevsubsubsublemmastar]
ssslstar[prevsubsubsublemmastar] = lastval .. "\n" .. str
else
local lastval = sssl[prevsubsubsublemma]
ssl[prevsubsubsublemma] = lastval .. "\n" .. str
end
end
elseif is_insubsublemmata == true then
subsublemma, subsublemmatext =
string.match( str, "^%s*\\Subsublemma%*(%b{})(.*)$" )--$
is_subsublemmastar = true
if not subsublemma or subsublemma == '' then
-- we check for unstarred version
subsublemma, subsublemmatext =
string.match( str, "^%s*\\Subsublemma(%b{})(.*)$" )--$
is_subsublemmastar = false
end
if subsublemma and subsublemma ~= '' then
-- we found a new sublemma
subsublemma = string.match( subsublemma, "{(.*)}" )
if is_subsublemmastar == true then
-- \Sublemma* found -> put it into table
sslstar[subsublemma] = subsublemmatext
-- store for potential additional text lines
prevsubsublemmastar = subsublemma
else
if next( sslstar ) ~= nil then
-- There are \Subsublemma* to sort
subsublemmastarcontent = ''
local lastval = ssl[prevsubsublemma]
sslstar[prevsubsublemma] = lastval
ssl[prevsubsublemma] = nil
newkeys = sortLemma( sslstar )
local firstentry = true
for _, k in ipairs( newkeys ) do
if firstentry == true then
ssl[k] = sslstar[k]
firstentry = false
prevsubsublemma = k
else
subsublemmastarcontent = subsublemmastarcontent .. "\n" ..
'\\Subsublemma*{' .. removesortid( k ) .. '}' .. sslstar[k]
end
end
-- put it into table with key of last \Sublemma
local lastval = ssl[prevsubsublemma]
ssl[prevsubsublemma] = lastval .. subsublemmastarcontent
-- Empty table slstar
sslstar = {}
end
-- add sublemma to table and save it for possible sublemma*
ssl[subsublemma] = subsublemmatext
prevsubsublemma = subsublemma
end
else
if next( sslstar ) ~= nil then
local lastval = sslstar[prevsubsublemmastar]
sslstar[prevsubsublemmastar] = lastval .. "\n" .. str
else
local lastval = ssl[prevsubsublemma]
ssl[prevsubsublemma] = lastval .. "\n" .. str
end
end
elseif is_insublemmata == true then
--[[
Within Sublemmata there can be two macros:
\Sublemma and \Sublemma*
We check for one of them, otherwise we add the text to the
current string
]]
-- We check for \Sublemma* first
sublemma, sublemmatext =
string.match( str, "^%s*\\Sublemma%*(%b{})(.*)$" )--$
is_sublemmastar = true
-- If we haven't found anything yet, we look for \Sublemma
if not sublemma or sublemma == '' then
sublemma, sublemmatext =
string.match( str, "^%s*\\Sublemma(%b{})(.*)$" )--$
is_sublemmastar = false
end
--[[
If we have found something we know from the boolean variable
is_sublemmastar
]]
if sublemma and sublemma ~= '' then
-- we found a new sublemma or a sublemma*
-- Rip off braces before continuing
sublemma = string.match( sublemma, "{(.*)}" )
--texio.write_nl( "Found new sublemma: " .. sublemma )
-- We now distinguish
if is_sublemmastar == true then
-- \Sublemma* found -> put it into table
slstar[sublemma] = sublemmatext
-- store for potential additional text lines
prevsublemmastar = sublemma
else
-- \Sublemma found -> sort \Sublemma* (if any), then proceed
if next( slstar ) ~= nil then
-- There are \Sublemma* to sort
sublemmastarcontent = ''
-- Add sublemma to table of sublemma* for sorting
local lastval = sl[prevsublemma]
slstar[prevsublemma] = lastval
-- Remove it from sublemma table
sl[prevsublemma] = nil
-- sort slstar
newkeys = sortLemma( slstar )
-- use the keys to retrieve the values in the sorted order
-- we write the sorted content to the top level structure
local firstentry = true
for _, k in ipairs( newkeys ) do
-- Put the first element back in sublemma table
if firstentry == true then
sl[k] = slstar[k]
firstentry = false
prevsublemma = k
-- All other elements are handeled as sublemma*
else
sublemmastarcontent = sublemmastarcontent .. "\n" ..
'\\Sublemma*{' .. removesortid( k ) .. '}' ..
slstar[k]
end
end
-- put it into table with key of last \Sublemma
local lastval = sl[prevsublemma]
sl[prevsublemma] = lastval .. sublemmastarcontent
-- Empty table slstar
slstar = {}
end
-- add sublemma to table and save it for possible sublemma*
sl[sublemma] = sublemmatext
prevsublemma = sublemma
end
else
--[[
we concatenate the string to the last
sublemma or sublemma* in the table
--]]
if next( slstar ) ~= nil then
local lastval = slstar[prevsublemmastar]
slstar[prevsublemmastar] = lastval .. "\n" .. str
else
local lastval = sl[prevsublemma]
sl[prevsublemma] = lastval .. "\n" .. str
end
end
else -- it can only be a lemma entry, but which one
--texio.write_nl("Check line within dictionary")
lemma_oarg, lemma, text = string.match( str, "^%s*\\Lemma%[(.-)%](%b{})(.*)$" ) --$
if not lemma_oarg or lemma_oarg == '' then
lemma, text = string.match( str, "^%s*\\Lemma(%b{})(.*)$" ) --$
else
text = "\\Lemmaoarg{" .. lemma_oarg .. "}" .. text
end
if lemma and lemma ~= '' then
lemma = string.match( lemma, "{(.*)}" )
-- texio.write_nl("Found new lemma " .. lemma)
-- we found a new lemma
-- write previous lemma (if any) to table
if prevlemma and prevlemma ~= '' then
lemmacontent = string.gsub( lemmacontent, '\n\n', '\n' )
result[prevlemma] = lemmacontent
end
-- remember new lemma as prevlemma for next entry
prevlemma = lemma
lemmacontent = text
-- delete old entries for sublemma
prevsublemma = ''
sublemmacontent = ''
else
lemmacontent = lemmacontent .. "\n" .. str
end
end
end
end
end
elseif glosslang == "Av" or
glosslang == "MP" or
glosslang == "NP" or
glosslang == "Skt" then
for k,v in pairs( lines ) do
-- get line k and process it
local str = lines[k]
if string.match( str, "^%s*\\begin{Dictionary}" ) then
f:write( '\\begin{ModDictionary}', "\n" )
is_indictionary = true
elseif string.match( str, "^%s*\\end{Dictionary}" ) then
-- we reached the end of the dictionary
-- write last lemma to file
if prevlemma and prevlemma ~= '' then
result[prevlemma] = lemmacontent
end
-- start sorting process
newkeys = sortLemma( result )
-- use the keys to retrieve the values in the sorted order
for _, k in ipairs( newkeys ) do
f:write( '\n\\Lemma{' .. removesortid( k ) .. '}' .. result[k] )
-- get the first letter of the lemma
local first = ustring.sub( removesortid( k ), 1, 1 )
--texio.write_nl(first)
-- check whether the letter is already known and not -
if not hash[first] and first ~= "-" then
res[#res+1] = first
hash[first] = true
end
end
-- if lines follow they should be processed as well
f:write( '\n\\end{ModDictionary}', "\n" )
local sequenceofletters = ""
for k,v in pairs( res ) do
if sequenceofletters == "" then
sequenceofletters = v
else
sequenceofletters = sequenceofletters .. ", " .. v
end
end
tex.sprint( [[\makeatletter\immediate\write\@mainaux{\string\ifltxcounter{numberofglossaries}
{}{\string\newcounter{numberofglossaries}}\string\stepcounter{numberofglossaries}}\makeatother]])
tex.sprint([[\makeatletter\write\@mainaux{\string\csxdef{@sequenceofletters\arabic{numberofglossaries}}{]],sequenceofletters,"}}",[[\makeatother]] )
is_indictionary = false
else
if is_indictionary == false then
else -- it can only be a lemma entry, but which one
--texio.write_nl("Check line within dictionary")
lemma_oarg, lemma, text = string.match( str, "^%s*\\Lemma%[(.-)%](%b{})(.*)$" ) --$
if not lemma_oarg or lemma_oarg == '' then
lemma, text = string.match( str, "^%s*\\Lemma(%b{})(.*)$" ) --$
else
text = "\\Lemmaoarg{" .. lemma_oarg .. "}" .. text
end
if lemma and lemma ~= '' then
lemma = string.match( lemma, "{(.*)}" )
--texio.write_nl("Found new lemma " .. lemma)
-- we found a new lemma
-- write previous lemma (if any) to table
if prevlemma and prevlemma ~= '' then
lemmacontent = string.gsub( lemmacontent, '\n\n', '\n' )
result[prevlemma] = lemmacontent
end
-- remember new lemma as prevlemma for next entry
prevlemma = lemma
lemmacontent = text
else
lemmacontent = lemmacontent .. "\n" .. str
end
end
end
end
else
texio.write_nl( "Could not find a sort method for " .. glosslang )
end
f:close()
end
-- We remove the sortid after the comparison
function removesortid( s )
local snew = s
snew = string.gsub( snew, '^¹(.+)$', '%1' )
snew = string.gsub( snew, '^²(.+)$', '%1' )
snew = string.gsub( snew, '^³(.+)$', '%1' )
return snew
end
function removespecialchars( s )
local snew = s
-- We replace/remove some characters not to be considered for sorting
--snew = string.gsub(snew, '^%-?(.+)%-?$', '%1')--$
--texio.write_nl("Vorher: " .. snew)
snew = string.gsub( snew, '%-', '' )
snew = string.gsub( snew, '%.', '' )
snew = string.gsub( snew, '%(', '' )
snew = string.gsub( snew, '%)', '' )
snew = string.gsub( snew, '°', '' )
snew = string.gsub( snew, '⁺', '' )
snew = string.gsub( snew, '%s-/%s-', ' ' )
snew = string.gsub( snew, '%s-…%s-', ' ' )
-- ... and we move sort ids to the very end
snew = string.gsub( snew, '^¹(.+)$', '%11' )
snew = string.gsub( snew, '^²(.+)$', '%12' )
snew = string.gsub( snew, '^³(.+)$', '%13' )
-- we change special chars to match Unicode characters
-- s1 = ustring.gsub(s1, 'é', 'é')
snew = ustring.gsub( snew, 'ḍ', 'ḍ' )
-- s1 = ustring.gsub(s1, 'ḳ', 'ḳ')
snew = ustring.gsub( snew, 'ḷ', 'ḷ' )
snew = ustring.gsub( snew, 'ṃ', 'ṃ' )
snew = ustring.gsub( snew, 'ṇ', 'ṇ' )
-- s1 = ustring.gsub(s1, 'ọ', 'ọ')
snew = ustring.gsub( snew, 'ś', 'ś' )
snew = ustring.gsub( snew, 'š' ,'š' )
snew = ustring.gsub( snew, 'ṣ', 'ṣ' )
snew = ustring.gsub( snew, 'ṭ', 'ṭ' )
snew = string.gsub( snew, '\\XVE ', 'xv' )
snew = string.gsub( snew, '\\NGVE' , 'ŋv' )
snew = string.gsub( snew, '\\aee ', 'ǝ̄' )
snew = string.gsub( snew, '\\XVE{}', 'xv' )
snew = string.gsub( snew, '\\NGVE{}', 'ŋv' )
snew = string.gsub( snew, '\\aee{}', 'ǝ̄' )
snew = string.gsub( snew, '\\uncertain{([^}]+)}', '%1' )
--texio.write_nl("Nachher: " .. snew)
return snew
end
function sortLemma( t )
local tkeys = {}
-- populate the table that holds the keys
for k in pairs( t ) do table.insert( tkeys, k ) end
-- sort the keys
table.sort( tkeys, compare )
return tkeys
end
function compare( a, b )
-- before sorting, we remove dashes from the beginning and from the end ...
local s1 = removespecialchars( a )
local s2 = removespecialchars( b )
-- the comparison returns a sort order so1 and so2
local so1, so2
--texio.write_nl('Compare ' .. s1 .. ' with ' .. s2)
-- if both strings are equal we stop processing
if s1 ~= s2 then
-- as long as both strings have equal characters (and are both not empty)
-- get the next sorting letter and compare them
while s1 ~= '' and s2 ~= '' do
--texio.write_nl('Vorher: ' .. s1 .. ' ' .. s2)
so1, s1 = sortletter(s1)
so2, s2 = sortletter(s2)
--texio.write_nl('Sort order: ' .. so1 .. ' ' .. so2)
--texio.write_nl('Rest: ' .. s1 .. ' ' .. s2)
if so1 < so2 then
return true
elseif so1 > so2 then
return false
end
--texio.write_nl('Nachher: ' .. s1 .. ' ' .. s2)
end
if s1 == '' then
return true
else
return false
end
else
return false
end
end
function sortletter(s)
local sortorder
if glosslang == 'Guj' then -- Gujarati
sortorder = {["a"] = 11, ["ā"] = 12, ["i"] = 13, ["ī"] = 14,["u"] = 15,
["ū"] = 16, ["r̥"] = 17, ["e"] = 18, ["o"] = 19, ["ṃ"] = 20, ["k"] = 21,
["kh"] = 22, ["g"] = 23, ["gh"] = 24, ["ṅ"] = 25, ["c"] = 26, ["ch"] = 27,
["j"] = 28, ["jh"] = 29, ["z"] = 30, ["ñ"] = 31, ["ṭ"] = 32, ["ṭh"] = 33,
["ḍ"] = 34, ["ḍh"] = 35, ["ṇ"] = 36, ["t"] = 37, ["th"] = 38, ["d"] = 39,
["dh"] = 40, ["n"] = 41, ["p"] = 42, ["ph"] = 43, ["f"] = 44, ["b"] = 45,
["bh"] = 46, ["m"] = 47, ["y"] = 48, ["r"] = 49, ["l"] = 50, ["v"] = 51,
["ś"] = 52, ["ṣ"] = 53, ["s"] = 54, ["h"] = 55, ["ḷ"] = 56, ["1"] = 1,
["2"] = 2, ["3"] = 3, [" "] = 60}
elseif glosslang == 'MP' then -- Middle Persian (Pahlavi)
sortorder = {["a"] = 11, ["ā"] = 12, ["b"] = 13, ["c"] = 14, ["d"] = 15,
["e"] = 16, ["ē"] = 17, ["f"] = 18, ["g"] = 19, ["γ"] = 20, ["h"] = 21,
["i"] = 22, ["ī"] = 23, ["j"] = 24, ["k"] = 25, ["l"] = 26, ["m"] = 27,
["n"] = 28, ["o"] = 29, ["ō"] = 30, ["p"] = 31, ["r"] = 32, ["s"] = 33,
["š"] = 34, ["t"] = 35, ["u"] = 36, ["ū"] = 37, ["w"] = 38, ["x"] = 39,
["y"] = 40, ["z"] = 41, ["ž"] = 42, ["1"] = 1, ["2"] = 2, ["3"] = 3,
[" "] = 50}
elseif glosslang == 'NP' then -- New Persian
sortorder = {["a"] = 11, ["ā"] = 12, ["e"] = 13, ["o"] = 14, ["u"] = 15,
["i"] = 16, ["b"] = 17, ["p"] = 18, ["t"] = 19, ["s̱"] = 20, ["j"] = 21,
["č"] = 22, ["ḥ"] = 23, ["x"] = 24, ["d"] = 25, ["ẕ"] = 26, ["r"] = 27,
["z"] = 28, ["ž"] = 29, ["s"] = 30, ["š"] = 31, ["ṣ"] = 32, ["ż"] = 33,
["ṭ"] = 34, ["ẓ"] = 35, ["ʿ"] = 36, ["ġ"] = 37, ["f"] = 38, ["q"] = 39,
["k"] = 40, ["g"] = 41, ["l"] = 42, ["m"] = 43, ["n"] = 44, ["w"] = 45,
["h"] = 46, ["y"] = 47, ["1"] = 2, ["2"] = 2, ["3"] = 3, [" "] = 50}
elseif glosslang == 'Av' then -- Avestan, standard case
sortorder = {["a"] = 11, ["ā"] = 12, ["ā̊ "] = 13, ["ą"] = 14, ["b"] = 15,
["β"] = 16, ["c"] = 17, ["d"] = 18, ["δ"] = 19, ["e"] = 20, ["ē"] = 21,
["ǝ"] = 22, ["ǝ̄"] = 23, -- U+01DD
["ə"] = 22, ["ə̄"] = 23, -- U+0259
["f"] = 24, ["g"] = 25, ["γ"] = 26, ["h"] = 27,
["i"] = 28, ["ī"] = 29, ["j"] = 30, ["k"] = 31, ["m"] = 32, ["n"] = 33,
["ń"] = 34, ["ṇ"] = 35, ["ŋ"] = 36, ["ŋ́"] = 37, ["ŋv"] = 38, ["o"] = 39,
["ō"] = 40, ["p"] = 41, ["r"] = 42, ["s"] = 43, ["š"] = 44,
["š́ "] = 45, ["ṣ̌"] = 46, ["t"] = 47, ["t̰"] = 48, ["ϑ"] = 49, ["θ"] = 49,
["u"] = 50, ["ū"] = 51,
["v"] = 52, ["x"] = 53, ["x́"] = 54, ["xv"] = 55, ["y"] = 56, ["z"] = 57,
["ž"] = 58, ["1"] = 1, ["2"] = 2, ["3"] = 3, [" "] = 60}
elseif glosslang == 'Skt' then -- Sanskrit
sortorder = {["a"] = 11, ["ā"] = 12, ["i"] = 13, ["ī"] = 14, ["u"] = 15,
["ū"] = 16, ["r̥"] = 17, ["r̥̄"] = 18, ["e"] = 19, ["ai"] = 20, ["o"] = 21,
["au"] = 22, ["ṃ"] = 23, ["ḥ"] = 24, ["k"] = 25, ["kh"] = 26, ["g"] = 27,
["gh"] = 28, ["ṅ"] = 29, ["c"] = 30, ["ch"] = 31, ["j"] = 32, ["jh"] = 33,
["ñ"] = 34, ["ṭ"] = 35, ["ṭh"] = 36, ["ḍ"] = 37, ["ḍh"] = 38, ["ṇ"] = 39,
["t"] = 40, ["th"] = 41, ["d"] = 42, ["dh"] = 43, ["n"] = 44,
["p"] = 45, ["ph"] = 46, ["b"] = 47, ["bh"] = 48, ["m"] = 49,
["y"] = 50, ["r"] = 51,
["l"] = 52, ["v"] = 53, ["ś"] = 54, ["ṣ"] = 55, ["s"] = 56, ["h"] = 57,
["1"] = 1, ["2"] = 2, ["3"] = 3, [" "] = 60}
else
texio.write_nl( "Unknown language for glossary sorting" )
end
local sortletter = ''
-- If s is at last two characters long, we check, whether the first two
-- characters form a valid sorting letter (according to our scheme)
if ustring.len( s ) > 1 then
sortletter = ustring.sub( s, 1, 2 )
if sortorder[sortletter] == nil then
sortletter = ustring.sub( s, 1, 1 )
end
else -- otherwise just take the first character and check
sortletter = ustring.sub( s, 1, 1 )
end
--texio.write_nl(s .. ' ' .. sortletter .. ' ' .. ustring.len(sortletter))
if sortorder[sortletter] then
return sortorder[sortletter], ustring.sub( s, ustring.len( sortletter ) + 1 )
else -- if there is a letter we don't know, insert at the very end
texio.write_nl( "Unknown letter " .. sortletter )
return 99, ustring.sub( s, ustring.len(sortletter) + 1 )
end
end
-- taken from https://gist.github.com/phi-gamma/2622252
--[[
https://tex.stackexchange.com/questions/374064/upright-punctuation-independent-from-font-style
This is a function to get specific punctuation characters upright even if they
are in an italics environment
--]]
function table.contains(t, k)
for _, v in pairs(t) do
if v == k then
return true
end
end
return false
end
function upright_punctuation(head)
-- Traverse vertical list
for line in node.traverse_id(node.id("hhead"),head) do
-- Traverse horizontal list
for glyph in node.traverse_id(node.id("glyph"), line.head) do
-- Check if the glyph is
-- ( ) , : ;
if (table.contains({ 40, 41, 44, 58, 59 }, glyph.char)) then
-- and change its font to upright.
-- (this is not so generic, 15 just happens to be upright)
glyph.font = 15
end
end
end
return head
end
function read_stanzas_from_file(f, suffix)
if not file_exists( f ) then return {} end
local outfile = 'stanzas.tex'
local lines = lines_from( f )
local stanzanr = ''
local stanzastart = ''
local stanzaend = ''
local text = ''
local book = ''
local buf = {}
for k,v in pairs( lines ) do
-- get line k and process it
local str = lines[k]
--texio.write_nl(str .. "\n")
if isempty( str ) then
buf[k] = ''
else
-- Check, whether a new stanza starts
if string.match( str, "^\\begin{stanza}{.-}" ) then
book, stanzanr, text = string.match( str, "^\\begin{stanza}{\\(.-){(.-)}}" )
buf[k] = "\\csgdef{stanza-" .. book .. stanzanr .. suffix .. "}{%\n" .. str .. "%\n"
elseif string.match( str, "^.-\\end{stanza}\\begin{stanza}{.-}.-$" ) then
stanzaend, book, stanzanr, stanzastart = string.match(str, "^(.-)\\end{stanza}\\begin{stanza}{\\(.-){(.-)}}(.-)$")
buf[k] = stanzaend .. "\n\\end{stanza}}%\n\\csgdef{stanza-" ..
book .. stanzanr .. suffix .. "}{%\n\\begin{stanza}{\\" .. book .. "{" .. stanzanr .. "}}%\n" .. stanzastart .. "\n"
elseif string.match( str, "^.-\\newline\\end{stanza}$" ) then
text, rest = string.match( str, "^(.-)(\\newline\\end{stanza})$" )
buf[k] = text .. "\\lastnewline\\end{stanza}}%\n"
elseif string.match( str, "^.-\\end{stanza}$" ) then
buf[k] = str .. "}\n"
else
buf[k] = str .. "\n"
end
end
end
local final_string = table.concat( buf )
local g = assert( io.open( outfile, "a" ))
g:write( final_string )
g:close()
end
function create_stanzafile()
local file = assert( io.open( "./stanzas.tex", "w" ))
file:close()
end
function strtocs( s )
local book, number = ''
book, number = string.match( s, "^(%u+)(.+)$" )
tex.sprint( "\\" .. book .. "{" .. number .. "}" )
end
function read_transcriptions( f )
if not file_exists( f ) then return {} end
local lines = lines_from( f )
local outfile = 'transcriptions-mod.tex'
local sec, thrd = ''
local newstr = ''
local buf = {}
local c = 0
-- Get third argument of \Newtranscription
for k, v in pairs( lines ) do
-- get line k and process it
local str = lines[k]
-- get second and third argument
sec, thrd = string.match( str, "^\\Newtranscription{(.-)}{(.-)}" )
newstr = ''
if not isempty( sec ) then -- ignore empty lines
c = 0
for i in string.gmatch( thrd, "%S+" ) do
c = c + 1
newstr = newstr .. "\\csgdef{" .. sec .. "-trans-" .. c .. "}{" .. i .. "}\n"
end
end
buf[k] = newstr
end
local final_string = table.concat( buf )
local g = assert( io.open( outfile, "w" ))
g:write( final_string )
g:close()
end
function isempty( s )
return s == nil or s == ''
end
|
-- @menu group
-- This group does and blits the main menu screen. With an offset and a real offset (leftoffset of the first option).
-- Then, the offset is multiplied by the option number, if go to right, offset inc, real offset "goes to" offset, so
-- our option will change progressively. Options spacing 240px.
menu = {
sxoffset = 0, rxoffset = 600, malpha = 0, malphad = 10,
snd = sound.load("snd/menu.wav",1), AR = image.load("img/arrowr.png"), AL = image.load("img/arrowl.png"),
x=0,
texts = { text.nuevojuego, text.cargajuego, text.multijuego, text.actujuego, text.kitajuego },
responses = { "newgam", "conti", "conti", "opti", "exit" },
numopt = 5,
blit = function(x)
if menu.rxoffset < menu.sxoffset then menu.rxoffset = menu.rxoffset + iif((((menu.sxoffset - menu.rxoffset) / 3) > 2),math.ceil((menu.sxoffset - menu.rxoffset) / 3),1); end
if menu.rxoffset > menu.sxoffset then menu.rxoffset = menu.rxoffset - iif((((menu.rxoffset - menu.sxoffset) / 3) > 2),math.ceil((menu.rxoffset - menu.sxoffset) / 3),1); end
menu.malpha = menu.malpha + menu.malphad; if menu.malpha > 255 and menu.malphad > 0 then menu.malpha = 255; menu.malphad = -menu.malphad; end
if menu.malpha < 100 and menu.malphad < 0 then menu.malpha = 100; menu.malphad = -menu.malphad; end
for i=1,menu.numopt do
screen.print((240*i) - menu.rxoffset,192,menu.texts[i],1,color.new(255,255,255,iif((x == (i-1)),255,128)),color.new(0,0,0,iif((x == (i-1)),255,128)),"center");
end
if x > 0 then image.blend(130,195,menu.AL,menu.malpha); end
if x < menu.numopt-1 then image.blend(350,195,menu.AR,menu.malpha); end
end,
exec = function() if not menu.opc then menu.opc = 0; end if controls.press("left") then if menu.opc > 0 then menu.snd:play(7); end menu.opc = math.max(menu.opc - 1,0); end if controls.press("right") then if menu.opc < menu.numopt-1 then menu.snd:play(7); end menu.opc = math.min(menu.opc + 1,menu.numopt-1); end menu.sxoffset = (240 * menu.opc); screen.clip(11,120,458,159); menu.blit(menu.opc); screen.clip(); if controls.press("cross") or controls.press("start") then menu.snd:play(7); controls.read(); return menu.responses[menu.opc+1] end return false; end,
}
menu.AR:center(); menu.AR:resize(25,25);
menu.AL:center(); menu.AL:resize(25,25);
-- @starfield
starfield = {
stars = {}, num=50, origx=240, origy=136, paused=false, speed=1, rspeed=1, a=255,
createstar = function() local star, xcoeff, ycoeff; star = { x = math.random() * 480 - starfield.origx, y = math.random() * 272 - starfield.origy, z = 480, width = 2 }; xcoeff, ycoeff = iif(star.x > 0,1,-1), iif(star.y > 0,1,-1); if (math.abs(star.x)>math.abs(star.y)) then star.dx = 1.0; star.dy = math.abs(star.y / star.x); else star.dx = math.abs(star.x / star.y); star.dy = 1.0; end star.dx, star.dy, star.dz = star.dx * xcoeff * starfield.speed, star.dy * ycoeff * starfield.speed, -1; star.ddx, star.ddy = 0.1 * star.dx, 0.1 * star.dy; return star; end,
move = function(star) if starfield.paused then return star; end star.x, star.y, star.z, star.dx, star.dy, star.width = star.x + star.dx, star.y + star.dy, star.z + star.dz, star.dx + star.ddx, star.dy + star.ddy, math.abs(1 + ((480 - star.z) * 0.05)); return star; end,
update = function() starfield.speed = vgt(starfield.speed,starfield.rspeed,0.01); for i = 1, #starfield.stars do starfield.stars[i] = starfield.move(starfield.stars[i]); local s = starfield.stars[i]; if (s.x < -starfield.origx or s.x > starfield.origx or s.y < -starfield.origy or s.y > starfield.origy) then starfield.stars[i] = starfield.createstar(); else draw.fillrect(starfield.stars[i].x + 240,starfield.stars[i].y+136,starfield.stars[i].width,starfield.stars[i].width,color.new(255,255,255,starfield.a)); end end for i = #starfield.stars, 50 do table.insert(starfield.stars,starfield.createstar()); end end,
};
-- @talkysys
talk = {
images = { image.loadsprite("res/pnj/00.png",100,100), image.loadsprite("res/pnj/01.png",100,100) },
showing = false,
mood = 0,
now = os.clock(),
speech = function(i,t) talk.i = i; talk.t = t; talk.showing = true; talk.now = os.clock(); end,
close = function() talk.showing = false; end,
blit = function()
if talk.showing then
pla.overridecontrols = true;
talk.images[talk.i]:setframe(talk.mood);
draw.fillrect(0,170,480,102,color.new(0,0,0,180));
talk.images[talk.i]:blit(5,272-100);
screen.print(110,175,talk.t,0.6,color.new(255,255,255),color.new(0,0,0,200),"left",340);
im.blit("xtocont");
if controls.press("cross") or (os.clock() - talk.now) > 10 then
if ( os.clock() - talk.now > 0.500 ) then menu.snd:play(7); talk.showing = false; pla.overridecontrols = false; end
end
end
end,
}
-- @savegames
mainconfigtable = { gameid="GDEFPATROL", savenames = "PERFIL" };
mainconfigvsh = { title=text.configtitle, subtitle=text.configsubtitle, details=text.configdetails, savetext=text.saveconfig, icon0="res/config_icon0.png", saveicon="res/save_icon0.png" };
historyconfigtable = { gameid="GDEFPATROL", savenames = { "HIST00", "HIST01", "HIST02", "HIST03", "HIST04", "HIST05", "HIST06", "HIST07", "HIST08", "HIST09" } };
historyconfigvsh = { title=text.savetitle, subtitle=os.date(), details=text.savedetails, savetext = text.savetext, icon0="res/save_icon0.png", saveicon="res/save_icon0new.png", snd0="res/snd0.at3" };
function saveconfig()
local iny = pla.invertaxis and "true" or "false";
local usa = pla.useanalog and "true" or "false";
local mxv = music.maxvol or 100;
local data = "iny="..iny..";usa="..usa..";mxv="..mxv..";";
local a,b = savedata.save(mainconfigtable,mainconfigvsh,data);
end
function loadconfig()
local a,b,c = savedata.autoload(mainconfigtable);
local iny = false;
local usa = false;
local mxv = 100;
if (a) then
local t = c:explode(";");
for i=1,#t do
local f = t[i]:explode("=");
if ( f[1] == "iny" ) then iny = iif(f[2]=="true",true,false); end
if ( f[1] == "usa" ) then usa = iif(f[2]=="true",true,false); end
if ( f[1] == "mxv" ) then mxv = tonumber(f[2]); end
end
end
pla.invertaxis = iny or false;
pla.useanalog = usa or false;
music.maxvol = iif(type(mxv)=="number" or type(mxv)=="string",mxv,100) or 100;
end
-- @pause function
function pause()
local a = screen.toimage(); -- grab a copy
local ret = false;
while not ret do
controls.read();
a:blit(0,0);
a:blend(-2,-2,100);
a:blend(2,2,100);
a:blend(-2,2,100);
a:blend(2,-2,100);
draw.fillrect(0,0,480,272,color.new(0,0,0,50));
screen.print(240,136,"PAUSE",1,color.new(255,255,255),color.new(0,0,0),"center");
screen.flip();
if controls.press("start") then ret = true; end
end
a:free();
end
|
return function()
add_dependencies { 'citizen:resources:client', 'vendor:concurrentqueue' }
end
|
-- rButtonTemplate: core
-- zork, 2016
-----------------------------
-- Variables
-----------------------------
local A, L = ...
-----------------------------
-- rButtonTemplate Global
-----------------------------
rButtonTemplate = {}
rButtonTemplate.addonName = A
-----------------------------
-- Init
-----------------------------
local function CallButtonFunctionByName(button, func, ...)
if button and func and button[func] then
button[func](button, ...)
end
end
local function ResetAlpha(self,a)
if not self.__alpha then return end
if a == self.__alpha then return end
self:SetAlpha(self.__alpha)
print(self:GetName(),a)
end
local function ResetNormalTexture(self, file)
if not self.__normalTextureFile then return end
if file == self.__normalTextureFile then return end
self:SetNormalTexture(self.__normalTextureFile)
end
local function ResetTexture(self, file)
if not self.__textureFile then return end
if file == self.__textureFile then return end
self:SetTexture(self.__textureFile)
end
local function ResetVertexColor(self,r,g,b,a)
if not self.__vertexColor then return end
local r2,g2,b2,a2 = unpack(self.__vertexColor)
if not a2 then a2 = 1 end
if r ~= r2 or g ~= g2 or b ~= b2 or a ~= a2 then
self:SetVertexColor(r2,g2,b2,a2)
end
end
local function ApplyPoints(self, points)
if not points then return end
self:ClearAllPoints()
for i, point in next, points do
self:SetPoint(unpack(point))
end
end
local function ApplyTexCoord(texture,texCoord)
if not texCoord then return end
texture:SetTexCoord(unpack(texCoord))
end
local function ApplyBlendMode(texture,blendMode)
if not blendMode then return end
texture:SetBlendMode(blendMode)
end
local function ApplySizeFactor(texture,sizeFactor)
if not sizeFactor then return end
local w,h = texture:GetParent():GetSize()
texture:SetSize(w*sizeFactor,h*sizeFactor)
end
local function ApplyVertexColor(texture,color)
if not color then return end
texture.__vertexColor = color
texture:SetVertexColor(unpack(color))
hooksecurefunc(texture, "SetVertexColor", ResetVertexColor)
end
local function ApplyAlpha(region,alpha)
if not alpha then return end
--region.__alpha = alpha
region:SetAlpha(alpha)
--hooksecurefunc(region, "SetAlpha", ResetAlpha)
end
local function ApplyFont(fontString,font)
if not font then return end
fontString:SetFont(unpack(font))
end
local function ApplyHorizontalAlign(fontString,align)
if not align then return end
fontString:SetJustifyH(align)
end
local function ApplyVerticalAlign(fontString,align)
if not align then return end
fontString:SetJustifyV(align)
end
local function ApplyTexture(texture,file)
if not file then return end
texture.__textureFile = file
texture:SetTexture(file)
hooksecurefunc(texture, "SetTexture", ResetTexture)
end
local function ApplyNormalTexture(button,file)
if not file then return end
button.__normalTextureFile = file
button:SetNormalTexture(file)
hooksecurefunc(button, "SetNormalTexture", ResetNormalTexture)
end
local function SetupTexture(texture,cfg,func,button)
if not texture or not cfg then return end
ApplyTexCoord(texture,cfg.texCoord)
ApplyBlendMode(texture,cfg.blendMode)
ApplySizeFactor(texture,cfg.sizeFactor)
ApplyPoints(texture,cfg.points)
ApplyVertexColor(texture,cfg.color)
ApplyAlpha(texture,cfg.alpha)
if func == "SetTexture" then
ApplyTexture(texture,cfg.file)
elseif func == "SetNormalTexture" then
ApplyNormalTexture(button,cfg.file)
elseif cfg.file then
CallButtonFunctionByName(button,func,cfg.file)
end
end
local function SetupFontString(fontString,cfg)
if not fontString or not cfg then return end
ApplyPoints(fontString, cfg.points)
ApplyFont(fontString,cfg.font)
ApplyAlpha(fontString,cfg.alpha)
ApplyHorizontalAlign(fontString,cfg.halign)
ApplyVerticalAlign(fontString,cfg.valign)
end
local function SetupCooldown(cooldown,cfg)
if not cooldown or not cfg then return end
cooldown:SetFrameLevel(cooldown:GetParent():GetFrameLevel())
ApplyPoints(cooldown, cfg.points)
end
local function SetupBackdrop(button,backdrop)
if not backdrop then return end
local bg = CreateFrame("Frame", nil, button, BackdropTemplateMixin and "BackdropTemplate")
ApplyPoints(bg, backdrop.points)
bg:SetFrameLevel(button:GetFrameLevel()-1)
bg:SetBackdrop(backdrop)
if backdrop.backgroundColor then
bg:SetBackdropColor(unpack(backdrop.backgroundColor))
end
if backdrop.borderColor then
bg:SetBackdropBorderColor(unpack(backdrop.borderColor))
end
end
function rButtonTemplate:StyleActionButton(button, cfg)
if not button then return end
if button.__styled then return end
local buttonName = button:GetName()
local icon = _G[buttonName.."Icon"]
local flash = _G[buttonName.."Flash"]
local flyoutBorder = _G[buttonName.."FlyoutBorder"]
local flyoutBorderShadow = _G[buttonName.."FlyoutBorderShadow"]
local flyoutArrow = _G[buttonName.."FlyoutArrow"]
local hotkey = _G[buttonName.."HotKey"]
local count = _G[buttonName.."Count"]
local name = _G[buttonName.."Name"]
local border = _G[buttonName.."Border"]
local NewActionTexture = button.NewActionTexture
local cooldown = _G[buttonName.."Cooldown"]
local normalTexture = button:GetNormalTexture()
local pushedTexture = button:GetPushedTexture()
local highlightTexture = button:GetHighlightTexture()
--normal buttons do not have a checked texture, but checkbuttons do and normal actionbuttons are checkbuttons
local checkedTexture = nil
if button.GetCheckedTexture then checkedTexture = button:GetCheckedTexture() end
local floatingBG = _G[buttonName.."FloatingBG"]
--hide stuff
if floatingBG then floatingBG:Hide() end
--backdrop
SetupBackdrop(button,cfg.backdrop)
--textures
SetupTexture(icon,cfg.icon,"SetTexture",icon)
SetupTexture(flash,cfg.flash,"SetTexture",flash)
SetupTexture(flyoutBorder,cfg.flyoutBorder,"SetTexture",flyoutBorder)
SetupTexture(flyoutBorderShadow,cfg.flyoutBorderShadow,"SetTexture",flyoutBorderShadow)
SetupTexture(border,cfg.border,"SetTexture",border)
SetupTexture(normalTexture,cfg.normalTexture,"SetNormalTexture",button)
SetupTexture(pushedTexture,cfg.pushedTexture,"SetPushedTexture",button)
SetupTexture(highlightTexture,cfg.highlightTexture,"SetHighlightTexture",button)
SetupTexture(checkedTexture,cfg.checkedTexture,"SetCheckedTexture",button)
--cooldown
SetupCooldown(cooldown,cfg.cooldown)
--no clue why but blizzard created count and duration on background layer, need to fix that
local overlay = CreateFrame("Frame",nil,button)
overlay:SetAllPoints()
if count then count:SetParent(overlay) end
if hotkey then hotkey:SetParent(overlay) end
if name then name:SetParent(overlay) end
--hotkey+count+name
SetupFontString(hotkey,cfg.hotkey)
SetupFontString(count,cfg.count)
SetupFontString(name,cfg.name)
button.__styled = true
end
function rButtonTemplate:StyleExtraActionButton(cfg)
local button = ExtraActionButton1
if button.__styled then return end
local buttonName = button:GetName()
local icon = _G[buttonName.."Icon"]
--local flash = _G[buttonName.."Flash"] --wierd the template has two textures of the same name
local hotkey = _G[buttonName.."HotKey"]
local count = _G[buttonName.."Count"]
local buttonstyle = button.style --artwork around the button
local cooldown = _G[buttonName.."Cooldown"]
local normalTexture = button:GetNormalTexture()
local pushedTexture = button:GetPushedTexture()
local highlightTexture = button:GetHighlightTexture()
local checkedTexture = button:GetCheckedTexture()
--backdrop
SetupBackdrop(button,cfg.backdrop)
--textures
SetupTexture(icon,cfg.icon,"SetTexture",icon)
SetupTexture(buttonstyle,cfg.buttonstyle,"SetTexture",buttonstyle)
SetupTexture(normalTexture,cfg.normalTexture,"SetNormalTexture",button)
SetupTexture(pushedTexture,cfg.pushedTexture,"SetPushedTexture",button)
SetupTexture(highlightTexture,cfg.highlightTexture,"SetHighlightTexture",button)
SetupTexture(checkedTexture,cfg.checkedTexture,"SetCheckedTexture",button)
--cooldown
SetupCooldown(cooldown,cfg.cooldown)
--hotkey, count
SetupFontString(hotkey,cfg.hotkey)
SetupFontString(count,cfg.count)
button.__styled = true
end
function rButtonTemplate:StyleItemButton(button,cfg)
if not button then return end
if button.__styled then return end
local buttonName = button:GetName()
local icon = _G[buttonName.."IconTexture"]
local count = _G[buttonName.."Count"]
local stock = _G[buttonName.."Stock"]
local searchOverlay = _G[buttonName.."SearchOverlay"]
local border = button.IconBorder
local normalTexture = button:GetNormalTexture()
local pushedTexture = button:GetPushedTexture()
local highlightTexture = button:GetHighlightTexture()
--the new ItemButton frame type introduced in 8.1.5 does not have a checked texture
local checkedTexture = nil
if button.GetCheckedTexture then checkedTexture = button:GetCheckedTexture() end
--backdrop
SetupBackdrop(button,cfg.backdrop)
--textures
SetupTexture(icon,cfg.icon,"SetTexture",icon)
SetupTexture(searchOverlay,cfg.searchOverlay,"SetTexture",searchOverlay)
SetupTexture(border,cfg.border,"SetTexture",border)
SetupTexture(normalTexture,cfg.normalTexture,"SetNormalTexture",button)
SetupTexture(pushedTexture,cfg.pushedTexture,"SetPushedTexture",button)
SetupTexture(highlightTexture,cfg.highlightTexture,"SetHighlightTexture",button)
SetupTexture(checkedTexture,cfg.checkedTexture,"SetCheckedTexture",button)
--count+stock
SetupFontString(count,cfg.count)
SetupFontString(stock,cfg.stock)
button.__styled = true
end
function rButtonTemplate:StyleAllActionButtons(cfg)
for i = 1, NUM_ACTIONBAR_BUTTONS do
rButtonTemplate:StyleActionButton(_G["ActionButton"..i],cfg)
rButtonTemplate:StyleActionButton(_G["MultiBarBottomLeftButton"..i],cfg)
rButtonTemplate:StyleActionButton(_G["MultiBarBottomRightButton"..i],cfg)
rButtonTemplate:StyleActionButton(_G["MultiBarRightButton"..i],cfg)
rButtonTemplate:StyleActionButton(_G["MultiBarLeftButton"..i],cfg)
end
for i = 1, 6 do
rButtonTemplate:StyleActionButton(_G["OverrideActionBarButton"..i],cfg)
end
--petbar buttons
for i=1, NUM_PET_ACTION_SLOTS do
rButtonTemplate:StyleActionButton(_G["PetActionButton"..i],cfg)
end
--stancebar buttons
for i=1, NUM_STANCE_SLOTS do
rButtonTemplate:StyleActionButton(_G["StanceButton"..i],cfg)
end
--possess buttons
for i=1, NUM_POSSESS_SLOTS do
rButtonTemplate:StyleActionButton(_G["PossessButton"..i],cfg)
end
end
function rButtonTemplate:StyleAuraButton(button, cfg)
if not button then return end
if button.__styled then return end
local buttonName = button:GetName()
local icon = _G[buttonName.."Icon"]
local count = _G[buttonName.."Count"]
local duration = _G[buttonName.."Duration"]
local border = _G[buttonName.."Border"]
local symbol = button.symbol
--backdrop
SetupBackdrop(button,cfg.backdrop)
--textures
SetupTexture(icon,cfg.icon,"SetTexture",icon)
SetupTexture(border,cfg.border,"SetTexture",border)
--create a normal texture on the aura button
if cfg.normalTexture and cfg.normalTexture.file then
button:SetNormalTexture(cfg.normalTexture.file)
local normalTexture = button:GetNormalTexture()
SetupTexture(normalTexture,cfg.normalTexture,"SetNormalTexture",button)
end
--no clue why but blizzard created count and duration on background layer, need to fix that
local overlay = CreateFrame("Frame",nil,button)
overlay:SetAllPoints()
if count then count:SetParent(overlay) end
if duration then duration:SetParent(overlay) end
--count,duration,symbol
SetupFontString(count,cfg.count)
SetupFontString(duration,cfg.duration)
SetupFontString(symbol,cfg.symbol)
button.__styled = true
end
--style player BuffFrame buff buttons
local buffButtonIndex = 1
function rButtonTemplate:StyleBuffButtons(cfg)
local function UpdateBuffButtons()
if buffButtonIndex > BUFF_MAX_DISPLAY then return end
for i = buffButtonIndex, BUFF_MAX_DISPLAY do
local button = _G["BuffButton"..i]
if not button then break end
rButtonTemplate:StyleAuraButton(button, cfg)
if button.__styled then buffButtonIndex = i+1 end
end
end
hooksecurefunc("BuffFrame_UpdateAllBuffAnchors", UpdateBuffButtons)
end
--style player BuffFrame debuff buttons
function rButtonTemplate:StyleDebuffButtons(cfg)
local function UpdateDebuffButton(buttonName, i)
local button = _G["DebuffButton"..i]
rButtonTemplate:StyleAuraButton(button, cfg)
end
hooksecurefunc("DebuffButton_UpdateAnchors", UpdateDebuffButton)
end
--style player TempEnchant buttons
function rButtonTemplate:StyleTempEnchants(cfg)
rButtonTemplate:StyleAuraButton(TempEnchant1, cfg)
rButtonTemplate:StyleAuraButton(TempEnchant2, cfg)
rButtonTemplate:StyleAuraButton(TempEnchant3, cfg)
end
--style all aura buttons
function rButtonTemplate:StyleAllAuraButtons(cfg)
rButtonTemplate:StyleBuffButtons(cfg)
rButtonTemplate:StyleDebuffButtons(cfg)
rButtonTemplate:StyleTempEnchants(cfg)
end
|
------------------------------------------------------------------------------------------------------------
-- This allows button rendering to be deferred if needed
------------------------------------------------------------------------------------------------------------
local res = sys.load_resource("/scripts/utils/directory.lua")
local dir = assert(loadstring(res))()
local widgets = {}
widgets.img_arrowup = nil
widgets.img_arrowdn = nil
widgets.cursorFlash = 0.4
------------------------------------------------------------------------------------------------------------
local function TweenDone(objList, name)
local sostate = objList[name]
sostate.tween = nil
end
------------------------------------------------------------------------------------------------------------
function widgets:ButtonImage(name, image, x, y, cb, meta)
local button = self:Button(name, x, y, image.width * image.scalex, image.height * image.scaley, 0, 6, cb, meta )
self:RenderImage(image, x, y, 0.0, 1)
end
------------------------------------------------------------------------------------------------------------
function widgets:ButtonText(name, text, x, y, fsize, tcolor, cb, meta)
local w,h = self:GetTextSize(text, fsize)
local button = self:Button(name, x, y-h, w, h, 0, 6, cb, meta )
self:RenderText(text, x, y, fsize, tcolor)
end
------------------------------------------------------------------------------------------------------------
function widgets:RenderCursor(name, x, y, width, height, tfade, cb)
if self.cursorStates[name] == nil then
local mistate = { name=name, alpha=0.0, state=CAIRO_STATE.SO_STATES.INITIAL, pos=0, posw=0 }
local newtween = tween( tfade, mistate, { alpha=1.0 }, 'inQuad', TweenDone, self.cursorStates, name )
mistate.tween = newtween
self.cursorStates[name] = mistate
end
local saved = self.style.button_color
local mistate = self.cursorStates[name]
-- Cursor Flashing
if mistate.state == CAIRO_STATE.SO_STATES.INITIAL then
self.style.button_color = { r=1, g=1, b=1, a=mistate.alpha }
self:RenderBox( x, y, width, height, 0 )
if mistate.tween == nil then
mistate.tween = tween( tfade, mistate, { alpha=0.0 }, 'inQuad', TweenDone, self.cursorStates, name )
self.style.image_color = {r=1, g=1, b=1, a=1}
mistate.state=CAIRO_STATE.SO_STATES.MOVING_OUT
end
-- Cursor Flashing
elseif mistate.state == CAIRO_STATE.SO_STATES.MOVING_OUT then
self.style.button_color = { r=1, g=1, b=1, a=mistate.alpha }
self:RenderBox( x, y, width, height, 0 )
if mistate.tween == nil then
mistate.tween = tween( tfade, mistate, { alpha=1.0 }, 'inQuad', TweenDone, self.cursorStates, name )
self.style.image_color = {r=1, g=1, b=1, a=1}
mistate.state=CAIRO_STATE.SO_STATES.INITIAL
end
end
self.style.button_color = saved
end
------------------------------------------------------------------------------------------------------------
function widgets:RenderMultiImage(name, image_list, x, y, tdelay, tfade, cb)
local saved = self.style.image_color
local icount = table.getn(image_list)
if icount == 0 then return end
if self.multiImageStates[name] == nil then
local mistate = { name=name, alpha=0.0, state=CAIRO_STATE.SO_STATES.INITIAL, current=1 }
local newtween = tween( tfade, mistate, { alpha=1.0 }, 'inQuad', TweenDone, self.multiImageStates, name )
mistate.tween = newtween
self.multiImageStates[name] = mistate
end
local mistate = self.multiImageStates[name]
-- print("State:", mistate.state, "Alpha:", mistate.alpha, "Tween:",mistate.tween)
-- Fading in..
if mistate.state == CAIRO_STATE.SO_STATES.INITIAL then
self.style.image_color = {r=1, g=1, b=1, a=mistate.alpha}
self:ButtonImage(name..string.format("_%03d", mistate.current), image_list[mistate.current], x, y, cb)
if mistate.tween == nil then
mistate.tween = tween( tdelay, mistate, { alpha=1.0 }, 'inQuad', TweenDone, self.multiImageStates, name )
self.style.image_color = {r=1, g=1, b=1, a=1}
mistate.state=CAIRO_STATE.SO_STATES.MOVING_OUT
end
-- Waiting for next fade out..
elseif mistate.state == CAIRO_STATE.SO_STATES.MOVING_OUT then
self:ButtonImage(name..string.format("_%03d", mistate.current), image_list[mistate.current], x, y, cb)
if mistate.tween == nil then
mistate.tween = tween( tfade, mistate, { alpha=0.0 }, 'inQuad', TweenDone, self.multiImageStates, name )
self.style.image_color = {r=1, g=1, b=1, a=1}
mistate.state=CAIRO_STATE.SO_STATES.OUT
end
-- Fading out..
elseif mistate.state == CAIRO_STATE.SO_STATES.OUT then
self.style.image_color = {r=1, g=1, b=1, a=mistate.alpha}
self:ButtonImage(name..string.format("_%03d", mistate.current), image_list[mistate.current], x, y, cb)
if mistate.tween == nil then
mistate.tween = tween( tfade, mistate, { alpha=1.0 }, 'inQuad', TweenDone, self.multiImageStates, name )
mistate.state=CAIRO_STATE.SO_STATES.INITIAL
mistate.current = mistate.current + 1
if mistate.current > icount then mistate.current = 1 end
end
end
-- Flip pic.. start again..
self.style.image_color = saved
end
------------------------------------------------------------------------------------------------------------
function widgets:RenderMultiSlideImage(name, image_list, x, y, swidth, tdelay, sspeed, cb)
local icount = table.getn(image_list)
if icount == 0 then return end
if self.multiImageStates[name] == nil then
local timage = image_list[1]
local imagex = timage.width * timage.scalex
local targetx = (x + swidth * 0.5) - imagex * 0.5
local mistate = { name=name, xpos=x-imagex, state=CAIRO_STATE.SO_STATES.INITIAL, current=1 }
local newtween = tween( sspeed, mistate, { xpos=targetx }, 'inCubic', TweenDone, self.multiImageStates, name )
mistate.tween = newtween
self.multiImageStates[name] = mistate
end
local mistate = self.multiImageStates[name]
-- print("State:", mistate.state, "Alpha:", mistate.alpha, "Tween:",mistate.tween)
local timage = image_list[mistate.current]
self:ClipRegion( x, y, swidth, timage.height * timage.scaley )
local nameid = name..string.format("_%03d", mistate.current)
-- Fading in..
if mistate.state == CAIRO_STATE.SO_STATES.INITIAL then
self:ButtonImage(nameid, image_list[mistate.current], mistate.xpos, y, cb)
if mistate.tween == nil then
local imagex = timage.width * timage.scalex
local targetx = (x + swidth * 0.5) - imagex * 0.5
mistate.tween = tween( tdelay, mistate, { xpos=targetx }, 'inCubic', TweenDone, self.multiImageStates, name )
mistate.state=CAIRO_STATE.SO_STATES.MOVING_OUT
end
-- Fading in..
elseif mistate.state == CAIRO_STATE.SO_STATES.MOVING_OUT then
self:ButtonImage(nameid, image_list[mistate.current], mistate.xpos, y, cb)
if mistate.tween == nil then
mistate.tween = tween( sspeed, mistate, { xpos=x+swidth }, 'inCubic', TweenDone, self.multiImageStates, name )
mistate.state=CAIRO_STATE.SO_STATES.OUT
end
-- Fading out..
elseif mistate.state == CAIRO_STATE.SO_STATES.OUT then
self:ButtonImage(nameid, image_list[mistate.current], mistate.xpos, y, cb)
if mistate.tween == nil then
mistate.current = mistate.current + 1
if mistate.current > icount then mistate.current = 1 end
local timage = image_list[mistate.current]
local imagex = timage.width * timage.scalex
local targetx = (x + swidth * 0.5) - imagex * 0.5
mistate.xpos = x-timage.width * timage.scalex
mistate.tween = tween( sspeed, mistate, { xpos=targetx }, 'inCubic', TweenDone, self.multiImageStates, name )
mistate.state=CAIRO_STATE.SO_STATES.INITIAL
end
end
self:ClipReset()
end
------------------------------------------------------------------------------------------------------------
function widgets:RenderButton(button, angle)
local style = self.style
self:RenderBox( button.left-style.border_width, button.top-style.border_width, button.width+style.border_width, button.height+style.border_width, button.corner )
self:ClipRegion(button.left-style.border_width, button.top-style.border_width, button.width+style.border_width, button.height+style.border_width)
local bs = button.height
if(bs > button.width) then bs = button.width end
cr.cairo_save(self.ctx)
cr.cairo_translate(self.ctx, button.left, button.top)
if(math.abs(angle) > 0.0) then
cr.cairo_rotate(self.ctx, angle)
cr.cairo_translate(self.ctx, 0.0, -bs)
end
self:RenderText( button.name, 0, bs * 0.85, bs, button.color )
cr.cairo_restore(self.ctx)
self:ClipReset()
end
------------------------------------------------------------------------------------------------------------
function widgets:Button(name, left, top, width, height, corner, border, cb, meta)
--if(oldButton) then return oldButton end
local newButton = { name=name, top=top, left=left, width=width, height=height, corner=corner, border=border }
-- Must add to a managed list to detect clip regions for mouse over etc.
-- Check it doesnt already exist!
self:AddObject(newButton, CAIRO_TYPE.BUTTON, cb, meta)
return newButton
end
------------------------------------------------------------------------------------------------------------
function widgets:List(name, left, top, width, height)
-- Work out "where" the panel is currently (list slider).
local state = {}
if(self.listStates[name] == nil) then
state = { state=CAIRO_STATE.SO_STATES.INITIAL, move=0, scroll=0, target=1.0 }
else
state = self.listStates[name]
end
local newListBox = {
otype = CAIRO_TYPE.LISTBOX, name=name, top=top, left=left, width=width, height=height, nodes = {}
}
self:AddObject(newListBox, CAIRO_TYPE.LISTBOX)
return newListBox
end
------------------------------------------------------------------------------------------------------------
function TextBoxHandler( object, cairo )
return function ( textbox, cstate, cairo )
local dlen = string.len(textbox.data)
local tbl = gSdisp.wm.KeyUp
local shifted = 0
local modified = 0
local tdata = textbox.data
object.changed = nil
if #tbl > 0 then object.changed = true end
-- TODO: This needs some work - would prefer this in a table of callbacks
for k,v in pairs(tbl) do
if v.scancode == sdl.SDL_SCANCODE_RETURN or v.scancode == sdl.SDL_SCANCODE_GRAVE then
modified = 1
elseif v.scancode == sdl.SDL_SCANCODE_RIGHT then
if cstate.pos < dlen-1 then cstate.pos = cstate.pos+1 end
modified = 1
elseif v.scancode == sdl.SDL_SCANCODE_LEFT then
if cstate.pos > 0 then cstate.pos = cstate.pos-1 end
modified = 1
elseif v.scancode == sdl.SDL_SCANCODE_DELETE then
if cstate.pos < dlen then
local left = string.sub(tdata, 1, cstate.pos)
local right = string.sub(tdata, cstate.pos+2, dlen)
if cstate.pos == dlen then cstate.pos = cstate.pos - 1 end
tdata = left..right
end
modified = 1
elseif v.scancode == sdl.SDL_SCANCODE_BACKSPACE then
if cstate.pos > 0 and cstate.pos <= dlen then
local left = string.sub(tdata, 1, cstate.pos-1)
local right = string.sub(tdata, cstate.pos+1)
cstate.pos = cstate.pos - 1
tdata = left..right
end
modified = 1
elseif v.mod == sdl.KMOD_RSHIFT or v.mod == sdl.KMOD_LSHIFT then
shifted = 1
elseif v.scancode > 0 and v.scancode < sdl.SDL_SCANCODE_CAPSLOCK and modified == 0 then
local char1 = string.char(v.sym)
if shifted == 1 then
char1 = string.upper(char1)
if char1 == '9' then char1 = '(' end
if char1 == '0' then char1 = ')' end
if char1 == '[' then char1 = '{' end
if char1 == ']' then char1 = '}' end
if char1 == "'" then char1 = '"' end
if char1 == ';' then char1 = ':' end
end
if dlen == 0 then
tdata = char1
cstate.pos = 0
else
if dlen == 1 then
tdata = tdata..char1
cstate.pos = 1
else
local left = string.sub(tdata, 1, cstate.pos)
local right = string.sub(tdata, cstate.pos+1)
tdata = left..char1..right
end
end
cstate.pos = cstate.pos + 1
end
end
local subtext = string.sub( tdata, 1, cstate.pos )
cstate.posw = cairo:GetTextSize( subtext, textbox.height )
return tdata
end
end
------------------------------------------------------------------------------------------------------------
function widgets:TextBox(name, left, top, width, height, target_table, col )
local cw, ch = self:GetTextSize(" ", height)
local ca, cd = self:GetFontExtents()
local newTextBox = {
otype = CAIRO_TYPE.TEXTBOX, name=name, top=top, left=left, width=width, height=height,
data=target_table, color=col, cursorw = cw, cursora = cd, changed = nil
}
-- Add to a managed list?
self:AddObject( newTextBox, CAIRO_TYPE.TEXTBOX, TextBoxHandler( newTextBox, self ) )
return newTextBox
end
------------------------------------------------------------------------------------------------------------
function widgets:GetLineSize(line)
-- When elements are added or changed, remember to set contentsize to nil
if line.contentsize then return line.contentsize end
local listNodes = line.nodes
local linesize = 0
for k,v in pairs(listNodes) do
-- Done include "space" in the calc - space should only effect horizontal.
if(v.size ~= nil) then
if((v.size > linesize) and (v.ntype ~= nil)) then linesize = v.size end
end
end
line.contentsize = linesize
return linesize
end
------------------------------------------------------------------------------------------------------------
function widgets:RenderLine(line, left, top)
local listNodes = line.nodes
local tleft = left
local linesize = 0
for k,v in pairs(listNodes) do
if v.ntype == CAIRO_TYPE.LIST then
local state = self:GetListState(v.list)
self:RenderList(state, v.cobject, tleft, top )
tleft = tleft + v.list.width
elseif v.ntype == CAIRO_TYPE.TEXT then
tcolor = {r=1, g=1, b=1, a=1}
local textsz = self:GetTextSize(v.name, v.size)
if(v.callback) then
local button = self:Button(v.name, tleft, top, textsz, v.size, v.corner, v.border, v.callback, v.meta)
if v.meta then button.meta = v.meta end
end
self:RenderText(v.name, tleft, top + v.size * 0.85, v.size, tcolor )
tleft = tleft + textsz
elseif v.ntype == CAIRO_TYPE.BUTTON then
if v.width == nil then v.width = self:GetTextSize(v.name, v.size) end
local button = self:Button(v.name, tleft, top, v.width, v.size, v.corner, v.border, v.callback, v.meta)
self:RenderButton(button, 0.0)
tleft = tleft + v.width
elseif v.ntype == CAIRO_TYPE.IMAGE then
v.image.scalex = v.size / v.image.width
v.image.scaley = v.size / v.image.height
if(v.callback) then
local button = self:Button(v.name, tleft, top, v.image.width * v.image.scalex, v.size, v.corner, v.border, v.callback, v.meta)
if v.meta then button.meta = v.meta end
end
self:RenderImage(v.image, tleft, top, 0.0, v.callback)
tleft = tleft + v.image.width * v.image.scalex
elseif v.ntype == CAIRO_TYPE.EXPLODER then
v.image.scalex = v.size / v.image.width
v.image.scaley = v.size / v.image.height
self:Exploder(v.name, v.image, tleft, top, v.image.width * v.image.scalex, v.size, v.corner, v.list)
tleft = tleft + v.image.width * v.image.scalex
end
if (v.ntype == nil) and (v.size ~= nil) then
tleft = tleft + v.size
end
-- Done include "space" in the calc - space should only effect horizontal.
if(v.size ~= nil) then
if((v.size > linesize) and (v.ntype ~= nil)) then linesize = v.size end
end
end
return linesize
end
------------------------------------------------------------------------------------------------------------
function widgets:GetListSize(list)
-- When elements are added or changed, remember to set contentsize to nil
if list.contentsize then return list.contentsize end
local listNodes = list.nodes
local listsize = 0
for k,v in pairs(listNodes) do
local lsize = v.size
if v.ntype == CAIRO_TYPE.HLINE then
lsize = self:GetLineSize(v)
end
listsize = listsize + lsize
end
list.contentsize = listsize
return listsize
end
------------------------------------------------------------------------------------------------------------
-- List Utility functions
function widgets:ListAddSpace( tbl, textsize )
local linedata = { name = "space", size = textsize }
table.insert( tbl, linedata )
end
------------------------------------------------------------------------------------------------------------
function widgets:ListAddText( tbl, text, textsize, callback, meta )
local linedata = { ntype = CAIRO_TYPE.TEXT, name = text, size = textsize, callback = callback, meta = meta }
table.insert( tbl, linedata )
end
------------------------------------------------------------------------------------------------------------
function widgets:ListAddImage( tbl, name, image, textsize, colour, callback, meta )
local linedata = { ntype = CAIRO_TYPE.IMAGE, name = name, image = image, size = textsize, color = colour, callback = callback, meta = meta }
table.insert( tbl, linedata )
end
------------------------------------------------------------------------------------------------------------
function widgets:ListAddButton( tbl, name, image, textsize, colour, callback, meta )
local linedata = { ntype = CAIRO_TYPE.BUTTON, name = name, image = image, size = textsize, color = colour, callback = callback, meta = meta }
table.insert( tbl, linedata )
end
------------------------------------------------------------------------------------------------------------
function widgets:ListAddExploder( tbl, name, image, width, height, list )
local linedata = { ntype = CAIRO_TYPE.EXPLODER, name = name, width = width, height = height, list = list }
table.insert( tbl, linedata )
end
------------------------------------------------------------------------------------------------------------
function widgets:ListAddLine( tbl, hline, name, size )
local linedata = { ntype = CAIRO_TYPE.HLINE, name = name, size = size, nodes = hline }
table.insert( tbl, linedata )
end
------------------------------------------------------------------------------------------------------------
function widgets:GetListState(list)
local state = {}
if(self.listStates[list.name] == nil) then
state = { state=CAIRO_STATE.SO_STATES.INITIAL, move=0, scroll=0, target=1.0, selected=0 }
self.listStates[list.name] = state
else
state = self.listStates[list.name]
end
return state
end
------------------------------------------------------------------------------------------------------------
function widgets:RenderList(state, list, left, top, select)
-- If no state has been defined, then make one to match the list name (this will generate a ListName state)
if state == nil then
state = self:GetListState(list)
end
local ttop = top
local style = self.style
list.region = { left=left-style.border_width, top=top-style.border_width,
width=list.width+style.border_width, height=list.height+style.border_width }
self:ClipRegion( list.region.left, list.region.top, list.region.width, list.region.height )
self:RenderBox( list.region.left, list.region.top, list.region.width, list.region.height, style.corner_size )
-- Get list size of content - if it is too big then need to make a scroll indicator
local listSize = self:GetListSize(list)
-- if need scroll control / indicators then work it out..
if listSize > list.height then
if( state.scroll > 0 ) then state.scroll = 0 end
if( state.scroll < -(listSize - list.height) ) then state.scroll = -(listSize - list.height) end
ttop = ttop + state.scroll
end
local listNodes = list.nodes
for k,v in pairs(listNodes) do
local lsize = v.size
if v.ntype == CAIRO_TYPE.TEXT then
tcolor = {r=1, g=1, b=1, a=1}
if(v.callback) then
local textsz = self:GetTextSize(v.name, v.size)
local button = self:Button(v.name, left, ttop, textsz, v.size, v.corner, v.border, v.callback)
end
self:RenderText(v.name, left, ttop + v.size * 0.85, v.size, tcolor )
elseif v.ntype == CAIRO_TYPE.BUTTON then
local button = self:Button(v.name, left, ttop, list.width, v.size, v.corner, v.border, v.callback)
self:RenderButton(button, 0.0)
elseif v.ntype == CAIRO_TYPE.IMAGE then
v.image.scalex = v.size / v.image.width
local halfx = 0.5 * v.image.width * v.image.scalex
v.image.scaley = v.size / v.image.height
local halfy = 0.5 * v.image.height * v.image.scaley
if(v.callback) then
local button = self:Button(v.name, left, ttop, v.image.width * v.image.scalex, v.size, v.corner, v.border, v.callback)
end
self:RenderImage(v.image, left + halfx, ttop + halfy, 0.0, v.callback)
elseif v.ntype == CAIRO_TYPE.EXPLODER then
widgets:Exploder(v.name, v.image, left, ttop, v.width, v.height, v.corner, v.list)
elseif v.ntype == CAIRO_TYPE.HLINE then
lsize = self:RenderLine(v, left, ttop)
end
if select == k then
self.img_select.scalex = 0.4
self.img_select.scaley = 0.4
self:RenderImage(self.img_select, left+list.width * 0.6, ttop, 0.0)
end
ttop = ttop + (lsize)
end
-- Render overlayed indicators.. for scrolling
if listSize > list.height then
local scrollheight = listSize - list.height
local left1 = left-style.border_width+list.width-self.img_arrowup.width * self.img_arrowup.scalex
local left2 = left-style.border_width+list.width-self.img_arrowdn.width * self.img_arrowup.scalex
local top2 = top-style.border_width+list.height-self.img_arrowdn.height * self.img_arrowup.scaley
if( state.scroll > -scrollheight ) then self:RenderImage( self.img_arrowup, left1, top-style.border_width, 0) end
if( state.scroll < 0 ) then self:RenderImage( self.img_arrowdn, left2, top2, 0) end
end
self:ClipReset()
end
------------------------------------------------------------------------------------------------------------
-- SlideOut Callback just moves to next state
local function SlideOutHandler( name, cairo_obj)
local sostate = cairo_obj.slideOutStates[name]
-- Dont bother if nothing exists!
if(sostate == nil) then return end
-- Change to moving on this callback (callback is a mouse up)
if(sostate.state == CAIRO_STATE.SO_STATES.OUT) then
sostate.state = CAIRO_STATE.SO_STATES.MOVING_OUT
sostate.tween = tween( sostate.speed, sostate, { move=sostate.target }, CAIRO_UI.SLIDER_MODE, TweenDone, cairo_obj.slideOutStates, name)
return
end
if(sostate.state == CAIRO_STATE.SO_STATES.IN) then
sostate.state = CAIRO_STATE.SO_STATES.MOVING_IN
sostate.tween = tween( sostate.speed, sostate, { move=0 }, CAIRO_UI.SLIDER_MODE, TweenDone, cairo_obj.slideOutStates, name)
return
end
end
------------------------------------------------------------------------------------------------------------
-- Return current position
function widgets:SlideOut(name, image, align, pos, size, corner, list, speed)
-- Work out "where" the slideout is currently.
if(self.slideOutStates[name] == nil) then
state = { state=CAIRO_STATE.SO_STATES.INITIAL, move=0, scroll=0, target=list.width, speed=speed }
else
state = self.slideOutStates[name]
end
if(state.speed == nil) then state.speed = CAIRO_UI.SLIDER_TWEEN_SPEED end
local style = self.style
local left = state.move;
local top = pos;
local width = size
local height = list.height;
local lleft = left - list.width
local ltop = top
if(align == CAIRO_UI.RIGHT) then left = self.WIDTH - state.move - size; top = pos; lleft = self.WIDTH - state.move; end
if(align == CAIRO_UI.TOP) then left = pos; top = state.move; width = list.width; height = size; state.target = list.height; lleft = left; ltop = top - list.height; end
if(align == CAIRO_UI.BOTTOM) then left = pos; top = self.HEIGHT - state.move - size; width = list.width; height = size; state.target = list.height; lleft = left; ltop = top + size; end
-- Draw the list
if(state.move > 0) then
-- Clip within the list box
self:RenderList(state, list, lleft, ltop)
end
local tcolor = { r=1, g=1, b=1, a=1 }
local button = self:Button(name, left, top, width, height, corner, 6 )
if(image) then
button = image
button.left = left; button.top = top
button.scalex = size / image.width; button.scaley = size / image.height
self:RenderImage(image, button.left, button.top, 0, 1)
else
local angle = 0
-- Draw the button
if(align == CAIRO_UI.LEFT) or (align == CAIRO_UI.RIGHT) then angle = math.pi * 0.5 end
self:RenderButton(button, angle)
end
local newSlideOut = { name=name, button=button, list=list }
self.slideOutStates[name] = state
self:AddObject( newSlideOut, CAIRO_TYPE.SLIDEOUT, coroutine.create(SlideOutHandler) )
end
------------------------------------------------------------------------------------------------------------
-- Exploder Callback just moves to next state
local function ExploderHandler(name, cairo_obj)
-- Dont bother if nothing exists!
--if(self.exploderStates[name] == nil) then return end
-- Handle the object - this is a ref remember!!!
local sostate = cairo_obj.exploderStates[name]
-- Change to moving on this callback (callback is a mouse up)
if(sostate.state == CAIRO_STATE.SO_STATES.OUT) then
sostate.state = CAIRO_STATE.SO_STATES.MOVING_OUT
sostate.tween = tween(sostate.speed, sostate, { move=1.0 }, CAIRO_UI.EXPLODER_MODE, TweenDone, cairo_obj.exploderStates, name)
return
end
if(sostate.state == CAIRO_STATE.SO_STATES.IN) then
sostate.state = CAIRO_STATE.SO_STATES.MOVING_IN
sostate.tween = tween(sostate.speed, sostate, { move=0 }, CAIRO_UI.EXPLODER_MODE, TweenDone, cairo_obj.exploderStates, name)
return
end
end
------------------------------------------------------------------------------------------------------------
-- Return current position
function widgets:Exploder(name, image, align, x, y, hsize, vsize, corner, list, speed)
-- Work out "where" the exploder is currently.
if(self.exploderStates[name] == nil) then
state = { state=CAIRO_STATE.SO_STATES.INITIAL, move=0, scroll=0, target=1.0, speed=speed }
else
state = self.exploderStates[name]
end
if(state.speed == nil) then state.speed = CAIRO_UI.EXPLODER_TWEEN_SPEED end
local left = x;
local top = y;
local button = nil
local aleft = 0
local atop = 10
local adir = 0
local aoff = 10
if(list.arrows == nil) then aoff = 0 end
local tpos = { 10, -10 }
if(align == CAIRO_UI.RIGHT) then aleft = hsize + aoff; atop = 0.0; adir = 90; tpos = { -10, 10 } end
if(align == CAIRO_UI.BOTTOM) then aleft = 0.0; atop = vsize + aoff; end
if(list.arrows == nil) then tpos = nil end
-- Draw the list
if(state.move > 0.1) then
cr.cairo_save(self.ctx)
cr.cairo_translate(self.ctx, left + aleft, top + atop)
if tpos then self:DrawTriangle( tpos, adir, 8, 16 ) end
cr.cairo_scale(self.ctx, state.move, state.move)
cr.cairo_translate(self.ctx, -left-aleft, -top - atop)
self:RenderList(state, list, left+aleft, top + atop)
cr.cairo_restore(self.ctx)
end
if(image) then
button = image
button.left = x; button.top = y
button.scalex = hsize / image.width; button.scaley = vsize / image.height
self:RenderImage(image, button.left, button.top, 0, 1)
else
button = self:Button(name, left, top, hsize, vsize, corner, 6 )
self:RenderButton(button, 0.0)
end
local newExploder = { name=name, button=button, list=list }
self.exploderStates[name] = state
self:AddObject( newExploder, CAIRO_TYPE.EXPLODER, coroutine.create(ExploderHandler) )
end
------------------------------------------------------------------------------------------------------------
-- Return current position
function widgets:Panel(name, posx, posy, size, corner, list, select )
local style = self.style
local left = posx;
local top = posy;
local width = list.width + list.left
local height = list.height + list.top;
local lleft = left + list.left
local ltop = top + list.top + size
local state = self:GetListState(list)
-- Draw the list
-- Clip within the list box
self:RenderList(state, list, lleft, ltop, select)
local tcolor = { r=1, g=1, b=1, a=1 }
local button = self:Button(name, left, top, width, size, corner, 6 )
local newPanel = { name=name, button=button, list=list }
if size > 0 then self:RenderButton(button, 0.0) end
self:AddObject( newPanel, CAIRO_TYPE.PANEL )
end
------------------------------------------------------------------------------------------------------------
-- Really... this is what Panel should have been. Panel is a little more flexible,
-- PanelList is used for displaying a list of panel text, nothing else.
function widgets:PanelListText(name, posx, posy, headsize, textsize, width, height, textlist )
local listid = "PanelListText"..tostring(textlist)
local tlist = self:List(listid, 0, 0, width, height)
local snodes = {}
local i = 1
for k,v in pairs(textlist) do
local nline1 = { name="space1", size=8 }
local nline2 = {
{ name="space1", size=2 },
{ name=v, ntype=CAIRO_TYPE.TEXT, size=textsize, color=tcolor }
}
local nline2ref = { name="line2", ntype=CAIRO_TYPE.HLINE, size=textsize, nodes = nline2 }
snodes[i] = nline1; i=i+1
snodes[i] = nline2ref; i=i+1
end
snodes[i] = { name = "space1", size=12 }; i=i+1
tlist.nodes = snodes
self:Panel(name, posx, posy, headsize, 0, tlist)
end
------------------------------------------------------------------------------------------------------------
local function CairoChangeFolder(callerobj, wcairo)
--print("*************", callerobj.name, wcairo.file_FileSelect)
wcairo.file_NewFolder = callerobj.name
end
------------------------------------------------------------------------------------------------------------
local function CairoSelectFile(callerobj, wcairo)
--print("------------", callerobj.name, wcairo.file_FileSelect)
if callerobj.name ~= "." and callerobj.name ~= ".." then
wcairo.file_LastSelect = wcairo.file_FileSelect
wcairo.file_FileSelect = callerobj.name
wcairo.file_preview_obj = nil
end
end
------------------------------------------------------------------------------------------------------------
function widgets:RenderDirectory(left, top, width, height)
if self.currdir == nil then return end
if self.dirlist == nil then self.dirlist = dir:listfolder(self.currdir) end
-- A Content window of 'stuff' to show
local list_assets = Gcairo:List("dirlist", 0, 0, width, height-20)
local snodes = {}
local i = 1
local line1 = {
{ name="space1", size=116 }
}
for k,v in pairs(self.dirlist) do
local nline1 = { name="space1", size=8 }
local nline2 = {
{ name="space1", size=6 },
{ name="space1", size=18 },
{ name="space1", size=6 },
{ name=v.name, ftype=v.ftype, ntype=CAIRO_TYPE.TEXT, size=18 }
}
if self.file_FileSelect == v.name then
nline2[2] = { name=v.name, ntype=CAIRO_TYPE.IMAGE, image=self.img_select, size=18, color=tcolor }
self.select_file = k
end
if v.ftype == 2 then
nline2[2] = { name=v.name, ntype=CAIRO_TYPE.IMAGE, image=self.img_folder, size=18, color=tcolor, callback=CairoChangeFolder }
nline2[4].callback = CairoChangeFolder
else
nline2[4].callback = CairoSelectFile
nline2[2].callback = CairoSelectFile
end
local nline2ref = { name="line2", ntype=CAIRO_TYPE.HLINE, size=18, nodes = nline2 }
if v.name ~= "." then
snodes[i] = nline1; i=i+1
snodes[i] = nline2ref; i=i+1
end
end
snodes[i] = { name = "space1", size=22 }; i=i+1
snodes[i] = { name = "line1", ntype=CAIRO_TYPE.HLINE, size=18 , nodes=line1 }; i=i+1
snodes[i] = { name = "space1", size=6 }; i=i+1
list_assets.nodes = snodes
--Gcairo.style.button_color = { r=0.6, g=0.3, b=0.3, a=1.0 }
Gcairo:Panel(" "..self.currdir, left, top, 20, 0, list_assets )
-- If folder has changed, then update
if self.file_NewFolder ~= nil then
-- Handle "up one directory differently
if self.file_NewFolder == ".." then
local s, e, m = string.find(self.currdir, ".*/([^/]+)")
-- print("Found:",self.currdir,s,e,m)
if s ~= nil and e ~= nil and m ~= nil then
self.currdir = string.sub(self.currdir, 1, e-string.len(m)-1)
end
self.preview_image = nil
else
self.currdir = self.currdir.."/"..self.file_NewFolder
end
self.dirlist = dir:listfolder(self.currdir)
self.file_NewFolder = nil
end
if (self.file_FileSelect ~= self.file_LastSelect) and (self.file_FileSelect ~= nil) then
local exttype = dir:getextension(self.file_FileSelect)
--print("Extension:", exttype, self.file_FileSelect)
local extobj = self.ExtensionFunc[exttype]
if extobj ~= nil then
--print("File:", self.currdir, self.file_FileSelect)
extobj.func(extobj.obj, self.file_FileSelect)
self.file_LastSelect = self.file_FileSelect
end
end
end
------------------------------------------------------------------------------------------------------------
function widgets:SetExtensionCallbacks(funcext)
self.ExtensionFunc = funcext
end
------------------------------------------------------------------------------------------------------------
return widgets
------------------------------------------------------------------------------------------------------------
|
--[[
This file is part of YunWebUI.
YunWebUI is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
As a special exception, you may use this file as part of a free software
library without restriction. Specifically, if other files instantiate
templates or use macros or inline functions from this file, or you compile
this file and link it with other files to produce an executable, this
file does not by itself cause the resulting executable to be covered by
the GNU General Public License. This exception does not however
invalidate any other reasons why the executable file might be covered by
the GNU General Public License.
Copyright 2013 Arduino LLC (http://www.arduino.cc/)
]]
module("luci.controller.arduino.index", package.seeall)
local function not_nil_or_empty(value)
return value and value ~= ""
end
local function get_first(cursor, config, type, option)
return cursor:get_first(config, type, option)
end
local function set_first(cursor, config, type, option, value)
cursor:foreach(config, type, function(s)
if s[".type"] == type then
cursor:set(config, s[".name"], option, value)
end
end)
end
local function to_key_value(s)
local parts = luci.util.split(s, ":")
parts[1] = luci.util.trim(parts[1])
parts[2] = luci.util.trim(parts[2])
return parts[1], parts[2]
end
function http_error(code, text)
luci.http.prepare_content("text/plain")
luci.http.status(code)
if text then
luci.http.write(text)
end
end
function index()
function luci.dispatcher.authenticator.arduinoauth(validator, accs, default)
require("luci.controller.arduino.index")
local user = luci.http.formvalue("username")
local pass = luci.http.formvalue("password")
local basic_auth = luci.http.getenv("HTTP_AUTHORIZATION")
if user and validator(user, pass) then
return user
end
if basic_auth and basic_auth ~= "" then
local decoded_basic_auth = nixio.bin.b64decode(string.sub(basic_auth, 7))
user = string.sub(decoded_basic_auth, 0, string.find(decoded_basic_auth, ":") - 1)
pass = string.sub(decoded_basic_auth, string.find(decoded_basic_auth, ":") + 1)
end
if user then
if #pass ~= 64 and validator(user, pass) then
return user
elseif #pass == 64 then
local uci = luci.model.uci.cursor()
uci:load("yunbridge")
local stored_encrypted_pass = uci:get_first("yunbridge", "bridge", "password")
if pass == stored_encrypted_pass then
return user
end
end
end
luci.http.header("WWW-Authenticate", "Basic realm=\"yunbridge\"")
luci.http.status(401)
return false
end
local function make_entry(path, target, title, order)
local page = entry(path, target, title, order)
page.leaf = true
return page
end
-- web panel
local webpanel = entry({ "webpanel" }, alias("webpanel", "go_to_homepage"), _("%s Web Panel") % luci.sys.hostname(), 10)
webpanel.sysauth = "root"
webpanel.sysauth_authenticator = "arduinoauth"
make_entry({ "webpanel", "go_to_homepage" }, call("go_to_homepage"), nil)
--api security level
local uci = luci.model.uci.cursor()
uci:load("yunbridge")
local secure_rest_api = uci:get_first("yunbridge", "bridge", "secure_rest_api")
local rest_api_sysauth = false
if secure_rest_api == "true" then
rest_api_sysauth = webpanel.sysauth
end
--storage api
local data_api = node("data")
data_api.sysauth = rest_api_sysauth
data_api.sysauth_authenticator = webpanel.sysauth_authenticator
make_entry({ "data", "get" }, call("storage_send_request"), nil).sysauth = rest_api_sysauth
make_entry({ "data", "put" }, call("storage_send_request"), nil).sysauth = rest_api_sysauth
make_entry({ "data", "delete" }, call("storage_send_request"), nil).sysauth = rest_api_sysauth
local mailbox_api = node("mailbox")
mailbox_api.sysauth = rest_api_sysauth
mailbox_api.sysauth_authenticator = webpanel.sysauth_authenticator
make_entry({ "mailbox" }, call("build_bridge_mailbox_request"), nil).sysauth = rest_api_sysauth
--plain socket endpoint
local plain_socket_endpoint = make_entry({ "arduino" }, call("board_plain_socket"), nil)
plain_socket_endpoint.sysauth = rest_api_sysauth
plain_socket_endpoint.sysauth_authenticator = webpanel.sysauth_authenticator
end
function go_to_homepage()
luci.http.redirect("/index.html")
end
local function build_bridge_request(command, params)
local bridge_request = {
command = command
}
if command == "raw" then
params = table.concat(params, "/")
if not_nil_or_empty(params) then
bridge_request["data"] = params
end
return bridge_request
end
if command == "get" then
if not_nil_or_empty(params[1]) then
bridge_request["key"] = params[1]
end
return bridge_request
end
if command == "put" and not_nil_or_empty(params[1]) and params[2] then
bridge_request["key"] = params[1]
bridge_request["value"] = params[2]
return bridge_request
end
if command == "delete" and not_nil_or_empty(params[1]) then
bridge_request["key"] = params[1]
return bridge_request
end
return nil
end
local function extract_jsonp_param(query_string)
if not not_nil_or_empty(query_string) then
return nil
end
local qs_parts = string.split(query_string, "&")
for idx, value in ipairs(qs_parts) do
if string.find(value, "jsonp") == 1 or string.find(value, "callback") == 1 then
return string.sub(value, string.find(value, "=") + 1)
end
end
end
local function parts_after(url_part)
local url = luci.http.getenv("PATH_INFO")
local url_after_part = string.find(url, "/", string.find(url, url_part) + 1)
if not url_after_part then
return {}
end
return luci.util.split(string.sub(url, url_after_part + 1), "/")
end
function storage_send_request()
local method = luci.http.getenv("REQUEST_METHOD")
local jsonp_callback = extract_jsonp_param(luci.http.getenv("QUERY_STRING"))
local parts = parts_after("data")
local command = parts[1]
if not command or command == "" then
luci.http.status(404)
return
end
local params = {}
for idx, param in ipairs(parts) do
if idx > 1 and not_nil_or_empty(param) then
table.insert(params, param)
end
end
-- TODO check method?
local bridge_request = build_bridge_request(command, params)
if not bridge_request then
luci.http.status(403)
return
end
local uci = luci.model.uci.cursor()
uci:load("yunbridge")
local socket_timeout = uci:get_first("yunbridge", "bridge", "socket_timeout", 5)
local sock, code, msg = nixio.connect("127.0.0.1", 5700)
if not sock then
code = code or ""
msg = msg or ""
http_error(500, "nil socket, " .. code .. " " .. msg)
return
end
sock:setopt("socket", "sndtimeo", socket_timeout)
sock:setopt("socket", "rcvtimeo", socket_timeout)
sock:setopt("tcp", "nodelay", 1)
local json = require("luci.json")
sock:write(json.encode(bridge_request))
sock:writeall("\n")
local response_text = {}
while true do
local bytes = sock:recv(4096)
if bytes and #bytes > 0 then
table.insert(response_text, bytes)
end
local json_response = json.decode(table.concat(response_text))
if json_response then
sock:close()
luci.http.status(200)
if jsonp_callback then
luci.http.prepare_content("application/javascript")
luci.http.write(jsonp_callback)
luci.http.write("(")
luci.http.write_json(json_response)
luci.http.write(");")
else
luci.http.prepare_content("application/json")
luci.http.write(json.encode(json_response))
end
return
end
if not bytes or #response_text == 0 then
sock:close()
http_error(500, "Empty response")
return
end
end
sock:close()
end
function board_plain_socket()
local function send_response(response_text, jsonp_callback)
if not response_text then
luci.http.status(500)
return
end
local rows = luci.util.split(response_text, "\r\n")
if #rows == 1 or string.find(rows[1], "Status") ~= 1 then
luci.http.prepare_content("text/plain")
luci.http.status(200)
luci.http.write(response_text)
return
end
local body_start_at_idx = -1
local content_type = "text/plain"
for idx, row in ipairs(rows) do
if row == "" then
body_start_at_idx = idx
break
end
local key, value = to_key_value(row)
if string.lower(key) == "status" then
luci.http.status(tonumber(value))
elseif string.lower(key) == "content-type" then
content_type = value
else
luci.http.header(key, value)
end
end
local response_body = table.concat(rows, "\r\n", body_start_at_idx + 1)
if content_type == "application/json" and jsonp_callback then
local json = require("luci.json")
luci.http.prepare_content("application/javascript")
luci.http.write(jsonp_callback)
luci.http.write("(")
luci.http.write_json(json.decode(response_body))
luci.http.write(");")
else
luci.http.prepare_content(content_type)
luci.http.write(response_body)
end
end
local method = luci.http.getenv("REQUEST_METHOD")
local jsonp_callback = extract_jsonp_param(luci.http.getenv("QUERY_STRING"))
local parts = parts_after("arduino")
local params = {}
for idx, param in ipairs(parts) do
if not_nil_or_empty(param) then
table.insert(params, param)
end
end
if #params == 0 then
luci.http.status(404)
return
end
params = table.concat(params, "/")
local uci = luci.model.uci.cursor()
uci:load("yunbridge")
local socket_timeout = uci:get_first("yunbridge", "bridge", "socket_timeout", 5)
local sock, code, msg = nixio.connect("127.0.0.1", 5555)
if not sock then
code = code or ""
msg = msg or ""
http_error(500, "Could not connect to YunServer " .. code .. " " .. msg)
return
end
sock:setopt("socket", "sndtimeo", socket_timeout)
sock:setopt("socket", "rcvtimeo", socket_timeout)
sock:setopt("tcp", "nodelay", 1)
sock:write(params)
sock:writeall("\r\n")
local response_text = sock:readall()
sock:close()
send_response(response_text, jsonp_callback)
end
function build_bridge_mailbox_request()
local method = luci.http.getenv("REQUEST_METHOD")
local jsonp_callback = extract_jsonp_param(luci.http.getenv("QUERY_STRING"))
local parts = parts_after("mailbox")
local params = {}
for idx, param in ipairs(parts) do
if not_nil_or_empty(param) then
table.insert(params, param)
end
end
if #params == 0 then
luci.http.status(400)
return
end
local bridge_request = build_bridge_request("raw", params)
if not bridge_request then
luci.http.status(403)
return
end
local uci = luci.model.uci.cursor()
uci:load("yunbridge")
local socket_timeout = uci:get_first("yunbridge", "bridge", "socket_timeout", 5)
local sock, code, msg = nixio.connect("127.0.0.1", 5700)
if not sock then
code = code or ""
msg = msg or ""
http_error(500, "nil socket, " .. code .. " " .. msg)
return
end
sock:setopt("socket", "sndtimeo", socket_timeout)
sock:setopt("socket", "rcvtimeo", socket_timeout)
sock:setopt("tcp", "nodelay", 1)
local json = require("luci.json")
sock:write(json.encode(bridge_request))
sock:writeall("\n")
sock:close()
luci.http.status(200)
end
|
inspect = require("inspect")
log = require("log")
require("component")
require("constants")
require("Print")
Project = require("Project")
log.overridePrint()
local cm = require("ComponentManager")
function _loadComponent(name) cm.loadComponent(name) end
local controller = require("Controller")()
function _getController() return controller end
|
local awful = require("awful")
local M = {}
M.setup = function()
local cmds = {
"setxkbmap -model abnt2 -layout br -option ctrl:swapcaps",
"xset r rate 320 40",
'xinput --set-prop "SIGMACHIP Usb Mouse" "Coordinate Transformation Matrix" 0.5 0 0 0 0.5 0 0 0 1',
"xsetroot -cursor_name left_ptr",
"picom --experimental-backends",
-- "feh --bg-scale ~/Imgs/wall/forest.jpg --no-fehbg",
"xrdb ~/.config/xrdb/Gruvbox",
}
for _, i in pairs(cmds) do
awful.spawn.with_shell(i .. " &")
end
end
return M
|
if (ImGui.TreeNode("Images"))then
ImGuiIO& io = ImGui.GetIO();
ImGui.TextWrapped(
"Below we are displaying the font texture (which is the only texture we have access to in this demo). "
"Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. "
"Hover the texture for a zoomed viewnot ");
-- Below we are displaying the font texture because it is the only texture we have access to inside the demonot
-- Remember that ImTextureID is just storage for whatever you want it to be. It is essentially a value that
-- will be passed to the rendering backend via the ImDrawCmd structure.
-- If you use one of the default imgui_impl_XXXX.cpp rendering backend, they all have comments at the top
-- of their respective source file to specify what they expect to be stored in ImTextureID, for example:
-- - The imgui_impl_dx11.cpp renderer expect a 'ID3D11ShaderResourceView*' pointer
-- - The imgui_impl_opengl3.cpp renderer expect a GLuint OpenGL texture identifier, etc.
-- More:
-- - If you decided that ImTextureID = MyEngineTexture*, then you can pass your MyEngineTexture* pointers
-- to ImGui.Image(), and gather width/height through your own functions, etc.
-- - You can use ShowMetricsWindow() to inspect the draw data that are being passed to your renderer,
-- it will help you debug issues if you are confused about it.
-- - Consider using the lower-level ImDrawList.AddImage() API, via ImGui.GetWindowDrawList()->AddImage().
-- - Read https:--github.com/ocornut/imgui/blob/master/docs/FAQ.md
-- - Read https:--github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples
ImTextureID my_tex_id = io.Fonts->TexID;
float my_tex_w = (float)io.Fonts->TexWidth;
float my_tex_h = (float)io.Fonts->TexHeight;then
ImGui.Text("%.0x%.0", my_tex_w, my_tex_h);
ImVec2 pos = ImGui.GetCursorScreenPos();
ImVec2 uv_min = ImVec2(0.0, 0.0); -- Top-left
ImVec2 uv_max = ImVec2(1.0, 1.0); -- Lower-right
ImVec4 tint_col = ImVec4(1.0, 1.0, 1.0, 1.0); -- No tint
ImVec4 border_col = ImVec4(1.0, 1.0, 1.0, 0.5f); -- 50% opaque white
ImGui.Image(my_tex_id, ImVec2(my_tex_w, my_tex_h), uv_min, uv_max, tint_col, border_col);
if (ImGui.IsItemHovered())then
ImGui.BeginTooltip();
float region_sz = 32.0;
float region_x = io.MousePos.x - pos.x - region_sz * 0.5f;
float region_y = io.MousePos.y - pos.y - region_sz * 0.5f;
float zoom = 4.0;
if (region_x < 0.0) do region_x = 0.0; end
else if (region_x > my_tex_w - region_sz) do region_x = my_tex_w - region_sz; end
if (region_y < 0.0) do region_y = 0.0; end
else if (region_y > my_tex_h - region_sz) do region_y = my_tex_h - region_sz; end
ImGui.Text("Min: (%.2f, %.2f)", region_x, region_y);
ImGui.Text("Max: (%.2f, %.2f)", region_x + region_sz, region_y + region_sz);
ImVec2 uv0 = ImVec2((region_x) / my_tex_w, (region_y) / my_tex_h);
ImVec2 uv1 = ImVec2((region_x + region_sz) / my_tex_w, (region_y + region_sz) / my_tex_h);
ImGui.Image(my_tex_id, ImVec2(region_sz * zoom, region_sz * zoom), uv0, uv1, tint_col, border_col);
ImGui.EndTooltip();
end
end
ImGui.TextWrapped("And now some textured buttons..");
static int pressed_count = 0;
for (int i = 0; i < 8; i++)then
ImGui.PushID(i);
int frame_padding = -1 + i; -- -1 == uses default padding (style.FramePadding)
ImVec2 size = ImVec2(32.0, 32.0); -- Size of the image we want to make visible
ImVec2 uv0 = ImVec2(0.0, 0.0); -- UV coordinates for lower-left
ImVec2 uv1 = ImVec2(32.0 / my_tex_w, 32.0 / my_tex_h);-- UV coordinates for (32,32) in our texture
ImVec4 bg_col = ImVec4(0.0, 0.0, 0.0, 1.0); -- Black background
ImVec4 tint_col = ImVec4(1.0, 1.0, 1.0, 1.0); -- No tint
if (ImGui.ImageButton(my_tex_id, size, uv0, uv1, frame_padding, bg_col, tint_col))
pressed_count += 1;
ImGui.PopID();
ImGui.SameLine();
end
ImGui.NewLine();
ImGui.Text("Pressed %d times.", pressed_count);
ImGui.TreePop();
end
if (ImGui.TreeNode("Combo"))then
-- Expose flags as checkbox for the demo
static ImGuiComboFlags flags = 0;
ImGui.CheckboxFlags("ImGuiComboFlags_PopupAlignLeft", flags, ImGuiComboFlags_PopupAlignLeft);
ImGui.SameLine(); HelpMarker("Only makes a difference if the popup is larger than the combo");
if (ImGui.CheckboxFlags("ImGuiComboFlags_NoArrowButton", flags, ImGuiComboFlags_NoArrowButton))
flags &= ~ImGuiComboFlags_NoPreview; -- Clear the other flag, as we cannot combine both
if (ImGui.CheckboxFlags("ImGuiComboFlags_NoPreview", flags, ImGuiComboFlags_NoPreview))
flags &= ~ImGuiComboFlags_NoArrowButton; -- Clear the other flag, as we cannot combine both
-- Using the generic BeginCombo() API, you have full control over how to display the combo contents.
-- (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively
-- stored in the object itself, etc.)
const char* items[] = do "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" end;
static int item_current_idx = 0; -- Here we store our selection data as an index.
const char* combo_preview_value = items[item_current_idx]; -- Pass in the preview value visible before opening the combo (it could be anything)
if (ImGui.BeginCombo("combo 1", combo_preview_value, flags))then
for (int n = 0; n < IM_ARRAYSIZE(items); n++)then
const bool is_selected = (item_current_idx == n);
if (ImGui.Selectable(items[n], is_selected))
item_current_idx = n;
-- Set the initial focus when opening the combo (scrolling + keyboard navigation focus)
if (is_selected)
ImGui.SetItemDefaultFocus();
end
ImGui.EndCombo();
end
-- Simplified one-liner Combo() API, using values packed in a single constant string
-- This is a convenience for when the selection set is small and known at compile-time.
static int item_current_2 = 0;
ImGui.Combo("combo 2 (one-liner)", item_current_2, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0");
-- Simplified one-liner Combo() using an array of const char*
-- This is not very useful (may obsolete): prefer using BeginCombo()/EndCombo() for full control.
static int item_current_3 = -1; -- If the selection isn't within 0..count, Combo won't display a preview
ImGui.Combo("combo 3 (array)", item_current_3, items, IM_ARRAYSIZE(items));
-- Simplified one-liner Combo() using an accessor function
struct Funcs do local ItemGetter(void* data, int n, const char** out_str) do *out_str = ((const char**)data)[n]; return true; end end;
static int item_current_4 = 0;
ImGui.Combo("combo 4 (function)", item_current_4, Funcs.ItemGetter, items, IM_ARRAYSIZE(items));
ImGui.TreePop();
end
if (ImGui.TreeNode("List boxes"))then
-- Using the generic BeginListBox() API, you have full control over how to display the combo contents.
-- (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively
-- stored in the object itself, etc.)
const char* items[] = do "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" end;
static int item_current_idx = 0; -- Here we store our selection data as an index.
if (ImGui.BeginListBox("listbox 1"))then
for (int n = 0; n < IM_ARRAYSIZE(items); n++)then
const bool is_selected = (item_current_idx == n);
if (ImGui.Selectable(items[n], is_selected))
item_current_idx = n;
-- Set the initial focus when opening the combo (scrolling + keyboard navigation focus)
if (is_selected)
ImGui.SetItemDefaultFocus();
end
ImGui.EndListBox();
end
-- Custom size: use all width, 5 items tall
ImGui.Text("Full-width:");
if (ImGui.BeginListBox("----listbox 2", ImVec2(-FLT_MIN, 5 * ImGui.GetTextLineHeightWithSpacing())))then
for (int n = 0; n < IM_ARRAYSIZE(items); n++)then
const bool is_selected = (item_current_idx == n);
if (ImGui.Selectable(items[n], is_selected))
item_current_idx = n;
-- Set the initial focus when opening the combo (scrolling + keyboard navigation focus)
if (is_selected)
ImGui.SetItemDefaultFocus();
end
ImGui.EndListBox();
end
ImGui.TreePop();
end
if (ImGui.TreeNode("Selectables"))then
-- Selectable() has 2 overloads:
-- - The one taking "bool selected" as a read-only selection information.
-- When Selectable() has been clicked it returns true and you can alter selection state accordingly.
-- - The one taking "bool* p_selected" as a read-write selection information (convenient in some cases)
-- The earlier is more flexible, as in real application your selection may be stored in many different ways
-- and not necessarily inside a bool value (e.g. in flags within objects, as an external list, etc).
if (ImGui.TreeNode("Basic"))then
local selection[5] = do false, true, false, false, false end;
ImGui.Selectable("1. I am selectable", selection[0]);
ImGui.Selectable("2. I am selectable", selection[1]);
ImGui.Text("(I am not selectable)");
ImGui.Selectable("4. I am selectable", selection[3]);
if (ImGui.Selectable("5. I am double clickable", selection[4], ImGuiSelectableFlags_AllowDoubleClick))
if (ImGui.IsMouseDoubleClicked(0))
selection[4] = not selection[4];
ImGui.TreePop();
end
if (ImGui.TreeNode("Selection State: Single Selection"))then
static int selected = -1;
for (int n = 0; n < 5; n++)then
char buf[32];
sprintf(buf, "Object %d", n);
if (ImGui.Selectable(buf, selected == n))
selected = n;
end
ImGui.TreePop();
end
if (ImGui.TreeNode("Selection State: Multiple Selection"))then
HelpMarker("Hold CTRL and click to select multiple items.");
local selection[5] = do false, false, false, false, false end;
for (int n = 0; n < 5; n++)then
char buf[32];
sprintf(buf, "Object %d", n);
if (ImGui.Selectable(buf, selection[n]))then
if (not ImGui.GetIO().KeyCtrl) -- Clear selection when CTRL is not held
memset(selection, 0, sizeof(selection));
selection[n] ^= 1;
end
end
ImGui.TreePop();
end
if (ImGui.TreeNode("Rendering more text into the same line"))then
-- Using the Selectable() override that takes "bool* p_selected" parameter,
-- this function toggle your bool value automatically.
local selected[3] = do false, false, false end;
ImGui.Selectable("main.c", &selected[0]); ImGui.SameLine(300); ImGui.Text(" 2,345 bytes");
ImGui.Selectable("Hello.cpp", selected[1]); ImGui.SameLine(300); ImGui.Text("12,345 bytes");
ImGui.Selectable("Hello.h", &selected[2]); ImGui.SameLine(300); ImGui.Text(" 2,345 bytes");
ImGui.TreePop();
end
if (ImGui.TreeNode("In columns"))then
local selected[10] = do end;
if (ImGui.BeginTable("split1", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_Borders))then
for (int i = 0; i < 10; i++)then
char label[32];
sprintf(label, "Item %d", i);
ImGui.TableNextColumn();
ImGui.Selectable(label, selected[i]); -- FIXME-TABLE: Selection overlap
end
ImGui.EndTable();
end
ImGui.Spacing();
if (ImGui.BeginTable("split2", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_Borders))then
for (int i = 0; i < 10; i++)then
char label[32];
sprintf(label, "Item %d", i);
ImGui.TableNextRow();
ImGui.TableNextColumn();
ImGui.Selectable(label, selected[i], ImGuiSelectableFlags_SpanAllColumns);
ImGui.TableNextColumn();
ImGui.Text("Some other contents");
ImGui.TableNextColumn();
ImGui.Text("123456");
end
ImGui.EndTable();
end
ImGui.TreePop();
end
if (ImGui.TreeNode("Grid"))then
static char selected[4][4] = do do 1, 0, 0, 0 end, do 0, 1, 0, 0 end, do 0, 0, 1, 0 end, do 0, 0, 0, 1 end end;
-- Add in a bit of silly fun...
const float time = (float)ImGui.GetTime();
const bool winning_state = memchr(selected, 0, sizeof(selected)) == NULL; -- If all cells are selected...
if (winning_state)
ImGui.PushStyleVar(ImGuiStyleVar_SelectableTextAlign, ImVec2(0.5f + 0.5f * cosf(time * 2.0), 0.5f + 0.5f * sinf(time * 3.0)));
for (int y = 0; y < 4; y++)
for (int x = 0; x < 4; x++)then
if (x > 0)
ImGui.SameLine();
ImGui.PushID(y * 4 + x);
if (ImGui.Selectable("Sailor", selected[y][x] ~= 0, 0, ImVec2(50, 50)))then
-- Toggle clicked cell + toggle neighbors
selected[y][x] ^= 1;
if (x > 0) do selected[y][x - 1] ^= 1; end
if (x < 3) do selected[y][x + 1] ^= 1; end
if (y > 0) do selected[y - 1][x] ^= 1; end
if (y < 3) do selected[y + 1][x] ^= 1; end
end
ImGui.PopID();
end
if (winning_state)
ImGui.PopStyleVar();
ImGui.TreePop();
end
if (ImGui.TreeNode("Alignment"))then
HelpMarker(
"By default, Selectables uses style.SelectableTextAlign but it can be overridden on a per-item "
"basis using PushStyleVar(). You'll probably want to always keep your default situation to "
"left-align otherwise it becomes difficult to layout multiple items on a same line");
local selected[3 * 3] = do true, false, true, false, true, false, true, false, true end;
for (int y = 0; y < 3; y++)then
for (int x = 0; x < 3; x++)then
ImVec2 alignment = ImVec2((float)x / 2.0, (float)y / 2.0);
char name[32];
sprintf(name, "(%.1f,%.1f)", alignment.x, alignment.y);
if (x > 0) ImGui.SameLine();
ImGui.PushStyleVar(ImGuiStyleVar_SelectableTextAlign, alignment);
ImGui.Selectable(name, selected[3 * y + x], ImGuiSelectableFlags_None, ImVec2(80, 80));
ImGui.PopStyleVar();
end
end
ImGui.TreePop();
end
ImGui.TreePop();
end
-- To wire InputText() with std.string or any other custom string type,
-- see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file.
if (ImGui.TreeNode("Text Input"))then
if (ImGui.TreeNode("Multi-line Text Input"))then
-- Note: we are using a fixed-sized buffer for simplicity here. See ImGuiInputTextFlags_CallbackResize
-- and the code in misc/cpp/imgui_stdlib.h for how to setup InputText() for dynamically resizing strings.
static char text[1024 * 16] =
"--\n"
" The Pentium F00F bug, shorthand for F0 0F C7 C8,\n"
" the hexadecimal encoding of one offending instruction,\n"
" more formally, the invalid operand with locked CMPXCHG8B\n"
" instruction bug, is a design flaw in the majority of\n"
" Intel Pentium, Pentium MMX, and Pentium OverDrive\n"
" processors (all in the P5 microarchitecture).\n"
"--\n\n"
"label:\n"
"\tlock cmpxchg8b eax\n";
static ImGuiInputTextFlags flags = ImGuiInputTextFlags_AllowTabInput;
HelpMarker("You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example. (This is not demonstrated in imgui_demo.cpp because we don't want to include <string> in here)");
ImGui.CheckboxFlags("ImGuiInputTextFlags_ReadOnly", flags, ImGuiInputTextFlags_ReadOnly);
ImGui.CheckboxFlags("ImGuiInputTextFlags_AllowTabInput", flags, ImGuiInputTextFlags_AllowTabInput);
ImGui.CheckboxFlags("ImGuiInputTextFlags_CtrlEnterForNewLine", flags, ImGuiInputTextFlags_CtrlEnterForNewLine);
ImGui.InputTextMultiline("----source", text, IM_ARRAYSIZE(text), ImVec2(-FLT_MIN, ImGui.GetTextLineHeight() * 16), flags);
ImGui.TreePop();
end
if (ImGui.TreeNode("Filtered Text Input"))then
struct TextFiltersthen
-- Return 0 (pass) if the character is 'i' or 'm' or 'g' or 'u' or 'i'
static int FilterImGuiLetters(ImGuiInputTextCallbackData* data)then
if (data->EventChar < 256 and strchr("imgui", (char)data->EventChar))
return 0;
return 1;
end
end;
static char buf1[64] = ""; ImGui.InputText("default", buf1, 64);
static char buf2[64] = ""; ImGui.InputText("decimal", buf2, 64, ImGuiInputTextFlags_CharsDecimal);
static char buf3[64] = ""; ImGui.InputText("hexadecimal", buf3, 64, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase);
static char buf4[64] = ""; ImGui.InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase);
static char buf5[64] = ""; ImGui.InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank);
static char buf6[64] = ""; ImGui.InputText("\"imgui\" letters", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters.FilterImGuiLetters);
ImGui.TreePop();
end
if (ImGui.TreeNode("Password Input"))then
static char password[64] = "password123";
ImGui.InputText("password", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password);
ImGui.SameLine(); HelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n");
ImGui.InputTextWithHint("password (w/ hint)", "<password>", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password);
ImGui.InputText("password (clear)", password, IM_ARRAYSIZE(password));
ImGui.TreePop();
end
if (ImGui.TreeNode("Completion, History, Edit Callbacks"))then
struct Funcsthen
static int MyCallback(ImGuiInputTextCallbackData* data)then
if (data->EventFlag == ImGuiInputTextFlags_CallbackCompletion)then
data->InsertChars(data->CursorPos, "..");
end
else if (data->EventFlag == ImGuiInputTextFlags_CallbackHistory)then
if (data->EventKey == ImGuiKey_UpArrow)then
data->DeleteChars(0, data->BufTextLen);
data->InsertChars(0, "Pressed Upnot ");
data->SelectAll();
end
else if (data->EventKey == ImGuiKey_DownArrow)then
data->DeleteChars(0, data->BufTextLen);
data->InsertChars(0, "Pressed Downnot ");
data->SelectAll();
end
end
else if (data->EventFlag == ImGuiInputTextFlags_CallbackEdit)then
-- Toggle casing of first character
char c = data->Buf[0];
if ((c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z')) data->Buf[0] ^= 32;
data->BufDirty = true;
-- Increment a counter
int* p_int = (int*)data->UserData;
*p_int = *p_int + 1;
end
return 0;
end
end;
static char buf1[64];
ImGui.InputText("Completion", buf1, 64, ImGuiInputTextFlags_CallbackCompletion, Funcs.MyCallback);
ImGui.SameLine(); HelpMarker("Here we append \"..\" each time Tab is pressed. See 'Examples>Console' for a more meaningful demonstration of using this callback.");
static char buf2[64];
ImGui.InputText("History", buf2, 64, ImGuiInputTextFlags_CallbackHistory, Funcs.MyCallback);
ImGui.SameLine(); HelpMarker("Here we replace and select text each time Up/Down are pressed. See 'Examples>Console' for a more meaningful demonstration of using this callback.");
static char buf3[64];
static int edit_count = 0;
ImGui.InputText("Edit", buf3, 64, ImGuiInputTextFlags_CallbackEdit, Funcs.MyCallback, (void*)&edit_count);
ImGui.SameLine(); HelpMarker("Here we toggle the casing of the first character on every edits + count edits.");
ImGui.SameLine(); ImGui.Text("(%d)", edit_count);
ImGui.TreePop();
end
if (ImGui.TreeNode("Resize Callback"))then
-- To wire InputText() with std.string or any other custom string type,
-- you can use the ImGuiInputTextFlags_CallbackResize flag + create a custom ImGui.InputText() wrapper
-- using your preferred type. See misc/cpp/imgui_stdlib.h for an implementation of this using std.string.
HelpMarker(
"Using ImGuiInputTextFlags_CallbackResize to wire your custom string type to InputText().\n\n"
"See misc/cpp/imgui_stdlib.h for an implementation of this for std.string.");
struct Funcsthen
static int MyResizeCallback(ImGuiInputTextCallbackData* data)then
if (data->EventFlag == ImGuiInputTextFlags_CallbackResize)then
ImVector<char>* my_str = (ImVector<char>*)data->UserData;
IM_ASSERT(my_str->begin() == data->Buf);
my_str->resize(data->BufSize); -- NB: On resizing calls, generally data->BufSize == data->BufTextLen + 1
data->Buf = my_str->begin();
end
return 0;
end
-- Note: Because ImGui. is a namespace you would typically add your own function into the namespace.
-- For example, you code may declare a function 'ImGui.InputText(const char* label, MyString* my_str)'
local MyInputTextMultiline(const char* label, ImVector<char>* my_str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0)then
IM_ASSERT((flags & ImGuiInputTextFlags_CallbackResize) == 0);
return ImGui.InputTextMultiline(label, my_str->begin(), (size_t)my_str->size(), size, flags | ImGuiInputTextFlags_CallbackResize, Funcs.MyResizeCallback, (void*)my_str);
end
end;
-- For this demo we are using ImVector as a string container.
-- Note that because we need to store a terminating zero character, our size/capacity are 1 more
-- than usually reported by a typical string class.
static ImVector<char> my_str;
if (my_str.empty())
my_str.push_back(0);
Funcs.MyInputTextMultiline("----MyStr", my_str, ImVec2(-FLT_MIN, ImGui.GetTextLineHeight() * 16));
ImGui.Text("Data: %p\nSize: %d\nCapacity: %d", (void*)my_str.begin(), my_str.size(), my_str.capacity());
ImGui.TreePop();
end
ImGui.TreePop();
end
-- Tabs
if (ImGui.TreeNode("Tabs"))then
if (ImGui.TreeNode("Basic"))then
ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_None;
if (ImGui.BeginTabBar("MyTabBar", tab_bar_flags))then
if (ImGui.BeginTabItem("Avocado"))then
ImGui.Text("This is the Avocado tabnot \nblah blah blah blah blah");
ImGui.EndTabItem();
end
if (ImGui.BeginTabItem("Broccoli"))then
ImGui.Text("This is the Broccoli tabnot \nblah blah blah blah blah");
ImGui.EndTabItem();
end
if (ImGui.BeginTabItem("Cucumber"))then
ImGui.Text("This is the Cucumber tabnot \nblah blah blah blah blah");
ImGui.EndTabItem();
end
ImGui.EndTabBar();
end
ImGui.Separator();
ImGui.TreePop();
end
if (ImGui.TreeNode("Advanced & Close Button"))then
-- Expose a couple of the available flags. In most cases you may just call BeginTabBar() with no flags (0).
static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable;
ImGui.CheckboxFlags("ImGuiTabBarFlags_Reorderable", tab_bar_flags, ImGuiTabBarFlags_Reorderable);
ImGui.CheckboxFlags("ImGuiTabBarFlags_AutoSelectNewTabs", tab_bar_flags, ImGuiTabBarFlags_AutoSelectNewTabs);
ImGui.CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton);
ImGui.CheckboxFlags("ImGuiTabBarFlags_NoCloseWithMiddleMouseButton", tab_bar_flags, ImGuiTabBarFlags_NoCloseWithMiddleMouseButton);
if ((tab_bar_flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0)
tab_bar_flags |= ImGuiTabBarFlags_FittingPolicyDefault_;
if (ImGui.CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown))
tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown);
if (ImGui.CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll))
tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll);
-- Tab Bar
const char* names[4] = do "Artichoke", "Beetroot", "Celery", "Daikon" end;
local opened[4] = do true, true, true, true end; -- Persistent user state
for (int n = 0; n < IM_ARRAYSIZE(opened); n++)then
if (n > 0) do ImGui.SameLine(); end
ImGui.Checkbox(names[n], opened[n]);
end
-- Passing a bool* to BeginTabItem() is similar to passing one to Begin():
-- the underlying bool will be set to false when the tab is closed.
if (ImGui.BeginTabBar("MyTabBar", tab_bar_flags))then
for (int n = 0; n < IM_ARRAYSIZE(opened); n++)
if (opened[n] and ImGui.BeginTabItem(names[n], opened[n], ImGuiTabItemFlags_None))then
ImGui.Text("This is the %s tabnot ", names[n]);
if (n & 1)
ImGui.Text("I am an odd tab.");
ImGui.EndTabItem();
end
ImGui.EndTabBar();
end
ImGui.Separator();
ImGui.TreePop();
end
if (ImGui.TreeNode("TabItemButton & Leading/Trailing flags"))then
static ImVector<int> active_tabs;
static int next_tab_id = 0;
if (next_tab_id == 0) -- Initialize with some default tabs
for (int i = 0; i < 3; i++)
active_tabs.push_back(next_tab_id++);
-- TabItemButton() and Leading/Trailing flags are distinct features which we will demo together.
-- (It is possible to submit regular tabs with Leading/Trailing flags, or TabItemButton tabs without Leading/Trailing flags...
-- but they tend to make more sense together)
local show_leading_button = true;
local show_trailing_button = true;
ImGui.Checkbox("Show Leading TabItemButton()", show_leading_button);
ImGui.Checkbox("Show Trailing TabItemButton()", show_trailing_button);
-- Expose some other flags which are useful to showcase how they interact with Leading/Trailing tabs
static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_AutoSelectNewTabs | ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_FittingPolicyResizeDown;
ImGui.CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton);
if (ImGui.CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown))
tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown);
if (ImGui.CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll))
tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll);
if (ImGui.BeginTabBar("MyTabBar", tab_bar_flags))then
-- Demo a Leading TabItemButton(): click the "?" button to open a menu
if (show_leading_button)
if (ImGui.TabItemButton("?", ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_NoTooltip))
ImGui.OpenPopup("MyHelpMenu");
if (ImGui.BeginPopup("MyHelpMenu"))then
ImGui.Selectable("Hellonot ");
ImGui.EndPopup();
end
-- Demo Trailing Tabs: click the "+" button to add a new tab (in your app you may want to use a font icon instead of the "+")
-- Note that we submit it before the regular tabs, but because of the ImGuiTabItemFlags_Trailing flag it will always appear at the end.
if (show_trailing_button)
if (ImGui.TabItemButton("+", ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_NoTooltip))
active_tabs.push_back(next_tab_id++); -- Add new tab
-- Submit our regular tabs
for (int n = 0; n < active_tabs.Size; )then
bool open = true;
char name[16];
snprintf(name, IM_ARRAYSIZE(name), "%04d", active_tabs[n]);
if (ImGui.BeginTabItem(name, open, ImGuiTabItemFlags_None))then
ImGui.Text("This is the %s tabnot ", name);
ImGui.EndTabItem();
end
if (not open)
active_tabs.erase(active_tabs.Data + n);
else
n++;
end
ImGui.EndTabBar();
end
ImGui.Separator();
ImGui.TreePop();
end
ImGui.TreePop();
end
-- Plot/Graph widgets are not very good.
-- Consider writing your own, or using a third-party one, see:
-- - ImPlot https:--github.com/epezent/implot
-- - others https:--github.com/ocornut/imgui/wiki/Useful-Extensions
if (ImGui.TreeNode("Plots Widgets"))then
local animate = true;
ImGui.Checkbox("Animate", animate);
static float arr[] = do 0.6f, 0.1f, 1.0, 0.5f, 0.92f, 0.1f, 0.2f end;
ImGui.PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr));
-- Fill an array of contiguous float values to plot
-- Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float
-- and the sizeof() of your structure in the "stride" parameter.
static float values[90] = do end;
static int values_offset = 0;
static double refresh_time = 0.0;
if (not animate or refresh_time == 0.0)
refresh_time = ImGui.GetTime();
while (refresh_time < ImGui.GetTime()) -- Create data at fixed 60 Hz rate for the demothen
static float phase = 0.0;
values[values_offset] = cosf(phase);
values_offset = (values_offset + 1) % IM_ARRAYSIZE(values);
phase += 0..0 * values_offset;
refresh_time += 1.0 / 60.0;
end
-- Plots can display overlay texts
-- (in this example, we will display an average value)then
float average = 0.0;
for (int n = 0; n < IM_ARRAYSIZE(values); n++)
average += values[n];
average /= (float)IM_ARRAYSIZE(values);
char overlay[32];
sprintf(overlay, "avg %f", average);
ImGui.PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, overlay, -1.0, 1.0, ImVec2(0, 80.0));
end
ImGui.PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0, 1.0, ImVec2(0, 80.0));
-- Use functions to generate output
-- FIXME: This is rather awkward because current plot API only pass in indices.
-- We probably want an API passing floats and user provide sample rate/count.
struct Funcsthen
static float Sin(void*, int i) do return sinf(i * 0.1f); end
static float Saw(void*, int i) do return (i & 1) ? 1.0 : -1.0; end
end;
static int func_type = 0, display_count = 70;
ImGui.Separator();
ImGui.SetNextItemWidth(ImGui.GetFontSize() * 8);
ImGui.Combo("func", func_type, "Sin\0Saw\0");
ImGui.SameLine();
ImGui.SliderInt("Sample count", display_count, 1, 400);
float (*func)(void*, int) = (func_type == 0) ? Funcs.Sin : Funcs.Saw;
ImGui.PlotLines("Lines", func, NULL, display_count, 0, NULL, -1.0, 1.0, ImVec2(0, 80));
ImGui.PlotHistogram("Histogram", func, NULL, display_count, 0, NULL, -1.0, 1.0, ImVec2(0, 80));
ImGui.Separator();
-- Animate a simple progress bar
static float progress = 0.0, progress_dir = 1.0;
if (animate)then
progress += progress_dir * 0.4f * ImGui.GetIO().DeltaTime;
if (progress >= +1.1f) do progress = +1.1f; progress_dir *= -1.0; end
if (progress <= -0.1f) do progress = -0.1f; progress_dir *= -1.0; end
end
-- Typically we would use ImVec2(-1.0,0.0) or ImVec2(-FLT_MIN,0.0) to use all available width,
-- or ImVec2(width,0.0) for a specified width. ImVec2(0.0,0.0) uses ItemWidth.
ImGui.ProgressBar(progress, ImVec2(0.0, 0.0));
ImGui.SameLine(0.0, ImGui.GetStyle().ItemInnerSpacing.x);
ImGui.Text("Progress Bar");
float progress_saturated = IM_CLAMP(progress, 0.0, 1.0);
char buf[32];
sprintf(buf, "%d/%d", (int)(progress_saturated * 1753), 1753);
ImGui.ProgressBar(progress, ImVec2(0.f, 0.f), buf);
ImGui.TreePop();
end
if (ImGui.TreeNode("Color/Picker Widgets"))then
static ImVec4 color = ImVec4(114.0 / 255.0, 144.0 / 255.0, 154.0 / 255.0, 200.0 / 255.0);
local alpha_preview = true;
local alpha_half_preview = false;
local drag_and_drop = true;
local options_menu = true;
local hdr = false;
ImGui.Checkbox("With Alpha Preview", alpha_preview);
ImGui.Checkbox("With Half Alpha Preview", alpha_half_preview);
ImGui.Checkbox("With Drag and Drop", drag_and_drop);
ImGui.Checkbox("With Options Menu", options_menu); ImGui.SameLine(); HelpMarker("Right-click on the individual color widget to show options.");
ImGui.Checkbox("With HDR", hdr); ImGui.SameLine(); HelpMarker("Currently all this does is to lift the 0..1 limits on dragging widgets.");
ImGuiColorEditFlags misc_flags = (hdr ? ImGuiColorEditFlags_HDR : 0) | (drag_and_drop ? 0 : ImGuiColorEditFlags_NoDragDrop) | (alpha_half_preview ? ImGuiColorEditFlags_AlphaPreviewHalf : (alpha_preview ? ImGuiColorEditFlags_AlphaPreview : 0)) | (options_menu ? 0 : ImGuiColorEditFlags_NoOptions);
ImGui.Text("Color widget:");
ImGui.SameLine(); HelpMarker(
"Click on the color square to open a color picker.\n"
"CTRL+click on individual component to input value.\n");
ImGui.ColorEdit3("MyColor----1", (float*)&color, misc_flags);
ImGui.Text("Color widget HSV with Alpha:");
ImGui.ColorEdit4("MyColor----2", (float*)&color, ImGuiColorEditFlags_DisplayHSV | misc_flags);
ImGui.Text("Color widget with Float Display:");
ImGui.ColorEdit4("MyColor----2f", (float*)&color, ImGuiColorEditFlags_Float | misc_flags);
ImGui.Text("Color button with Picker:");
ImGui.SameLine(); HelpMarker(
"With the ImGuiColorEditFlags_NoInputs flag you can hide all the slider/text inputs.\n"
"With the ImGuiColorEditFlags_NoLabel flag you can pass a non-empty label which will only "
"be used for the tooltip and picker popup.");
ImGui.ColorEdit4("MyColor----3", (float*)&color, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | misc_flags);
ImGui.Text("Color button with Custom Picker Popup:");
-- Generate a default palette. The palette will persist and can be edited.
local saved_palette_init = true;
static ImVec4 saved_palette[32] = do end;
if (saved_palette_init)then
for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++)then
ImGui.ColorConvertHSVtoRGB(n / 31.0, 0.8f, 0.8f,
saved_palette[n].x, saved_palette[n].y, saved_palette[n].z);
saved_palette[n].w = 1.0; -- Alpha
end
saved_palette_init = false;
end
static ImVec4 backup_color;
bool open_popup = ImGui.ColorButton("MyColor----3b", color, misc_flags);
ImGui.SameLine(0, ImGui.GetStyle().ItemInnerSpacing.x);
open_popup |= ImGui.Button("Palette");
if (open_popup)then
ImGui.OpenPopup("mypicker");
backup_color = color;
end
if (ImGui.BeginPopup("mypicker"))then
ImGui.Text("MY CUSTOM COLOR PICKER WITH AN AMAZING PALETTEnot ");
ImGui.Separator();
ImGui.ColorPicker4("----picker", (float*)&color, misc_flags | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoSmallPreview);
ImGui.SameLine();
ImGui.BeginGroup(); -- Lock X position
ImGui.Text("Current");
ImGui.ColorButton("----current", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40));
ImGui.Text("Previous");
if (ImGui.ColorButton("----previous", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40)))
color = backup_color;
ImGui.Separator();
ImGui.Text("Palette");
for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++)then
ImGui.PushID(n);
if ((n % 8) ~= 0)
ImGui.SameLine(0.0, ImGui.GetStyle().ItemSpacing.y);
ImGuiColorEditFlags palette_button_flags = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip;
if (ImGui.ColorButton("----palette", saved_palette[n], palette_button_flags, ImVec2(20, 20)))
color = ImVec4(saved_palette[n].x, saved_palette[n].y, saved_palette[n].z, color.w); -- Preserve alphanot
-- Allow user to drop colors into each palette entry. Note that ColorButton() is already a
-- drag source by default, unless specifying the ImGuiColorEditFlags_NoDragDrop flag.
if (ImGui.BeginDragDropTarget())then
if (const ImGuiPayload* payload = ImGui.AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))
memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 3);
if (const ImGuiPayload* payload = ImGui.AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F))
memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 4);
ImGui.EndDragDropTarget();
end
ImGui.PopID();
end
ImGui.EndGroup();
ImGui.EndPopup();
end
ImGui.Text("Color button only:");
local no_border = false;
ImGui.Checkbox("ImGuiColorEditFlags_NoBorder", no_border);
ImGui.ColorButton("MyColor----3c", *(ImVec4*)&color, misc_flags | (no_border ? ImGuiColorEditFlags_NoBorder : 0), ImVec2(80, 80));
ImGui.Text("Color picker:");
local alpha = true;
local alpha_bar = true;
local side_preview = true;
local ref_color = false;
static ImVec4 ref_color_v(1.0, 0.0, 1.0, 0.5f);
static int display_mode = 0;
static int picker_mode = 0;
ImGui.Checkbox("With Alpha", alpha);
ImGui.Checkbox("With Alpha Bar", alpha_bar);
ImGui.Checkbox("With Side Preview", side_preview);
if (side_preview)then
ImGui.SameLine();
ImGui.Checkbox("With Ref Color", ref_color);
if (ref_color)then
ImGui.SameLine();
ImGui.ColorEdit4("----RefColor", ref_color_v.x, ImGuiColorEditFlags_NoInputs | misc_flags);
end
end
ImGui.Combo("Display Mode", display_mode, "Auto/Current\0None\0RGB Only\0HSV Only\0Hex Only\0");
ImGui.SameLine(); HelpMarker(
"ColorEdit defaults to displaying RGB inputs if you don't specify a display mode, "
"but the user can change it with a right-click.\n\nColorPicker defaults to displaying RGB+HSV+Hex "
"if you don't specify a display mode.\n\nYou can change the defaults using SetColorEditOptions().");
ImGui.Combo("Picker Mode", picker_mode, "Auto/Current\0Hue bar + SV rect\0Hue wheel + SV triangle\0");
ImGui.SameLine(); HelpMarker("User can right-click the picker to change mode.");
ImGuiColorEditFlags flags = misc_flags;
if (not alpha) flags |= ImGuiColorEditFlags_NoAlpha; -- This is by default if you call ColorPicker3() instead of ColorPicker4()
if (alpha_bar) flags |= ImGuiColorEditFlags_AlphaBar;
if (not side_preview) flags |= ImGuiColorEditFlags_NoSidePreview;
if (picker_mode == 1) flags |= ImGuiColorEditFlags_PickerHueBar;
if (picker_mode == 2) flags |= ImGuiColorEditFlags_PickerHueWheel;
if (display_mode == 1) flags |= ImGuiColorEditFlags_NoInputs; -- Disable all RGB/HSV/Hex displays
if (display_mode == 2) flags |= ImGuiColorEditFlags_DisplayRGB; -- Override display mode
if (display_mode == 3) flags |= ImGuiColorEditFlags_DisplayHSV;
if (display_mode == 4) flags |= ImGuiColorEditFlags_DisplayHex;
ImGui.ColorPicker4("MyColor----4", (float*)&color, flags, ref_color ? &ref_color_v.x : NULL);
ImGui.Text("Set defaults in code:");
ImGui.SameLine(); HelpMarker(
"SetColorEditOptions() is designed to allow you to set boot-time default.\n"
"We don't have Push/Pop functions because you can force options on a per-widget basis if needed,"
"and the user can change non-forced ones with the options menu.\nWe don't have a getter to avoid"
"encouraging you to persistently save values that aren't forward-compatible.");
if (ImGui.Button("Default: Uint8 + HSV + Hue Bar"))
ImGui.SetColorEditOptions(ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_PickerHueBar);
if (ImGui.Button("Default: Float + HDR + Hue Wheel"))
ImGui.SetColorEditOptions(ImGuiColorEditFlags_Float | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_PickerHueWheel);
-- HSV encoded support (to avoid RGB<>HSV round trips and singularities when S==0 or V==0)
static ImVec4 color_hsv(0.23f, 1.0, 1.0, 1.0); -- Stored as HSVnot
ImGui.Spacing();
ImGui.Text("HSV encoded colors");
ImGui.SameLine(); HelpMarker(
"By default, colors are given to ColorEdit and ColorPicker in RGB, but ImGuiColorEditFlags_InputHSV"
"allows you to store colors as HSV and pass them to ColorEdit and ColorPicker as HSV. This comes with the"
"added benefit that you can manipulate hue values with the picker even when saturation or value are zero.");
ImGui.Text("Color widget with InputHSV:");
ImGui.ColorEdit4("HSV shown as RGB----1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float);
ImGui.ColorEdit4("HSV shown as HSV----1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float);
ImGui.DragFloat4("Raw HSV values", (float*)&color_hsv, 0.01f, 0.0, 1.0);
ImGui.TreePop();
end
if (ImGui.TreeNode("Drag/Slider Flags"))then
-- Demonstrate using advanced flags for DragXXX and SliderXXX functions. Note that the flags are the samenot
static ImGuiSliderFlags flags = ImGuiSliderFlags_None;
ImGui.CheckboxFlags("ImGuiSliderFlags_AlwaysClamp", flags, ImGuiSliderFlags_AlwaysClamp);
ImGui.SameLine(); HelpMarker("Always clamp value to min/max bounds (if any) when input manually with CTRL+Click.");
ImGui.CheckboxFlags("ImGuiSliderFlags_Logarithmic", flags, ImGuiSliderFlags_Logarithmic);
ImGui.SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values).");
ImGui.CheckboxFlags("ImGuiSliderFlags_NoRoundToFormat", flags, ImGuiSliderFlags_NoRoundToFormat);
ImGui.SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits).");
ImGui.CheckboxFlags("ImGuiSliderFlags_NoInput", flags, ImGuiSliderFlags_NoInput);
ImGui.SameLine(); HelpMarker("Disable CTRL+Click or Enter key allowing to input text directly into the widget.");
-- Drags
static float drag_f = 0.5f;
static int drag_i = 50;
ImGui.Text("Underlying float value: %f", drag_f);
ImGui.DragFloat("DragFloat (0 -> 1)", drag_f, 0.005f, 0.0, 1.0, "%.3f", flags);
ImGui.DragFloat("DragFloat (0 -> +inf)", drag_f, 0.005f, 0.0, FLT_MAX, "%.3f", flags);
ImGui.DragFloat("DragFloat (-inf -> 1)", drag_f, 0.005f, -FLT_MAX, 1.0, "%.3f", flags);
ImGui.DragFloat("DragFloat (-inf -> +inf)", drag_f, 0.005f, -FLT_MAX, +FLT_MAX, "%.3f", flags);
ImGui.DragInt("DragInt (0 -> 100)", drag_i, 0.5f, 0, 100, "%d", flags);
-- Sliders
static float slider_f = 0.5f;
static int slider_i = 50;
ImGui.Text("Underlying float value: %f", slider_f);
ImGui.SliderFloat("SliderFloat (0 -> 1)", slider_f, 0.0, 1.0, "%.3f", flags);
ImGui.SliderInt("SliderInt (0 -> 100)", slider_i, 0, 100, "%d", flags);
ImGui.TreePop();
end
if (ImGui.TreeNode("Range Widgets"))then
static float begin = 10, end = 90;
static int begin_i = 100, end_i = 1000;
ImGui.DragFloatRange2("range float", begin, end, 0.25f, 0.0, 100.0, "Min: %.1f %%", "Max: %.1f %%", ImGuiSliderFlags_AlwaysClamp);
ImGui.DragIntRange2("range int", begin_i, end_i, 5, 0, 1000, "Min: %d units", "Max: %d units");
ImGui.DragIntRange2("range int (no bounds)", begin_i, end_i, 5, 0, 0, "Min: %d units", "Max: %d units");
ImGui.TreePop();
end
if (ImGui.TreeNode("Data Types"))then
-- DragScalar/InputScalar/SliderScalar functions allow various data types
-- - signed/unsigned
-- - 8/16/32/64-bits
-- - integer/float/double
-- To avoid polluting the public API with all possible combinations, we use the ImGuiDataType enum
-- to pass the type, and passing all arguments by pointer.
-- This is the reason the test code below creates local variables to hold "zero" "one" etc. for each types.
-- In practice, if you frequently use a given type that is not covered by the normal API entry points,
-- you can wrap it yourself inside a 1 line function which can take typed argument as value instead of void*,
-- and then pass their address to the generic function. For example:
-- bool MySliderU64(const char *label, u64* value, u64 min = 0, u64 max = 0, const char* format = "%lld")
-- do
-- return SliderScalar(label, ImGuiDataType_U64, value, min, max, format);
-- end
-- Setup limits (as helper variables so we can take their address, as explained above)
-- Note: SliderScalar() functions have a maximum usable range of half the natural type maximum, hence the /2.
--ifndef LLONG_MIN
ImS64 LLONG_MIN = -9223372036854775807LL - 1;
ImS64 LLONG_MAX = 9223372036854775807LL;
ImU64 ULLONG_MAX = (2ULL * 9223372036854775807LL + 1);
--endif
const char s8_zero = 0, s8_one = 1, s8_fifty = 50, s8_min = -128, s8_max = 127;
const ImU8 u8_zero = 0, u8_one = 1, u8_fifty = 50, u8_min = 0, u8_max = 255;
const short s16_zero = 0, s16_one = 1, s16_fifty = 50, s16_min = -32768, s16_max = 32767;
const ImU16 u16_zero = 0, u16_one = 1, u16_fifty = 50, u16_min = 0, u16_max = 65535;
const ImS32 s32_zero = 0, s32_one = 1, s32_fifty = 50, s32_min = INT_MIN/2, s32_max = INT_MAX/2, s32_hi_a = INT_MAX/2 - 100, s32_hi_b = INT_MAX/2;
const ImU32 u32_zero = 0, u32_one = 1, u32_fifty = 50, u32_min = 0, u32_max = UINT_MAX/2, u32_hi_a = UINT_MAX/2 - 100, u32_hi_b = UINT_MAX/2;
const ImS64 s64_zero = 0, s64_one = 1, s64_fifty = 50, s64_min = LLONG_MIN/2, s64_max = LLONG_MAX/2, s64_hi_a = LLONG_MAX/2 - 100, s64_hi_b = LLONG_MAX/2;
const ImU64 u64_zero = 0, u64_one = 1, u64_fifty = 50, u64_min = 0, u64_max = ULLONG_MAX/2, u64_hi_a = ULLONG_MAX/2 - 100, u64_hi_b = ULLONG_MAX/2;
const float f32_zero = 0.f, f32_one = 1.f, f32_lo_a = -10000000000.0, f32_hi_a = +10000000000.0;
const double f64_zero = 0., f64_one = 1., f64_lo_a = -1000000000000000.0, f64_hi_a = +1000000000000000.0;
-- State
static char s8_v = 127;
static ImU8 u8_v = 255;
static short s16_v = 32767;
static ImU16 u16_v = 65535;
static ImS32 s32_v = -1;
static ImU32 u32_v = (ImU32)-1;
static ImS64 s64_v = -1;
static ImU64 u64_v = (ImU64)-1;
static float f32_v = 0.123f;
static double f64_v = 90000.01234567890123456789;
const float drag_speed = 0.2f;
local drag_clamp = false;
ImGui.Text("Drags:");
ImGui.Checkbox("Clamp integers to 0..50", drag_clamp);
ImGui.SameLine(); HelpMarker(
"As with every widgets in dear imgui, we never modify values unless there is a user interaction.\n"
"You can override the clamping limits by using CTRL+Click to input a value.");
ImGui.DragScalar("drag s8", ImGuiDataType_S8, &s8_v, drag_speed, drag_clamp ? &s8_zero : NULL, drag_clamp ? &s8_fifty : NULL);
ImGui.DragScalar("drag u8", ImGuiDataType_U8, &u8_v, drag_speed, drag_clamp ? &u8_zero : NULL, drag_clamp ? &u8_fifty : NULL, "%u ms");
ImGui.DragScalar("drag s16", ImGuiDataType_S16, &s16_v, drag_speed, drag_clamp ? &s16_zero : NULL, drag_clamp ? &s16_fifty : NULL);
ImGui.DragScalar("drag u16", ImGuiDataType_U16, &u16_v, drag_speed, drag_clamp ? &u16_zero : NULL, drag_clamp ? &u16_fifty : NULL, "%u ms");
ImGui.DragScalar("drag s32", ImGuiDataType_S32, &s32_v, drag_speed, drag_clamp ? &s32_zero : NULL, drag_clamp ? &s32_fifty : NULL);
ImGui.DragScalar("drag u32", ImGuiDataType_U32, &u32_v, drag_speed, drag_clamp ? &u32_zero : NULL, drag_clamp ? &u32_fifty : NULL, "%u ms");
ImGui.DragScalar("drag s64", ImGuiDataType_S64, &s64_v, drag_speed, drag_clamp ? &s64_zero : NULL, drag_clamp ? &s64_fifty : NULL);
ImGui.DragScalar("drag u64", ImGuiDataType_U64, &u64_v, drag_speed, drag_clamp ? &u64_zero : NULL, drag_clamp ? &u64_fifty : NULL);
ImGui.DragScalar("drag float", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, f32_one, "%f");
ImGui.DragScalar("drag float log", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, f32_one, "%f", ImGuiSliderFlags_Logarithmic);
ImGui.DragScalar("drag double", ImGuiDataType_Double, f64_v, 0.0005f, f64_zero, NULL, "%..0 grams");
ImGui.DragScalar("drag double log",ImGuiDataType_Double, f64_v, 0.0005f, f64_zero, f64_one, "0 < %..0 < 1", ImGuiSliderFlags_Logarithmic);
ImGui.Text("Sliders");
ImGui.SliderScalar("slider s8 full", ImGuiDataType_S8, &s8_v, &s8_min, &s8_max, "%d");
ImGui.SliderScalar("slider u8 full", ImGuiDataType_U8, &u8_v, &u8_min, &u8_max, "%u");
ImGui.SliderScalar("slider s16 full", ImGuiDataType_S16, &s16_v, s16_min, &s16_max, "%d");
ImGui.SliderScalar("slider u16 full", ImGuiDataType_U16, &u16_v, u16_min, &u16_max, "%u");
ImGui.SliderScalar("slider s32 low", ImGuiDataType_S32, &s32_v, s32_zero, s32_fifty,"%d");
ImGui.SliderScalar("slider s32 high", ImGuiDataType_S32, &s32_v, s32_hi_a, s32_hi_b, "%d");
ImGui.SliderScalar("slider s32 full", ImGuiDataType_S32, &s32_v, s32_min, &s32_max, "%d");
ImGui.SliderScalar("slider u32 low", ImGuiDataType_U32, &u32_v, u32_zero, u32_fifty,"%u");
ImGui.SliderScalar("slider u32 high", ImGuiDataType_U32, &u32_v, u32_hi_a, u32_hi_b, "%u");
ImGui.SliderScalar("slider u32 full", ImGuiDataType_U32, &u32_v, u32_min, &u32_max, "%u");
ImGui.SliderScalar("slider s64 low", ImGuiDataType_S64, &s64_v, s64_zero, s64_fifty,"%" IM_PRId64);
ImGui.SliderScalar("slider s64 high", ImGuiDataType_S64, &s64_v, s64_hi_a, s64_hi_b, "%" IM_PRId64);
ImGui.SliderScalar("slider s64 full", ImGuiDataType_S64, &s64_v, s64_min, &s64_max, "%" IM_PRId64);
ImGui.SliderScalar("slider u64 low", ImGuiDataType_U64, &u64_v, u64_zero, u64_fifty,"%" IM_PRIu64 " ms");
ImGui.SliderScalar("slider u64 high", ImGuiDataType_U64, &u64_v, u64_hi_a, u64_hi_b, "%" IM_PRIu64 " ms");
ImGui.SliderScalar("slider u64 full", ImGuiDataType_U64, &u64_v, u64_min, &u64_max, "%" IM_PRIu64 " ms");
ImGui.SliderScalar("slider float low", ImGuiDataType_Float, &f32_v, f32_zero, f32_one);
ImGui.SliderScalar("slider float low log", ImGuiDataType_Float, &f32_v, f32_zero, f32_one, "%..0", ImGuiSliderFlags_Logarithmic);
ImGui.SliderScalar("slider float high", ImGuiDataType_Float, &f32_v, f32_lo_a, f32_hi_a, "%e");
ImGui.SliderScalar("slider double low", ImGuiDataType_Double, f64_v, f64_zero, f64_one, "%..0 grams");
ImGui.SliderScalar("slider double low log",ImGuiDataType_Double, f64_v, f64_zero, f64_one, "%..0", ImGuiSliderFlags_Logarithmic);
ImGui.SliderScalar("slider double high", ImGuiDataType_Double, f64_v, f64_lo_a, f64_hi_a, "%e grams");
ImGui.Text("Sliders (reverse)");
ImGui.SliderScalar("slider s8 reverse", ImGuiDataType_S8, &s8_v, &s8_max, &s8_min, "%d");
ImGui.SliderScalar("slider u8 reverse", ImGuiDataType_U8, &u8_v, &u8_max, &u8_min, "%u");
ImGui.SliderScalar("slider s32 reverse", ImGuiDataType_S32, &s32_v, s32_fifty, s32_zero, "%d");
ImGui.SliderScalar("slider u32 reverse", ImGuiDataType_U32, &u32_v, u32_fifty, u32_zero, "%u");
ImGui.SliderScalar("slider s64 reverse", ImGuiDataType_S64, &s64_v, s64_fifty, s64_zero, "%" IM_PRId64);
ImGui.SliderScalar("slider u64 reverse", ImGuiDataType_U64, &u64_v, u64_fifty, u64_zero, "%" IM_PRIu64 " ms");
local inputs_step = true;
ImGui.Text("Inputs");
ImGui.Checkbox("Show step buttons", inputs_step);
ImGui.InputScalar("input s8", ImGuiDataType_S8, &s8_v, inputs_step ? &s8_one : NULL, NULL, "%d");
ImGui.InputScalar("input u8", ImGuiDataType_U8, &u8_v, inputs_step ? &u8_one : NULL, NULL, "%u");
ImGui.InputScalar("input s16", ImGuiDataType_S16, &s16_v, inputs_step ? &s16_one : NULL, NULL, "%d");
ImGui.InputScalar("input u16", ImGuiDataType_U16, &u16_v, inputs_step ? &u16_one : NULL, NULL, "%u");
ImGui.InputScalar("input s32", ImGuiDataType_S32, &s32_v, inputs_step ? &s32_one : NULL, NULL, "%d");
ImGui.InputScalar("input s32 hex", ImGuiDataType_S32, &s32_v, inputs_step ? &s32_one : NULL, NULL, "%08X", ImGuiInputTextFlags_CharsHexadecimal);
ImGui.InputScalar("input u32", ImGuiDataType_U32, &u32_v, inputs_step ? &u32_one : NULL, NULL, "%u");
ImGui.InputScalar("input u32 hex", ImGuiDataType_U32, &u32_v, inputs_step ? &u32_one : NULL, NULL, "%08X", ImGuiInputTextFlags_CharsHexadecimal);
ImGui.InputScalar("input s64", ImGuiDataType_S64, &s64_v, inputs_step ? &s64_one : NULL);
ImGui.InputScalar("input u64", ImGuiDataType_U64, &u64_v, inputs_step ? &u64_one : NULL);
ImGui.InputScalar("input float", ImGuiDataType_Float, &f32_v, inputs_step ? &f32_one : NULL);
ImGui.InputScalar("input double", ImGuiDataType_Double, f64_v, inputs_step ? &f64_one : NULL);
ImGui.TreePop();
end
if (ImGui.TreeNode("Multi-component Widgets"))then
static float vec4f[4] = do 0..0, 0..0, 0..0, 0.44f end;
static int vec4i[4] = do 1, 5, 100, 255 end;
ImGui.InputFloat2("input float2", vec4f);
ImGui.DragFloat2("drag float2", vec4f, 0.01f, 0.0, 1.0);
ImGui.SliderFloat2("slider float2", vec4f, 0.0, 1.0);
ImGui.InputInt2("input int2", vec4i);
ImGui.DragInt2("drag int2", vec4i, 1, 0, 255);
ImGui.SliderInt2("slider int2", vec4i, 0, 255);
ImGui.Spacing();
ImGui.InputFloat3("input float3", vec4f);
ImGui.DragFloat3("drag float3", vec4f, 0.01f, 0.0, 1.0);
ImGui.SliderFloat3("slider float3", vec4f, 0.0, 1.0);
ImGui.InputInt3("input int3", vec4i);
ImGui.DragInt3("drag int3", vec4i, 1, 0, 255);
ImGui.SliderInt3("slider int3", vec4i, 0, 255);
ImGui.Spacing();
ImGui.InputFloat4("input float4", vec4f);
ImGui.DragFloat4("drag float4", vec4f, 0.01f, 0.0, 1.0);
ImGui.SliderFloat4("slider float4", vec4f, 0.0, 1.0);
ImGui.InputInt4("input int4", vec4i);
ImGui.DragInt4("drag int4", vec4i, 1, 0, 255);
ImGui.SliderInt4("slider int4", vec4i, 0, 255);
ImGui.TreePop();
end
if (ImGui.TreeNode("Vertical Sliders"))then
const float spacing = 4;
ImGui.PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing));
static int int_value = 0;
ImGui.VSliderInt("----int", ImVec2(18, 160), int_value, 0, 5);
ImGui.SameLine();
static float values[7] = do 0.0, 0..0, 0.35f, 0.9f, 0..0, 0..0, 0.0 end;
ImGui.PushID("set1");
for (int i = 0; i < 7; i++)then
if (i > 0) ImGui.SameLine();
ImGui.PushID(i);
ImGui.PushStyleColor(ImGuiCol_FrameBg, (ImVec4)ImColor.HSV(i / 7.0, 0.5f, 0.5f));
ImGui.PushStyleColor(ImGuiCol_FrameBgHovered, (ImVec4)ImColor.HSV(i / 7.0, 0.6f, 0.5f));
ImGui.PushStyleColor(ImGuiCol_FrameBgActive, (ImVec4)ImColor.HSV(i / 7.0, 0.7f, 0.5f));
ImGui.PushStyleColor(ImGuiCol_SliderGrab, (ImVec4)ImColor.HSV(i / 7.0, 0.9f, 0.9f));
ImGui.VSliderFloat("----v", ImVec2(18, 160), values[i], 0.0, 1.0, "");
if (ImGui.IsItemActive() or ImGui.IsItemHovered())
ImGui.SetTooltip("%.3f", values[i]);
ImGui.PopStyleColor(4);
ImGui.PopID();
end
ImGui.PopID();
ImGui.SameLine();
ImGui.PushID("set2");
static float values2[4] = do 0..0, 0..0, 0..0, 0.25f end;
const int rows = 3;
const ImVec2 small_slider_size(18, (float)(int)((160.0 - (rows - 1) * spacing) / rows));
for (int nx = 0; nx < 4; nx++)then
if (nx > 0) ImGui.SameLine();
ImGui.BeginGroup();
for (int ny = 0; ny < rows; ny++)then
ImGui.PushID(nx * rows + ny);
ImGui.VSliderFloat("----v", small_slider_size, values2[nx], 0.0, 1.0, "");
if (ImGui.IsItemActive() or ImGui.IsItemHovered())
ImGui.SetTooltip("%.3f", values2[nx]);
ImGui.PopID();
end
ImGui.EndGroup();
end
ImGui.PopID();
ImGui.SameLine();
ImGui.PushID("set3");
for (int i = 0; i < 4; i++)then
if (i > 0) ImGui.SameLine();
ImGui.PushID(i);
ImGui.PushStyleVar(ImGuiStyleVar_GrabMinSize, 40);
ImGui.VSliderFloat("----v", ImVec2(40, 160), values[i], 0.0, 1.0, "%.2f\nsec");
ImGui.PopStyleVar();
ImGui.PopID();
end
ImGui.PopID();
ImGui.PopStyleVar();
ImGui.TreePop();
end
if (ImGui.TreeNode("Drag and Drop"))then
if (ImGui.TreeNode("Drag and drop in standard widgets"))then
-- ColorEdit widgets automatically act as drag source and drag target.
-- They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F
-- to allow your own widgets to use colors in their drag and drop interaction.
-- Also see 'Demo->Widgets->Color/Picker Widgets->Palette' demo.
HelpMarker("You can drag from the color squares.");
static float col1[3] = do 1.0, 0.0, 0.2f end;
static float col2[4] = do 0.4f, 0.7f, 0.0, 0.5f end;
ImGui.ColorEdit3("color 1", col1);
ImGui.ColorEdit4("color 2", col2);
ImGui.TreePop();
end
if (ImGui.TreeNode("Drag and drop to copy/swap items"))then
enum Modethen
Mode_Copy,
Mode_Move,
Mode_Swap
end;
static int mode = 0;
if (ImGui.RadioButton("Copy", mode == Mode_Copy)) do mode = Mode_Copy; end ImGui.SameLine();
if (ImGui.RadioButton("Move", mode == Mode_Move)) do mode = Mode_Move; end ImGui.SameLine();
if (ImGui.RadioButton("Swap", mode == Mode_Swap)) do mode = Mode_Swap; end
static const char* names[9] =then
"Bobby", "Beatrice", "Betty",
"Brianna", "Barry", "Bernard",
"Bibi", "Blaine", "Bryn"
end;
for (int n = 0; n < IM_ARRAYSIZE(names); n++)then
ImGui.PushID(n);
if ((n % 3) ~= 0)
ImGui.SameLine();
ImGui.Button(names[n], ImVec2(60, 60));
-- Our buttons are both drag sources and drag targets herenot
if (ImGui.BeginDragDropSource(ImGuiDragDropFlags_None))then
-- Set payload to carry the index of our item (could be anything)
ImGui.SetDragDropPayload("DND_DEMO_CELL", n, sizeof(int));
-- Display preview (could be anything, e.g. when dragging an image we could decide to display
-- the filename and a small preview of the image, etc.)
if (mode == Mode_Copy) do ImGui.Text("Copy %s", names[n]); end
if (mode == Mode_Move) do ImGui.Text("Move %s", names[n]); end
if (mode == Mode_Swap) do ImGui.Text("Swap %s", names[n]); end
ImGui.EndDragDropSource();
end
if (ImGui.BeginDragDropTarget())then
if (const ImGuiPayload* payload = ImGui.AcceptDragDropPayload("DND_DEMO_CELL"))then
IM_ASSERT(payload->DataSize == sizeof(int));
int payload_n = *(const int*)payload->Data;
if (mode == Mode_Copy)then
names[n] = names[payload_n];
end
if (mode == Mode_Move)then
names[n] = names[payload_n];
names[payload_n] = "";
end
if (mode == Mode_Swap)then
const char* tmp = names[n];
names[n] = names[payload_n];
names[payload_n] = tmp;
end
end
ImGui.EndDragDropTarget();
end
ImGui.PopID();
end
ImGui.TreePop();
end
if (ImGui.TreeNode("Drag to reorder items (simple)"))then
-- Simple reordering
HelpMarker(
"We don't use the drag and drop api at all herenot "
"Instead we query when the item is held but not hovered, and order items accordingly.");
static const char* item_names[] = do "Item One", "Item Two", "Item Three", "Item Four", "Item Five" end;
for (int n = 0; n < IM_ARRAYSIZE(item_names); n++)then
const char* item = item_names[n];
ImGui.Selectable(item);
if (ImGui.IsItemActive() and not ImGui.IsItemHovered())then
int n_next = n + (ImGui.GetMouseDragDelta(0).y < 0.f ? -1 : 1);
if (n_next >= 0 and n_next < IM_ARRAYSIZE(item_names))then
item_names[n] = item_names[n_next];
item_names[n_next] = item;
ImGui.ResetMouseDragDelta();
end
end
end
ImGui.TreePop();
end
ImGui.TreePop();
end
if (ImGui.TreeNode("Querying Status (Edited/Active/Hovered etc.)"))then
-- Select an item type
const char* item_names[] =then
"Text", "Button", "Button (w/ repeat)", "Checkbox", "SliderFloat", "InputText", "InputFloat",
"InputFloat3", "ColorEdit4", "Selectable", "MenuItem", "TreeNode", "TreeNode (w/ double-click)", "Combo", "ListBox"
end;
static int item_type = 4;
local item_disabled = false;
ImGui.Combo("Item Type", item_type, item_names, IM_ARRAYSIZE(item_names), IM_ARRAYSIZE(item_names));
ImGui.SameLine();
HelpMarker("Testing how various types of items are interacting with the IsItemXXX functions. Note that the bool return value of most ImGui function is generally equivalent to calling ImGui.IsItemHovered().");
ImGui.Checkbox("Item Disabled", &item_disabled);
-- Submit selected item item so we can query their status in the code following it.
bool ret = false;
local b = false;
static float col4f[4] = do 1.0, 0.5, 0.0, 1.0 end;
static char str[16] = do end;
if (item_disabled)
ImGui.BeginDisabled(true);
if (item_type == 0) do ImGui.Text("ITEM: Text"); end -- Testing text items with no identifier/interaction
if (item_type == 1) do ret = ImGui.Button("ITEM: Button"); end -- Testing button
if (item_type == 2) do ImGui.PushButtonRepeat(true); ret = ImGui.Button("ITEM: Button"); ImGui.PopButtonRepeat(); end -- Testing button (with repeater)
if (item_type == 3) do ret = ImGui.Checkbox("ITEM: Checkbox", b); end -- Testing checkbox
if (item_type == 4) do ret = ImGui.SliderFloat("ITEM: SliderFloat", col4f[0], 0.0, 1.0); end -- Testing basic item
if (item_type == 5) do ret = ImGui.InputText("ITEM: InputText", str[0], IM_ARRAYSIZE(str)); end -- Testing input text (which handles tabbing)
if (item_type == 6) do ret = ImGui.InputFloat("ITEM: InputFloat", col4f, 1.0); end -- Testing +/- buttons on scalar input
if (item_type == 7) do ret = ImGui.InputFloat3("ITEM: InputFloat3", col4f); end -- Testing multi-component items (IsItemXXX flags are reported merged)
if (item_type == 8) do ret = ImGui.ColorEdit4("ITEM: ColorEdit4", col4f); end -- Testing multi-component items (IsItemXXX flags are reported merged)
if (item_type == 9) do ret = ImGui.Selectable("ITEM: Selectable"); end -- Testing selectable item
if (item_type == 10)do ret = ImGui.MenuItem("ITEM: MenuItem"); end -- Testing menu item (they use ImGuiButtonFlags_PressedOnRelease button policy)
if (item_type == 11)do ret = ImGui.TreeNode("ITEM: TreeNode"); if (ret) ImGui.TreePop(); end -- Testing tree node
if (item_type == 12)do ret = ImGui.TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_NoTreePushOnOpen); end -- Testing tree node with ImGuiButtonFlags_PressedOnDoubleClick button policy.
if (item_type == 13)do const char* items[] = do "Apple", "Banana", "Cherry", "Kiwi" end; static int current = 1; ret = ImGui.Combo("ITEM: Combo", current, items, IM_ARRAYSIZE(items)); end
if (item_type == 14)do const char* items[] = do "Apple", "Banana", "Cherry", "Kiwi" end; static int current = 1; ret = ImGui.ListBox("ITEM: ListBox", current, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); end
-- Display the values of IsItemHovered() and other common item state functions.
-- Note that the ImGuiHoveredFlags_XXX flags can be combined.
-- Because BulletText is an item itself and that would affect the output of IsItemXXX functions,
-- we query every state in a single call to avoid storing them and to simplify the code.
ImGui.BulletText(
"Return value = %d\n"
"IsItemFocused() = %d\n"
"IsItemHovered() = %d\n"
"IsItemHovered(_AllowWhenBlockedByPopup) = %d\n"
"IsItemHovered(_AllowWhenBlockedByActiveItem) = %d\n"
"IsItemHovered(_AllowWhenOverlapped) = %d\n"
"IsItemHovered(_AllowWhenDisabled) = %d\n"
"IsItemHovered(_RectOnly) = %d\n"
"IsItemActive() = %d\n"
"IsItemEdited() = %d\n"
"IsItemActivated() = %d\n"
"IsItemDeactivated() = %d\n"
"IsItemDeactivatedAfterEdit() = %d\n"
"IsItemVisible() = %d\n"
"IsItemClicked() = %d\n"
"IsItemToggledOpen() = %d\n"
"GetItemRectMin() = (%.1f, %.1f)\n"
"GetItemRectMax() = (%.1f, %.1f)\n"
"GetItemRectSize() = (%.1f, %.1f)",
ret,
ImGui.IsItemFocused(),
ImGui.IsItemHovered(),
ImGui.IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup),
ImGui.IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem),
ImGui.IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlapped),
ImGui.IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled),
ImGui.IsItemHovered(ImGuiHoveredFlags_RectOnly),
ImGui.IsItemActive(),
ImGui.IsItemEdited(),
ImGui.IsItemActivated(),
ImGui.IsItemDeactivated(),
ImGui.IsItemDeactivatedAfterEdit(),
ImGui.IsItemVisible(),
ImGui.IsItemClicked(),
ImGui.IsItemToggledOpen(),
ImGui.GetItemRectMin().x, ImGui.GetItemRectMin().y,
ImGui.GetItemRectMax().x, ImGui.GetItemRectMax().y,
ImGui.GetItemRectSize().x, ImGui.GetItemRectSize().y
);
if (item_disabled)
ImGui.EndDisabled();
local embed_all_inside_a_child_window = false;
ImGui.Checkbox("Embed everything inside a child window (for additional testing)", embed_all_inside_a_child_window);
if (embed_all_inside_a_child_window)
ImGui.BeginChild("outer_child", ImVec2(0, ImGui.GetFontSize() * 20.0), true);
-- Testing IsWindowFocused() function with its various flags.
-- Note that the ImGuiFocusedFlags_XXX flags can be combined.
ImGui.BulletText(
"IsWindowFocused() = %d\n"
"IsWindowFocused(_ChildWindows) = %d\n"
"IsWindowFocused(_ChildWindows|_RootWindow) = %d\n"
"IsWindowFocused(_RootWindow) = %d\n"
"IsWindowFocused(_AnyWindow) = %d\n",
ImGui.IsWindowFocused(),
ImGui.IsWindowFocused(ImGuiFocusedFlags_ChildWindows),
ImGui.IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow),
ImGui.IsWindowFocused(ImGuiFocusedFlags_RootWindow),
ImGui.IsWindowFocused(ImGuiFocusedFlags_AnyWindow));
-- Testing IsWindowHovered() function with its various flags.
-- Note that the ImGuiHoveredFlags_XXX flags can be combined.
ImGui.BulletText(
"IsWindowHovered() = %d\n"
"IsWindowHovered(_AllowWhenBlockedByPopup) = %d\n"
"IsWindowHovered(_AllowWhenBlockedByActiveItem) = %d\n"
"IsWindowHovered(_ChildWindows) = %d\n"
"IsWindowHovered(_ChildWindows|_RootWindow) = %d\n"
"IsWindowHovered(_ChildWindows|_AllowWhenBlockedByPopup) = %d\n"
"IsWindowHovered(_RootWindow) = %d\n"
"IsWindowHovered(_AnyWindow) = %d\n",
ImGui.IsWindowHovered(),
ImGui.IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup),
ImGui.IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem),
ImGui.IsWindowHovered(ImGuiHoveredFlags_ChildWindows),
ImGui.IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow),
ImGui.IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_AllowWhenBlockedByPopup),
ImGui.IsWindowHovered(ImGuiHoveredFlags_RootWindow),
ImGui.IsWindowHovered(ImGuiHoveredFlags_AnyWindow));
ImGui.BeginChild("child", ImVec2(0, 50), true);
ImGui.Text("This is another child window for testing the _ChildWindows flag.");
ImGui.EndChild();
if (embed_all_inside_a_child_window)
ImGui.EndChild();
static char unused_str[] = "This widget is only here to be able to tab-out of the widgets above.";
ImGui.InputText("unused", unused_str, IM_ARRAYSIZE(unused_str), ImGuiInputTextFlags_ReadOnly);
-- Calling IsItemHovered() after begin returns the hovered status of the title bar.
-- This is useful in particular if you want to create a context menu associated to the title bar of a window.
-- This will also work when docked into a Tab (the Tab replace the Title Bar and guarantee the same properties).
local test_window = false;
ImGui.Checkbox("Hovered/Active tests after Begin() for title bar testing", test_window);
if (test_window)then
-- FIXME-DOCK: This window cannot be docked within the ImGui Demo window, this will cause a feedback loop and get them stuck.
-- Could we fix this through an ImGuiWindowClass feature? Or an API call to tag our parent as "don't skip items"?
ImGui.Begin("Title bar Hovered/Active tests", test_window);
if (ImGui.BeginPopupContextItem()) -- <-- This is using IsItemHovered()then
if (ImGui.MenuItem("Close")) do test_window = false; end
ImGui.EndPopup();
end
ImGui.Text(
"IsItemHovered() after begin = %d (== is title bar hovered)\n"
"IsItemActive() after begin = %d (== is window being clicked/moved)\n",
ImGui.IsItemHovered(), ImGui.IsItemActive());
ImGui.End();
end
ImGui.TreePop();
end
end
function ShowDemoWindowLayout()
if (not ImGui.CollapsingHeader("Layout & Scrolling"))
return;
if (ImGui.TreeNode("Child windows"))then
HelpMarker("Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window.");
local disable_mouse_wheel = false;
local disable_menu = false;
ImGui.Checkbox("Disable Mouse Wheel", disable_mouse_wheel);
ImGui.Checkbox("Disable Menu", disable_menu);
-- Child 1: no border, enable horizontal scrollbarthen
ImGuiWindowFlags window_flags = ImGuiWindowFlags_HorizontalScrollbar;
if (disable_mouse_wheel)
window_flags |= ImGuiWindowFlags_NoScrollWithMouse;
ImGui.BeginChild("ChildL", ImVec2(ImGui.GetContentRegionAvail().x * 0.5f, 260), false, window_flags);
for (int i = 0; i < 100; i++)
ImGui.Text("%04d: scrollable region", i);
ImGui.EndChild();
end
ImGui.SameLine();
-- Child 2: rounded borderthen
ImGuiWindowFlags window_flags = ImGuiWindowFlags_None;
if (disable_mouse_wheel)
window_flags |= ImGuiWindowFlags_NoScrollWithMouse;
if (not disable_menu)
window_flags |= ImGuiWindowFlags_MenuBar;
ImGui.PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0);
ImGui.BeginChild("ChildR", ImVec2(0, 260), true, window_flags);
if (not disable_menu and ImGui.BeginMenuBar())then
if (ImGui.BeginMenu("Menu"))then
ShowExampleMenuFile();
ImGui.EndMenu();
end
ImGui.EndMenuBar();
end
if (ImGui.BeginTable("split", 2, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings))then
for (int i = 0; i < 100; i++)then
char buf[32];
sprintf(buf, "%03d", i);
ImGui.TableNextColumn();
ImGui.Button(buf, ImVec2(-FLT_MIN, 0.0));
end
ImGui.EndTable();
end
ImGui.EndChild();
ImGui.PopStyleVar();
end
ImGui.Separator();
-- Demonstrate a few extra things
-- - Changing ImGuiCol_ChildBg (which is transparent black in default styles)
-- - Using SetCursorPos() to position child window (the child window is an item from the POV of parent window)
-- You can also call SetNextWindowPos() to position the child window. The parent window will effectively
-- layout from this position.
-- - Using ImGui.GetItemRectMin/Max() to query the "item" state (because the child window is an item from
-- the POV of the parent window). See 'Demo->Querying Status (Edited/Active/Hovered etc.)' for details.then
static int offset_x = 0;
ImGui.SetNextItemWidth(ImGui.GetFontSize() * 8);
ImGui.DragInt("Offset X", offset_x, 1.0, -1000, 1000);
ImGui.SetCursorPosX(ImGui.GetCursorPosX() + (float)offset_x);
ImGui.PushStyleColor(ImGuiCol_ChildBg, IM_COL32(255, 0, 0, 100));
ImGui.BeginChild("Red", ImVec2(200, 100), true, ImGuiWindowFlags_None);
for (int n = 0; n < 50; n++)
ImGui.Text("Some test %d", n);
ImGui.EndChild();
bool child_is_hovered = ImGui.IsItemHovered();
ImVec2 child_rect_min = ImGui.GetItemRectMin();
ImVec2 child_rect_max = ImGui.GetItemRectMax();
ImGui.PopStyleColor();
ImGui.Text("Hovered: %d", child_is_hovered);
ImGui.Text("Rect of child window is: (%.0,%.0) (%.0,%.0)", child_rect_min.x, child_rect_min.y, child_rect_max.x, child_rect_max.y);
end
ImGui.TreePop();
end
if (ImGui.TreeNode("Widgets Width"))then
static float f = 0.0;
local show_indented_items = true;
ImGui.Checkbox("Show indented items", show_indented_items);
-- Use SetNextItemWidth() to set the width of a single upcoming item.
-- Use PushItemWidth()/PopItemWidth() to set the width of a group of items.
-- In real code use you'll probably want to choose width values that are proportional to your font size
-- e.g. Using '20.0 * GetFontSize()' as width instead of '200.0', etc.
ImGui.Text("SetNextItemWidth/PushItemWidth(100)");
ImGui.SameLine(); HelpMarker("Fixed width.");
ImGui.PushItemWidth(100);
ImGui.DragFloat("float----1b", f);
if (show_indented_items)then
ImGui.Indent();
ImGui.DragFloat("float (indented)----1b", f);
ImGui.Unindent();
end
ImGui.PopItemWidth();
ImGui.Text("SetNextItemWidth/PushItemWidth(-100)");
ImGui.SameLine(); HelpMarker("Align to right edge minus 100");
ImGui.PushItemWidth(-100);
ImGui.DragFloat("float----2a", f);
if (show_indented_items)then
ImGui.Indent();
ImGui.DragFloat("float (indented)----2b", f);
ImGui.Unindent();
end
ImGui.PopItemWidth();
ImGui.Text("SetNextItemWidth/PushItemWidth(GetContentRegionAvail().x * 0.5f)");
ImGui.SameLine(); HelpMarker("Half of available width.\n(~ right-cursor_pos)\n(works within a column set)");
ImGui.PushItemWidth(ImGui.GetContentRegionAvail().x * 0.5f);
ImGui.DragFloat("float----3a", f);
if (show_indented_items)then
ImGui.Indent();
ImGui.DragFloat("float (indented)----3b", f);
ImGui.Unindent();
end
ImGui.PopItemWidth();
ImGui.Text("SetNextItemWidth/PushItemWidth(-GetContentRegionAvail().x * 0.5f)");
ImGui.SameLine(); HelpMarker("Align to right edge minus half");
ImGui.PushItemWidth(-ImGui.GetContentRegionAvail().x * 0.5f);
ImGui.DragFloat("float----4a", f);
if (show_indented_items)then
ImGui.Indent();
ImGui.DragFloat("float (indented)----4b", f);
ImGui.Unindent();
end
ImGui.PopItemWidth();
-- Demonstrate using PushItemWidth to surround three items.
-- Calling SetNextItemWidth() before each of them would have the same effect.
ImGui.Text("SetNextItemWidth/PushItemWidth(-FLT_MIN)");
ImGui.SameLine(); HelpMarker("Align to right edge");
ImGui.PushItemWidth(-FLT_MIN);
ImGui.DragFloat("----float5a", f);
if (show_indented_items)then
ImGui.Indent();
ImGui.DragFloat("float (indented)----5b", f);
ImGui.Unindent();
end
ImGui.PopItemWidth();
ImGui.TreePop();
end
if (ImGui.TreeNode("Basic Horizontal Layout"))then
ImGui.TextWrapped("(Use ImGui.SameLine() to keep adding items to the right of the preceding item)");
-- Text
ImGui.Text("Two items: Hello"); ImGui.SameLine();
ImGui.TextColored(ImVec4(1,1,0,1), "Sailor");
-- Adjust spacing
ImGui.Text("More spacing: Hello"); ImGui.SameLine(0, 20);
ImGui.TextColored(ImVec4(1,1,0,1), "Sailor");
-- Button
ImGui.AlignTextToFramePadding();
ImGui.Text("Normal buttons"); ImGui.SameLine();
ImGui.Button("Banana"); ImGui.SameLine();
ImGui.Button("Apple"); ImGui.SameLine();
ImGui.Button("Corniflower");
-- Button
ImGui.Text("Small buttons"); ImGui.SameLine();
ImGui.SmallButton("Like this one"); ImGui.SameLine();
ImGui.Text("can fit within a text block.");
-- Aligned to arbitrary position. Easy/cheap column.
ImGui.Text("Aligned");
ImGui.SameLine(150); ImGui.Text("x=150");
ImGui.SameLine(300); ImGui.Text("x=300");
ImGui.Text("Aligned");
ImGui.SameLine(150); ImGui.SmallButton("x=150");
ImGui.SameLine(300); ImGui.SmallButton("x=300");
-- Checkbox
local c1 = false, c2 = false, c3 = false, c4 = false;
ImGui.Checkbox("My", c1); ImGui.SameLine();
ImGui.Checkbox("Tailor", c2); ImGui.SameLine();
ImGui.Checkbox("Is", c3); ImGui.SameLine();
ImGui.Checkbox("Rich", c4);
-- Various
static float f0 = 1.0, f1 = 2.0, f2 = 3.0;
ImGui.PushItemWidth(80);
const char* items[] = do "AAAA", "BBBB", "CCCC", "DDDD" end;
static int item = -1;
ImGui.Combo("Combo", item, items, IM_ARRAYSIZE(items)); ImGui.SameLine();
ImGui.SliderFloat("X", f0, 0.0, 5.0); ImGui.SameLine();
ImGui.SliderFloat("Y", f1, 0.0, 5.0); ImGui.SameLine();
ImGui.SliderFloat("Z", f2, 0.0, 5.0);
ImGui.PopItemWidth();
ImGui.PushItemWidth(80);
ImGui.Text("Lists:");
static int selection[4] = do 0, 1, 2, 3 end;
for (int i = 0; i < 4; i++)then
if (i > 0) ImGui.SameLine();
ImGui.PushID(i);
ImGui.ListBox("", selection[i], items, IM_ARRAYSIZE(items));
ImGui.PopID();
--if (ImGui.IsItemHovered()) ImGui.SetTooltip("ListBox %d hovered", i);
end
ImGui.PopItemWidth();
-- Dummy
ImVec2 button_sz(40, 40);
ImGui.Button("A", button_sz); ImGui.SameLine();
ImGui.Dummy(button_sz); ImGui.SameLine();
ImGui.Button("B", button_sz);
-- Manually wrapping
-- (we should eventually provide this as an automatic layout feature, but for now you can do it manually)
ImGui.Text("Manually wrapping:");
ImGuiStyle& style = ImGui.GetStyle();
int buttons_count = 20;
float window_visible_x2 = ImGui.GetWindowPos().x + ImGui.GetWindowContentRegionMax().x;
for (int n = 0; n < buttons_count; n++)then
ImGui.PushID(n);
ImGui.Button("Box", button_sz);
float last_button_x2 = ImGui.GetItemRectMax().x;
float next_button_x2 = last_button_x2 + style.ItemSpacing.x + button_sz.x; -- Expected position if next button was on same line
if (n + 1 < buttons_count and next_button_x2 < window_visible_x2)
ImGui.SameLine();
ImGui.PopID();
end
ImGui.TreePop();
end
if (ImGui.TreeNode("Groups"))then
HelpMarker(
"BeginGroup() basically locks the horizontal position for new line. "
"EndGroup() bundles the whole group so that you can use \"item\" functions such as "
"IsItemHovered()/IsItemActive() or SameLine() etc. on the whole group.");
ImGui.BeginGroup();then
ImGui.BeginGroup();
ImGui.Button("AAA");
ImGui.SameLine();
ImGui.Button("BBB");
ImGui.SameLine();
ImGui.BeginGroup();
ImGui.Button("CCC");
ImGui.Button("DDD");
ImGui.EndGroup();
ImGui.SameLine();
ImGui.Button("EEE");
ImGui.EndGroup();
if (ImGui.IsItemHovered())
ImGui.SetTooltip("First group hovered");
end
-- Capture the group size and create widgets using the same size
ImVec2 size = ImGui.GetItemRectSize();
const float values[5] = do 0.5f, 0..0, 0..0, 0..0, 0.25f end;
ImGui.PlotHistogram("----values", values, IM_ARRAYSIZE(values), 0, NULL, 0.0, 1.0, size);
ImGui.Button("ACTION", ImVec2((size.x - ImGui.GetStyle().ItemSpacing.x) * 0.5f, size.y));
ImGui.SameLine();
ImGui.Button("REACTION", ImVec2((size.x - ImGui.GetStyle().ItemSpacing.x) * 0.5f, size.y));
ImGui.EndGroup();
ImGui.SameLine();
ImGui.Button("LEVERAGE\nBUZZWORD", size);
ImGui.SameLine();
if (ImGui.BeginListBox("List", size))then
ImGui.Selectable("Selected", true);
ImGui.Selectable("Not Selected", false);
ImGui.EndListBox();
end
ImGui.TreePop();
end
if (ImGui.TreeNode("Text Baseline Alignment"))thenthen
ImGui.BulletText("Text baseline:");
ImGui.SameLine(); HelpMarker(
"This is testing the vertical alignment that gets applied on text to keep it aligned with widgets. "
"Lines only composed of text or \"small\" widgets use less vertical space than lines with framed widgets.");
ImGui.Indent();
ImGui.Text("KO Blahblah"); ImGui.SameLine();
ImGui.Button("Some framed item"); ImGui.SameLine();
HelpMarker("Baseline of button will look misaligned with text..");
-- If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets.
-- (because we don't know what's coming after the Text() statement, we need to move the text baseline
-- down by FramePadding.y ahead of time)
ImGui.AlignTextToFramePadding();
ImGui.Text("OK Blahblah"); ImGui.SameLine();
ImGui.Button("Some framed item"); ImGui.SameLine();
HelpMarker("We call AlignTextToFramePadding() to vertically align the text baseline by +FramePadding.y");
-- SmallButton() uses the same vertical padding as Text
ImGui.Button("TEST----1"); ImGui.SameLine();
ImGui.Text("TEST"); ImGui.SameLine();
ImGui.SmallButton("TEST----2");
-- If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets.
ImGui.AlignTextToFramePadding();
ImGui.Text("Text aligned to framed item"); ImGui.SameLine();
ImGui.Button("Item----1"); ImGui.SameLine();
ImGui.Text("Item"); ImGui.SameLine();
ImGui.SmallButton("Item----2"); ImGui.SameLine();
ImGui.Button("Item----3");
ImGui.Unindent();
end
ImGui.Spacing();then
ImGui.BulletText("Multi-line text:");
ImGui.Indent();
ImGui.Text("One\nTwo\nThree"); ImGui.SameLine();
ImGui.Text("Hello\nWorld"); ImGui.SameLine();
ImGui.Text("Banana");
ImGui.Text("Banana"); ImGui.SameLine();
ImGui.Text("Hello\nWorld"); ImGui.SameLine();
ImGui.Text("One\nTwo\nThree");
ImGui.Button("HOP----1"); ImGui.SameLine();
ImGui.Text("Banana"); ImGui.SameLine();
ImGui.Text("Hello\nWorld"); ImGui.SameLine();
ImGui.Text("Banana");
ImGui.Button("HOP----2"); ImGui.SameLine();
ImGui.Text("Hello\nWorld"); ImGui.SameLine();
ImGui.Text("Banana");
ImGui.Unindent();
end
ImGui.Spacing();then
ImGui.BulletText("Misc items:");
ImGui.Indent();
-- SmallButton() sets FramePadding to zero. Text baseline is aligned to match baseline of previous Button.
ImGui.Button("80x80", ImVec2(80, 80));
ImGui.SameLine();
ImGui.Button("50x50", ImVec2(50, 50));
ImGui.SameLine();
ImGui.Button("Button()");
ImGui.SameLine();
ImGui.SmallButton("SmallButton()");
-- Tree
const float spacing = ImGui.GetStyle().ItemInnerSpacing.x;
ImGui.Button("Button----1");
ImGui.SameLine(0.0, spacing);
if (ImGui.TreeNode("Node----1"))then
-- Placeholder tree data
for (int i = 0; i < 6; i++)
ImGui.BulletText("Item %d..", i);
ImGui.TreePop();
end
-- Vertically align text node a bit lower so it'll be vertically centered with upcoming widget.
-- Otherwise you can use SmallButton() (smaller fit).
ImGui.AlignTextToFramePadding();
-- Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add
-- other contents below the node.
bool node_open = ImGui.TreeNode("Node----2");
ImGui.SameLine(0.0, spacing); ImGui.Button("Button----2");
if (node_open)then
-- Placeholder tree data
for (int i = 0; i < 6; i++)
ImGui.BulletText("Item %d..", i);
ImGui.TreePop();
end
-- Bullet
ImGui.Button("Button----3");
ImGui.SameLine(0.0, spacing);
ImGui.BulletText("Bullet text");
ImGui.AlignTextToFramePadding();
ImGui.BulletText("Node");
ImGui.SameLine(0.0, spacing); ImGui.Button("Button----4");
ImGui.Unindent();
end
ImGui.TreePop();
end
if (ImGui.TreeNode("Scrolling"))then
-- Vertical scroll functions
HelpMarker("Use SetScrollHereY() or SetScrollFromPosY() to scroll to a given vertical position.");
static int track_item = 50;
local enable_track = true;
local enable_extra_decorations = false;
static float scroll_to_off_px = 0.0;
static float scroll_to_pos_px = 200.0;
ImGui.Checkbox("Decoration", enable_extra_decorations);
ImGui.Checkbox("Track", enable_track);
ImGui.PushItemWidth(100);
ImGui.SameLine(140); enable_track |= ImGui.DragInt("----item", track_item, 0.25f, 0, 99, "Item = %d");
bool scroll_to_off = ImGui.Button("Scroll Offset");
ImGui.SameLine(140); scroll_to_off |= ImGui.DragFloat("----off", scroll_to_off_px, 1..0, 0, FLT_MAX, "+%.0 px");
bool scroll_to_pos = ImGui.Button("Scroll To Pos");
ImGui.SameLine(140); scroll_to_pos |= ImGui.DragFloat("----pos", scroll_to_pos_px, 1..0, -10, FLT_MAX, "X/Y = %.0 px");
ImGui.PopItemWidth();
if (scroll_to_off or scroll_to_pos)
enable_track = false;
ImGuiStyle& style = ImGui.GetStyle();
float child_w = (ImGui.GetContentRegionAvail().x - 4 * style.ItemSpacing.x) / 5;
if (child_w < 1.0)
child_w = 1.0;
ImGui.PushID("----VerticalScrolling");
for (int i = 0; i < 5; i++)then
if (i > 0) ImGui.SameLine();
ImGui.BeginGroup();
const char* names[] = do "Top", "25%", "Center", "75%", "Bottom" end;
ImGui.TextUnformatted(names[i]);
const ImGuiWindowFlags child_flags = enable_extra_decorations ? ImGuiWindowFlags_MenuBar : 0;
const ImGuiID child_id = ImGui.GetID((void*)(intptr_t)i);
const bool child_is_visible = ImGui.BeginChild(child_id, ImVec2(child_w, 200.0), true, child_flags);
if (ImGui.BeginMenuBar())then
ImGui.TextUnformatted("abc");
ImGui.EndMenuBar();
end
if (scroll_to_off)
ImGui.SetScrollY(scroll_to_off_px);
if (scroll_to_pos)
ImGui.SetScrollFromPosY(ImGui.GetCursorStartPos().y + scroll_to_pos_px, i * 0.25f);
if (child_is_visible) -- Avoid calling SetScrollHereY when running with culled itemsthen
for (int item = 0; item < 100; item++)then
if (enable_track and item == track_item)then
ImGui.TextColored(ImVec4(1, 1, 0, 1), "Item %d", item);
ImGui.SetScrollHereY(i * 0.25f); -- 0.0:top, 0.5f:center, 1.0:bottom
end
elsethen
ImGui.Text("Item %d", item);
end
end
end
float scroll_y = ImGui.GetScrollY();
float scroll_max_y = ImGui.GetScrollMaxY();
ImGui.EndChild();
ImGui.Text("%.0/%.0", scroll_y, scroll_max_y);
ImGui.EndGroup();
end
ImGui.PopID();
-- Horizontal scroll functions
ImGui.Spacing();
HelpMarker(
"Use SetScrollHereX() or SetScrollFromPosX() to scroll to a given horizontal position.\n\n"
"Because the clipping rectangle of most window hides half worth of WindowPadding on the "
"left/right, using SetScrollFromPosX(+1) will usually result in clipped text whereas the "
"equivalent SetScrollFromPosY(+1) wouldn't.");
ImGui.PushID("----HorizontalScrolling");
for (int i = 0; i < 5; i++)then
float child_height = ImGui.GetTextLineHeight() + style.ScrollbarSize + style.WindowPadding.y * 2.0;
ImGuiWindowFlags child_flags = ImGuiWindowFlags_HorizontalScrollbar | (enable_extra_decorations ? ImGuiWindowFlags_AlwaysVerticalScrollbar : 0);
ImGuiID child_id = ImGui.GetID((void*)(intptr_t)i);
bool child_is_visible = ImGui.BeginChild(child_id, ImVec2(-100, child_height), true, child_flags);
if (scroll_to_off)
ImGui.SetScrollX(scroll_to_off_px);
if (scroll_to_pos)
ImGui.SetScrollFromPosX(ImGui.GetCursorStartPos().x + scroll_to_pos_px, i * 0.25f);
if (child_is_visible) -- Avoid calling SetScrollHereY when running with culled itemsthen
for (int item = 0; item < 100; item++)then
if (item > 0)
ImGui.SameLine();
if (enable_track and item == track_item)then
ImGui.TextColored(ImVec4(1, 1, 0, 1), "Item %d", item);
ImGui.SetScrollHereX(i * 0.25f); -- 0.0:left, 0.5f:center, 1.0:right
end
elsethen
ImGui.Text("Item %d", item);
end
end
end
float scroll_x = ImGui.GetScrollX();
float scroll_max_x = ImGui.GetScrollMaxX();
ImGui.EndChild();
ImGui.SameLine();
const char* names[] = do "Left", "25%", "Center", "75%", "Right" end;
ImGui.Text("%s\n%.0/%.0", names[i], scroll_x, scroll_max_x);
ImGui.Spacing();
end
ImGui.PopID();
-- Miscellaneous Horizontal Scrolling Demo
HelpMarker(
"Horizontal scrolling for a window is enabled via the ImGuiWindowFlags_HorizontalScrollbar flag.\n\n"
"You may want to also explicitly specify content width by using SetNextWindowContentWidth() before Begin().");
static int lines = 7;
ImGui.SliderInt("Lines", lines, 1, 15);
ImGui.PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0);
ImGui.PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2.0, 1.0));
ImVec2 scrolling_child_size = ImVec2(0, ImGui.GetFrameHeightWithSpacing() * 7 + 30);
ImGui.BeginChild("scrolling", scrolling_child_size, true, ImGuiWindowFlags_HorizontalScrollbar);
for (int line = 0; line < lines; line++)then
-- Display random stuff. For the sake of this trivial demo we are using basic Button() + SameLine()
-- If you want to create your own time line for a real application you may be better off manipulating
-- the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets
-- yourself. You may also want to use the lower-level ImDrawList API.
int num_buttons = 10 + ((line & 1) ? line * 9 : line * 3);
for (int n = 0; n < num_buttons; n++)then
if (n > 0) ImGui.SameLine();
ImGui.PushID(n + line * 1000);
char num_buf[16];
sprintf(num_buf, "%d", n);
const char* label = (not (n % 15)) ? "FizzBuzz" : (not (n % 3)) ? "Fizz" : (not (n % 5)) ? "Buzz" : num_buf;
float hue = n * 0.05f;
ImGui.PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor.HSV(hue, 0.6f, 0.6f));
ImGui.PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor.HSV(hue, 0.7f, 0.7f));
ImGui.PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor.HSV(hue, 0.8f, 0.8f));
ImGui.Button(label, ImVec2(40.0 + sinf((float)(line + n)) * 20.0, 0.0));
ImGui.PopStyleColor(3);
ImGui.PopID();
end
end
float scroll_x = ImGui.GetScrollX();
float scroll_max_x = ImGui.GetScrollMaxX();
ImGui.EndChild();
ImGui.PopStyleVar(2);
float scroll_x_delta = 0.0;
ImGui.SmallButton("<<");
if (ImGui.IsItemActive())
scroll_x_delta = -ImGui.GetIO().DeltaTime * 1000.0;
ImGui.SameLine();
ImGui.Text("Scroll from code"); ImGui.SameLine();
ImGui.SmallButton(">>");
if (ImGui.IsItemActive())
scroll_x_delta = +ImGui.GetIO().DeltaTime * 1000.0;
ImGui.SameLine();
ImGui.Text("%.0/%.0", scroll_x, scroll_max_x);
if (scroll_x_delta ~= 0.0)then
-- Demonstrate a trick: you can use Begin to set yourself in the context of another window
-- (here we are already out of your child window)
ImGui.BeginChild("scrolling");
ImGui.SetScrollX(ImGui.GetScrollX() + scroll_x_delta);
ImGui.EndChild();
end
ImGui.Spacing();
local show_horizontal_contents_size_demo_window = false;
ImGui.Checkbox("Show Horizontal contents size demo window", show_horizontal_contents_size_demo_window);
if (show_horizontal_contents_size_demo_window)then
local show_h_scrollbar = true;
local show_button = true;
local show_tree_nodes = true;
local show_text_wrapped = false;
local show_columns = true;
local show_tab_bar = true;
local show_child = false;
local explicit_content_size = false;
static float contents_size_x = 300.0;
if (explicit_content_size)
ImGui.SetNextWindowContentSize(ImVec2(contents_size_x, 0.0));
ImGui.Begin("Horizontal contents size demo window", show_horizontal_contents_size_demo_window, show_h_scrollbar ? ImGuiWindowFlags_HorizontalScrollbar : 0);
ImGui.PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2, 0));
ImGui.PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 0));
HelpMarker("Test of different widgets react and impact the work rectangle growing when horizontal scrolling is enabled.\n\nUse 'Metrics->Tools->Show windows rectangles' to visualize rectangles.");
ImGui.Checkbox("H-scrollbar", show_h_scrollbar);
ImGui.Checkbox("Button", show_button); -- Will grow contents size (unless explicitly overwritten)
ImGui.Checkbox("Tree nodes", show_tree_nodes); -- Will grow contents size and display highlight over full width
ImGui.Checkbox("Text wrapped", show_text_wrapped);-- Will grow and use contents size
ImGui.Checkbox("Columns", show_columns); -- Will use contents size
ImGui.Checkbox("Tab bar", show_tab_bar); -- Will use contents size
ImGui.Checkbox("Child", show_child); -- Will grow and use contents size
ImGui.Checkbox("Explicit content size", explicit_content_size);
ImGui.Text("Scroll %.1f/%.1f %.1f/%.1f", ImGui.GetScrollX(), ImGui.GetScrollMaxX(), ImGui.GetScrollY(), ImGui.GetScrollMaxY());
if (explicit_content_size)then
ImGui.SameLine();
ImGui.SetNextItemWidth(100);
ImGui.DragFloat("----csx", contents_size_x);
ImVec2 p = ImGui.GetCursorScreenPos();
ImGui.GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x + 10, p.y + 10), IM_COL32_WHITE);
ImGui.GetWindowDrawList()->AddRectFilled(ImVec2(p.x + contents_size_x - 10, p.y), ImVec2(p.x + contents_size_x, p.y + 10), IM_COL32_WHITE);
ImGui.Dummy(ImVec2(0, 10));
end
ImGui.PopStyleVar(2);
ImGui.Separator();
if (show_button)then
ImGui.Button("this is a 300-wide button", ImVec2(300, 0));
end
if (show_tree_nodes)then
bool open = true;
if (ImGui.TreeNode("this is a tree node"))then
if (ImGui.TreeNode("another one of those tree node..."))then
ImGui.Text("Some tree contents");
ImGui.TreePop();
end
ImGui.TreePop();
end
ImGui.CollapsingHeader("CollapsingHeader", open);
end
if (show_text_wrapped)then
ImGui.TextWrapped("This text should automatically wrap on the edge of the work rectangle.");
end
if (show_columns)then
ImGui.Text("Tables:");
if (ImGui.BeginTable("table", 4, ImGuiTableFlags_Borders))then
for (int n = 0; n < 4; n++)then
ImGui.TableNextColumn();
ImGui.Text("Width %.2f", ImGui.GetContentRegionAvail().x);
end
ImGui.EndTable();
end
ImGui.Text("Columns:");
ImGui.Columns(4);
for (int n = 0; n < 4; n++)then
ImGui.Text("Width %.2f", ImGui.GetColumnWidth());
ImGui.NextColumn();
end
ImGui.Columns(1);
end
if (show_tab_bar and ImGui.BeginTabBar("Hello"))then
if (ImGui.BeginTabItem("OneOneOne")) do ImGui.EndTabItem(); end
if (ImGui.BeginTabItem("TwoTwoTwo")) do ImGui.EndTabItem(); end
if (ImGui.BeginTabItem("ThreeThreeThree")) do ImGui.EndTabItem(); end
if (ImGui.BeginTabItem("FourFourFour")) do ImGui.EndTabItem(); end
ImGui.EndTabBar();
end
if (show_child)then
ImGui.BeginChild("child", ImVec2(0, 0), true);
ImGui.EndChild();
end
ImGui.End();
end
ImGui.TreePop();
end
if (ImGui.TreeNode("Clipping"))then
static ImVec2 size(100.0, 100.0);
static ImVec2 offset(30.0, 30.0);
ImGui.DragFloat2("size", (float*)&size, 0.5f, 1.0, 200.0, "%.0");
ImGui.TextWrapped("(Click and drag to scroll)");
for (int n = 0; n < 3; n++)then
if (n > 0)
ImGui.SameLine();
ImGui.PushID(n);
ImGui.BeginGroup(); -- Lock X position
ImGui.InvisibleButton("----empty", size);
if (ImGui.IsItemActive() and ImGui.IsMouseDragging(ImGuiMouseButton_Left))then
offset.x += ImGui.GetIO().MouseDelta.x;
offset.y += ImGui.GetIO().MouseDelta.y;
end
const ImVec2 p0 = ImGui.GetItemRectMin();
const ImVec2 p1 = ImGui.GetItemRectMax();
const char* text_str = "Line 1 hello\nLine 2 clip menot ";
const ImVec2 text_pos = ImVec2(p0.x + offset.x, p0.y + offset.y);
ImDrawList* draw_list = ImGui.GetWindowDrawList();
switch (n)then
case 0:
HelpMarker(
"Using ImGui.PushClipRect():\n"
"Will alter ImGui hit-testing logic + ImDrawList rendering.\n"
"(use this if you want your clipping rectangle to affect interactions)");
ImGui.PushClipRect(p0, p1, true);
draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255));
draw_list->AddText(text_pos, IM_COL32_WHITE, text_str);
ImGui.PopClipRect();
break;
case 1:
HelpMarker(
"Using ImDrawList.PushClipRect():\n"
"Will alter ImDrawList rendering only.\n"
"(use this as a shortcut if you are only using ImDrawList calls)");
draw_list->PushClipRect(p0, p1, true);
draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255));
draw_list->AddText(text_pos, IM_COL32_WHITE, text_str);
draw_list->PopClipRect();
break;
case 2:
HelpMarker(
"Using ImDrawList.AddText() with a fine ClipRect:\n"
"Will alter only this specific ImDrawList.AddText() rendering.\n"
"(this is often used internally to avoid altering the clipping rectangle and minimize draw calls)");
ImVec4 clip_rect(p0.x, p0.y, p1.x, p1.y); -- AddText() takes a ImVec4* here so let's convert.
draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255));
draw_list->AddText(ImGui.GetFont(), ImGui.GetFontSize(), text_pos, IM_COL32_WHITE, text_str, NULL, 0.0, clip_rect);
break;
end
ImGui.EndGroup();
ImGui.PopID();
end
ImGui.TreePop();
end
end
-- Dummy data structure that we use for the Table demo.
-- (pre-C++11 doesn't allow us to instantiate ImVector<MyItem> template if this structure if defined inside the demo function)
--namespace
--do
-- We are passing our own identifier to TableSetupColumn() to facilitate identifying columns in the sorting code.
-- This identifier will be passed down into ImGuiTableSortSpec.ColumnUserID.
-- But it is possible to omit the user id parameter of TableSetupColumn() and just use the column index insteadnot (ImGuiTableSortSpec.ColumnIndex)
-- If you don't use sorting, you will generally never care about giving column an IDnot
enum MyItemColumnID
MyItemColumnID_ID,
MyItemColumnID_Name,
MyItemColumnID_Action,
MyItemColumnID_Quantity,
MyItemColumnID_Description
end;
struct MyItem
int ID;
const char* Name;
int Quantity;
-- We have a problem which is affecting _only this demo_ and should not affect your code:
-- As we don't rely on std. or other third-party library to compile dear imgui, we only have reliable access to qsort(),
-- however qsort doesn't allow passing user data to comparing function.
-- As a workaround, we are storing the sort specs in a static/global for the comparing function to access.
-- In your own use case you would probably pass the sort specs to your sorting/comparing functions directly and not use a global.
-- We could technically call ImGui.TableGetSortSpecs() in CompareWithSortSpecs(), but considering that this function is called
-- very often by the sorting algorithm it would be a little wasteful.
static const ImGuiTableSortSpecs* s_current_sort_specs;
-- Compare function to be used by qsort()
static int IMGUI_CDECL CompareWithSortSpecs(const void* lhs, const void* rhs)then
const MyItem* a = (const MyItem*)lhs;
const MyItem* b = (const MyItem*)rhs;
for (int n = 0; n < s_current_sort_specs->SpecsCount; n++)then
-- Here we identify columns using the ColumnUserID value that we ourselves passed to TableSetupColumn()
-- We could also choose to identify columns based on their index (sort_spec->ColumnIndex), which is simplernot
const ImGuiTableColumnSortSpecs* sort_spec = &s_current_sort_specs->Specs[n];
int delta = 0;
switch (sort_spec->ColumnUserID)then
case MyItemColumnID_ID: delta = (a->ID - b->ID); break;
case MyItemColumnID_Name: delta = (strcmp(a->Name, b->Name)); break;
case MyItemColumnID_Quantity: delta = (a->Quantity - b->Quantity); break;
case MyItemColumnID_Description: delta = (strcmp(a->Name, b->Name)); break;
default: IM_ASSERT(0); break;
end
if (delta > 0)
return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? +1 : -1;
if (delta < 0)
return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? -1 : +1;
end
-- qsort() is instable so always return a way to differenciate items.
-- Your own compare function may want to avoid fallback on implicit sort specs e.g. a Name compare if it wasn't already part of the sort specs.
return (a->ID - b->ID);
end
end;
const ImGuiTableSortSpecs* MyItem.s_current_sort_specs = NULL;
--end
-- Make the UI compact because there are so many fields
function PushStyleCompact()
ImGuiStyle& style = ImGui.GetStyle();
ImGui.PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(style.FramePadding.x, (float)(int)(style.FramePadding.y * 0..0)));
ImGui.PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x, (float)(int)(style.ItemSpacing.y * 0..0)));
end
function PopStyleCompact()
ImGui.PopStyleVar(2);
end
-- Show a combo box with a choice of sizing policies
function EditTableSizingFlags(ImGuiTableFlags* p_flags)
struct EnumDesc do ImGuiTableFlags Value; const char* Name; const char* Tooltip; end;
static const EnumDesc policies[] =thenthen ImGuiTableFlags_None, "Default", "Use default sizing policy:\n- ImGuiTableFlags_SizingFixedFit if ScrollX is on or if host window has ImGuiWindowFlags_AlwaysAutoResize.\n- ImGuiTableFlags_SizingStretchSame otherwise." end,then ImGuiTableFlags_SizingFixedFit, "ImGuiTableFlags_SizingFixedFit", "Columns default to _WidthFixed (if resizable) or _WidthAuto (if not resizable), matching contents width." end,then ImGuiTableFlags_SizingFixedSame, "ImGuiTableFlags_SizingFixedSame", "Columns are all the same width, matching the maximum contents width.\nImplicitly disable ImGuiTableFlags_Resizable and enable ImGuiTableFlags_NoKeepColumnsVisible." end,then ImGuiTableFlags_SizingStretchProp, "ImGuiTableFlags_SizingStretchProp", "Columns default to _WidthStretch with weights proportional to their widths." end,then ImGuiTableFlags_SizingStretchSame, "ImGuiTableFlags_SizingStretchSame", "Columns default to _WidthStretch with same weights." end
end;
int idx;
for (idx = 0; idx < IM_ARRAYSIZE(policies); idx++)
if (policies[idx].Value == (*p_flags & ImGuiTableFlags_SizingMask_))
break;
const char* preview_text = (idx < IM_ARRAYSIZE(policies)) ? policies[idx].Name + (idx > 0 ? strlen("ImGuiTableFlags") : 0) : "";
if (ImGui.BeginCombo("Sizing Policy", preview_text))then
for (int n = 0; n < IM_ARRAYSIZE(policies); n++)
if (ImGui.Selectable(policies[n].Name, idx == n))
*p_flags = (*p_flags & ~ImGuiTableFlags_SizingMask_) | policies[n].Value;
ImGui.EndCombo();
end
ImGui.SameLine();
ImGui.TextDisabled("(?)");
if (ImGui.IsItemHovered())then
ImGui.BeginTooltip();
ImGui.PushTextWrapPos(ImGui.GetFontSize() * 50.0);
for (int m = 0; m < IM_ARRAYSIZE(policies); m++)then
ImGui.Separator();
ImGui.Text("%s:", policies[m].Name);
ImGui.Separator();
ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().IndentSpacing * 0.5f);
ImGui.TextUnformatted(policies[m].Tooltip);
end
ImGui.PopTextWrapPos();
ImGui.EndTooltip();
end
end
function EditTableColumnsFlags(ImGuiTableColumnFlags* p_flags)
ImGui.CheckboxFlags("_Disabled", p_flags, ImGuiTableColumnFlags_Disabled); ImGui.SameLine(); HelpMarker("Master disable flag (also hide from context menu)");
ImGui.CheckboxFlags("_DefaultHide", p_flags, ImGuiTableColumnFlags_DefaultHide);
ImGui.CheckboxFlags("_DefaultSort", p_flags, ImGuiTableColumnFlags_DefaultSort);
if (ImGui.CheckboxFlags("_WidthStretch", p_flags, ImGuiTableColumnFlags_WidthStretch))
*p_flags &= ~(ImGuiTableColumnFlags_WidthMask_ ^ ImGuiTableColumnFlags_WidthStretch);
if (ImGui.CheckboxFlags("_WidthFixed", p_flags, ImGuiTableColumnFlags_WidthFixed))
*p_flags &= ~(ImGuiTableColumnFlags_WidthMask_ ^ ImGuiTableColumnFlags_WidthFixed);
ImGui.CheckboxFlags("_NoResize", p_flags, ImGuiTableColumnFlags_NoResize);
ImGui.CheckboxFlags("_NoReorder", p_flags, ImGuiTableColumnFlags_NoReorder);
ImGui.CheckboxFlags("_NoHide", p_flags, ImGuiTableColumnFlags_NoHide);
ImGui.CheckboxFlags("_NoClip", p_flags, ImGuiTableColumnFlags_NoClip);
ImGui.CheckboxFlags("_NoSort", p_flags, ImGuiTableColumnFlags_NoSort);
ImGui.CheckboxFlags("_NoSortAscending", p_flags, ImGuiTableColumnFlags_NoSortAscending);
ImGui.CheckboxFlags("_NoSortDescending", p_flags, ImGuiTableColumnFlags_NoSortDescending);
ImGui.CheckboxFlags("_NoHeaderLabel", p_flags, ImGuiTableColumnFlags_NoHeaderLabel);
ImGui.CheckboxFlags("_NoHeaderWidth", p_flags, ImGuiTableColumnFlags_NoHeaderWidth);
ImGui.CheckboxFlags("_PreferSortAscending", p_flags, ImGuiTableColumnFlags_PreferSortAscending);
ImGui.CheckboxFlags("_PreferSortDescending", p_flags, ImGuiTableColumnFlags_PreferSortDescending);
ImGui.CheckboxFlags("_IndentEnable", p_flags, ImGuiTableColumnFlags_IndentEnable); ImGui.SameLine(); HelpMarker("Default for column 0");
ImGui.CheckboxFlags("_IndentDisable", p_flags, ImGuiTableColumnFlags_IndentDisable); ImGui.SameLine(); HelpMarker("Default for column >0");
end
function ShowTableColumnsStatusFlags(ImGuiTableColumnFlags flags)
ImGui.CheckboxFlags("_IsEnabled", flags, ImGuiTableColumnFlags_IsEnabled);
ImGui.CheckboxFlags("_IsVisible", flags, ImGuiTableColumnFlags_IsVisible);
ImGui.CheckboxFlags("_IsSorted", flags, ImGuiTableColumnFlags_IsSorted);
ImGui.CheckboxFlags("_IsHovered", flags, ImGuiTableColumnFlags_IsHovered);
end
function ShowDemoWindowTables()
--ImGui.SetNextItemOpen(true, ImGuiCond_Once);
if (not ImGui.CollapsingHeader("Tables & Columns"))
return;
-- Using those as a base value to create width/height that are factor of the size of our font
const float TEXT_BASE_WIDTH = ImGui.CalcTextSize("A").x;
const float TEXT_BASE_HEIGHT = ImGui.GetTextLineHeightWithSpacing();
ImGui.PushID("Tables");
int open_action = -1;
if (ImGui.Button("Open all"))
open_action = 1;
ImGui.SameLine();
if (ImGui.Button("Close all"))
open_action = 0;
ImGui.SameLine();
-- Options
local disable_indent = false;
ImGui.Checkbox("Disable tree indentation", disable_indent);
ImGui.SameLine();
HelpMarker("Disable the indenting of tree nodes so demo tables can use the full window width.");
ImGui.Separator();
if (disable_indent)
ImGui.PushStyleVar(ImGuiStyleVar_IndentSpacing, 0.0);
-- About Styling of tables
-- Most settings are configured on a per-table basis via the flags passed to BeginTable() and TableSetupColumns APIs.
-- There are however a few settings that a shared and part of the ImGuiStyle structure:
-- style.CellPadding -- Padding within each cell
-- style.Colors[ImGuiCol_TableHeaderBg] -- Table header background
-- style.Colors[ImGuiCol_TableBorderStrong] -- Table outer and header borders
-- style.Colors[ImGuiCol_TableBorderLight] -- Table inner borders
-- style.Colors[ImGuiCol_TableRowBg] -- Table row background when ImGuiTableFlags_RowBg is enabled (even rows)
-- style.Colors[ImGuiCol_TableRowBgAlt] -- Table row background when ImGuiTableFlags_RowBg is enabled (odds rows)
-- Demos
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Basic"))then
-- Here we will showcase three different ways to output a table.
-- They are very simple variations of a same thingnot
-- [Method 1] Using TableNextRow() to create a new row, and TableSetColumnIndex() to select the column.
-- In many situations, this is the most flexible and easy to use pattern.
HelpMarker("Using TableNextRow() + calling TableSetColumnIndex() _before_ each cell, in a loop.");
if (ImGui.BeginTable("table1", 3))then
for (int row = 0; row < 4; row++)then
ImGui.TableNextRow();
for (int column = 0; column < 3; column++)then
ImGui.TableSetColumnIndex(column);
ImGui.Text("Row %d Column %d", row, column);
end
end
ImGui.EndTable();
end
-- [Method 2] Using TableNextColumn() called multiple times, instead of using a for loop + TableSetColumnIndex().
-- This is generally more convenient when you have code manually submitting the contents of each columns.
HelpMarker("Using TableNextRow() + calling TableNextColumn() _before_ each cell, manually.");
if (ImGui.BeginTable("table2", 3))then
for (int row = 0; row < 4; row++)then
ImGui.TableNextRow();
ImGui.TableNextColumn();
ImGui.Text("Row %d", row);
ImGui.TableNextColumn();
ImGui.Text("Some contents");
ImGui.TableNextColumn();
ImGui.Text("123.456");
end
ImGui.EndTable();
end
-- [Method 3] We call TableNextColumn() _before_ each cell. We never call TableNextRow(),
-- as TableNextColumn() will automatically wrap around and create new roes as needed.
-- This is generally more convenient when your cells all contains the same type of data.
HelpMarker(
"Only using TableNextColumn(), which tends to be convenient for tables where every cells contains the same type of contents.\n"
"This is also more similar to the old NextColumn() function of the Columns API, and provided to facilitate the Columns->Tables API transition.");
if (ImGui.BeginTable("table3", 3))then
for (int item = 0; item < 14; item++)then
ImGui.TableNextColumn();
ImGui.Text("Item %d", item);
end
ImGui.EndTable();
end
ImGui.TreePop();
end
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Borders, background"))then
-- Expose a few Borders related flags interactively
enum ContentsType do CT_Text, CT_FillButton end;
static ImGuiTableFlags flags = ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg;
local display_headers = false;
static int contents_type = CT_Text;
PushStyleCompact();
ImGui.CheckboxFlags("ImGuiTableFlags_RowBg", flags, ImGuiTableFlags_RowBg);
ImGui.CheckboxFlags("ImGuiTableFlags_Borders", flags, ImGuiTableFlags_Borders);
ImGui.SameLine(); HelpMarker("ImGuiTableFlags_Borders\n = ImGuiTableFlags_BordersInnerV\n | ImGuiTableFlags_BordersOuterV\n | ImGuiTableFlags_BordersInnerV\n | ImGuiTableFlags_BordersOuterH");
ImGui.Indent();
ImGui.CheckboxFlags("ImGuiTableFlags_BordersH", flags, ImGuiTableFlags_BordersH);
ImGui.Indent();
ImGui.CheckboxFlags("ImGuiTableFlags_BordersOuterH", flags, ImGuiTableFlags_BordersOuterH);
ImGui.CheckboxFlags("ImGuiTableFlags_BordersInnerH", flags, ImGuiTableFlags_BordersInnerH);
ImGui.Unindent();
ImGui.CheckboxFlags("ImGuiTableFlags_BordersV", flags, ImGuiTableFlags_BordersV);
ImGui.Indent();
ImGui.CheckboxFlags("ImGuiTableFlags_BordersOuterV", flags, ImGuiTableFlags_BordersOuterV);
ImGui.CheckboxFlags("ImGuiTableFlags_BordersInnerV", flags, ImGuiTableFlags_BordersInnerV);
ImGui.Unindent();
ImGui.CheckboxFlags("ImGuiTableFlags_BordersOuter", flags, ImGuiTableFlags_BordersOuter);
ImGui.CheckboxFlags("ImGuiTableFlags_BordersInner", flags, ImGuiTableFlags_BordersInner);
ImGui.Unindent();
ImGui.AlignTextToFramePadding(); ImGui.Text("Cell contents:");
ImGui.SameLine(); ImGui.RadioButton("Text", contents_type, CT_Text);
ImGui.SameLine(); ImGui.RadioButton("FillButton", contents_type, CT_FillButton);
ImGui.Checkbox("Display headers", display_headers);
ImGui.CheckboxFlags("ImGuiTableFlags_NoBordersInBody", flags, ImGuiTableFlags_NoBordersInBody); ImGui.SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appears in Headers");
PopStyleCompact();
if (ImGui.BeginTable("table1", 3, flags))then
-- Display headers so we can inspect their interaction with borders.
-- (Headers are not the main purpose of this section of the demo, so we are not elaborating on them too much. See other sections for details)
if (display_headers)then
ImGui.TableSetupColumn("One");
ImGui.TableSetupColumn("Two");
ImGui.TableSetupColumn("Three");
ImGui.TableHeadersRow();
end
for (int row = 0; row < 5; row++)then
ImGui.TableNextRow();
for (int column = 0; column < 3; column++)then
ImGui.TableSetColumnIndex(column);
char buf[32];
sprintf(buf, "Hello %d,%d", column, row);
if (contents_type == CT_Text)
ImGui.TextUnformatted(buf);
else if (contents_type)
ImGui.Button(buf, ImVec2(-FLT_MIN, 0.0));
end
end
ImGui.EndTable();
end
ImGui.TreePop();
end
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Resizable, stretch"))then
-- By default, if we don't enable ScrollX the sizing policy for each columns is "Stretch"
-- Each columns maintain a sizing weight, and they will occupy all available width.
static ImGuiTableFlags flags = ImGuiTableFlags_SizingStretchSame | ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_ContextMenuInBody;
PushStyleCompact();
ImGui.CheckboxFlags("ImGuiTableFlags_Resizable", flags, ImGuiTableFlags_Resizable);
ImGui.CheckboxFlags("ImGuiTableFlags_BordersV", flags, ImGuiTableFlags_BordersV);
ImGui.SameLine(); HelpMarker("Using the _Resizable flag automatically enables the _BordersInnerV flag as well, this is why the resize borders are still showing when unchecking this.");
PopStyleCompact();
if (ImGui.BeginTable("table1", 3, flags))then
for (int row = 0; row < 5; row++)then
ImGui.TableNextRow();
for (int column = 0; column < 3; column++)then
ImGui.TableSetColumnIndex(column);
ImGui.Text("Hello %d,%d", column, row);
end
end
ImGui.EndTable();
end
ImGui.TreePop();
end
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Resizable, fixed"))then
-- Here we use ImGuiTableFlags_SizingFixedFit (even though _ScrollX is not set)
-- So columns will adopt the "Fixed" policy and will maintain a fixed width regardless of the whole available width (unless table is small)
-- If there is not enough available width to fit all columns, they will however be resized down.
-- FIXME-TABLE: Providing a stretch-on-init would make sense especially for tables which don't have saved settings
HelpMarker(
"Using _Resizable + _SizingFixedFit flags.\n"
"Fixed-width columns generally makes more sense if you want to use horizontal scrolling.\n\n"
"Double-click a column border to auto-fit the column to its contents.");
PushStyleCompact();
static ImGuiTableFlags flags = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_ContextMenuInBody;
ImGui.CheckboxFlags("ImGuiTableFlags_NoHostExtendX", flags, ImGuiTableFlags_NoHostExtendX);
PopStyleCompact();
if (ImGui.BeginTable("table1", 3, flags))then
for (int row = 0; row < 5; row++)then
ImGui.TableNextRow();
for (int column = 0; column < 3; column++)then
ImGui.TableSetColumnIndex(column);
ImGui.Text("Hello %d,%d", column, row);
end
end
ImGui.EndTable();
end
ImGui.TreePop();
end
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Resizable, mixed"))then
HelpMarker(
"Using TableSetupColumn() to alter resizing policy on a per-column basis.\n\n"
"When combining Fixed and Stretch columns, generally you only want one, maybe two trailing columns to use _WidthStretch.");
static ImGuiTableFlags flags = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable;
if (ImGui.BeginTable("table1", 3, flags))then
ImGui.TableSetupColumn("AAA", ImGuiTableColumnFlags_WidthFixed);
ImGui.TableSetupColumn("BBB", ImGuiTableColumnFlags_WidthFixed);
ImGui.TableSetupColumn("CCC", ImGuiTableColumnFlags_WidthStretch);
ImGui.TableHeadersRow();
for (int row = 0; row < 5; row++)then
ImGui.TableNextRow();
for (int column = 0; column < 3; column++)then
ImGui.TableSetColumnIndex(column);
ImGui.Text("%s %d,%d", (column == 2) ? "Stretch" : "Fixed", column, row);
end
end
ImGui.EndTable();
end
if (ImGui.BeginTable("table2", 6, flags))then
ImGui.TableSetupColumn("AAA", ImGuiTableColumnFlags_WidthFixed);
ImGui.TableSetupColumn("BBB", ImGuiTableColumnFlags_WidthFixed);
ImGui.TableSetupColumn("CCC", ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_DefaultHide);
ImGui.TableSetupColumn("DDD", ImGuiTableColumnFlags_WidthStretch);
ImGui.TableSetupColumn("EEE", ImGuiTableColumnFlags_WidthStretch);
ImGui.TableSetupColumn("FFF", ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_DefaultHide);
ImGui.TableHeadersRow();
for (int row = 0; row < 5; row++)then
ImGui.TableNextRow();
for (int column = 0; column < 6; column++)then
ImGui.TableSetColumnIndex(column);
ImGui.Text("%s %d,%d", (column >= 3) ? "Stretch" : "Fixed", column, row);
end
end
ImGui.EndTable();
end
ImGui.TreePop();
end
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Reorderable, hideable, with headers"))then
HelpMarker(
"Click and drag column headers to reorder columns.\n\n"
"Right-click on a header to open a context menu.");
static ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV;
PushStyleCompact();
ImGui.CheckboxFlags("ImGuiTableFlags_Resizable", flags, ImGuiTableFlags_Resizable);
ImGui.CheckboxFlags("ImGuiTableFlags_Reorderable", flags, ImGuiTableFlags_Reorderable);
ImGui.CheckboxFlags("ImGuiTableFlags_Hideable", flags, ImGuiTableFlags_Hideable);
ImGui.CheckboxFlags("ImGuiTableFlags_NoBordersInBody", flags, ImGuiTableFlags_NoBordersInBody);
ImGui.CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", flags, ImGuiTableFlags_NoBordersInBodyUntilResize); ImGui.SameLine(); HelpMarker("Disable vertical borders in columns Body until hovered for resize (borders will always appears in Headers)");
PopStyleCompact();
if (ImGui.BeginTable("table1", 3, flags))then
-- Submit columns name with TableSetupColumn() and call TableHeadersRow() to create a row with a header in each column.
-- (Later we will show how TableSetupColumn() has other uses, optional flags, sizing weight etc.)
ImGui.TableSetupColumn("One");
ImGui.TableSetupColumn("Two");
ImGui.TableSetupColumn("Three");
ImGui.TableHeadersRow();
for (int row = 0; row < 6; row++)then
ImGui.TableNextRow();
for (int column = 0; column < 3; column++)then
ImGui.TableSetColumnIndex(column);
ImGui.Text("Hello %d,%d", column, row);
end
end
ImGui.EndTable();
end
-- Use outer_size.x == 0.0 instead of default to make the table as tight as possible (only valid when no scrolling and no stretch column)
if (ImGui.BeginTable("table2", 3, flags | ImGuiTableFlags_SizingFixedFit, ImVec2(0.0, 0.0)))then
ImGui.TableSetupColumn("One");
ImGui.TableSetupColumn("Two");
ImGui.TableSetupColumn("Three");
ImGui.TableHeadersRow();
for (int row = 0; row < 6; row++)then
ImGui.TableNextRow();
for (int column = 0; column < 3; column++)then
ImGui.TableSetColumnIndex(column);
ImGui.Text("Fixed %d,%d", column, row);
end
end
ImGui.EndTable();
end
ImGui.TreePop();
end
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Padding"))then
-- First example: showcase use of padding flags and effect of BorderOuterV/BorderInnerV on X padding.
-- We don't expose BorderOuterH/BorderInnerH here because they have no effect on X padding.
HelpMarker(
"We often want outer padding activated when any using features which makes the edges of a column visible:\n"
"e.g.:\n"
"- BorderOuterV\n"
"- any form of row selection\n"
"Because of this, activating BorderOuterV sets the default to PadOuterX. Using PadOuterX or NoPadOuterX you can override the default.\n\n"
"Actual padding values are using style.CellPadding.\n\n"
"In this demo we don't show horizontal borders to emphasis how they don't affect default horizontal padding.");
static ImGuiTableFlags flags1 = ImGuiTableFlags_BordersV;
PushStyleCompact();
ImGui.CheckboxFlags("ImGuiTableFlags_PadOuterX", flags1, ImGuiTableFlags_PadOuterX);
ImGui.SameLine(); HelpMarker("Enable outer-most padding (default if ImGuiTableFlags_BordersOuterV is set)");
ImGui.CheckboxFlags("ImGuiTableFlags_NoPadOuterX", flags1, ImGuiTableFlags_NoPadOuterX);
ImGui.SameLine(); HelpMarker("Disable outer-most padding (default if ImGuiTableFlags_BordersOuterV is not set)");
ImGui.CheckboxFlags("ImGuiTableFlags_NoPadInnerX", flags1, ImGuiTableFlags_NoPadInnerX);
ImGui.SameLine(); HelpMarker("Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off)");
ImGui.CheckboxFlags("ImGuiTableFlags_BordersOuterV", flags1, ImGuiTableFlags_BordersOuterV);
ImGui.CheckboxFlags("ImGuiTableFlags_BordersInnerV", flags1, ImGuiTableFlags_BordersInnerV);
local show_headers = false;
ImGui.Checkbox("show_headers", show_headers);
PopStyleCompact();
if (ImGui.BeginTable("table_padding", 3, flags1))then
if (show_headers)then
ImGui.TableSetupColumn("One");
ImGui.TableSetupColumn("Two");
ImGui.TableSetupColumn("Three");
ImGui.TableHeadersRow();
end
for (int row = 0; row < 5; row++)then
ImGui.TableNextRow();
for (int column = 0; column < 3; column++)then
ImGui.TableSetColumnIndex(column);
if (row == 0)then
ImGui.Text("Avail %.2f", ImGui.GetContentRegionAvail().x);
end
elsethen
char buf[32];
sprintf(buf, "Hello %d,%d", column, row);
ImGui.Button(buf, ImVec2(-FLT_MIN, 0.0));
end
--if (ImGui.TableGetColumnFlags() & ImGuiTableColumnFlags_IsHovered)
-- ImGui.TableSetBgColor(ImGuiTableBgTarget_CellBg, IM_COL32(0, 100, 0, 255));
end
end
ImGui.EndTable();
end
-- Second example: set style.CellPadding to (0.0) or a custom value.
-- FIXME-TABLE: Vertical border effectively not displayed the same way as horizontal one...
HelpMarker("Setting style.CellPadding to (0,0) or a custom value.");
static ImGuiTableFlags flags2 = ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg;
static ImVec2 cell_padding(0.0, 0.0);
local show_widget_frame_bg = true;
PushStyleCompact();
ImGui.CheckboxFlags("ImGuiTableFlags_Borders", flags2, ImGuiTableFlags_Borders);
ImGui.CheckboxFlags("ImGuiTableFlags_BordersH", flags2, ImGuiTableFlags_BordersH);
ImGui.CheckboxFlags("ImGuiTableFlags_BordersV", flags2, ImGuiTableFlags_BordersV);
ImGui.CheckboxFlags("ImGuiTableFlags_BordersInner", flags2, ImGuiTableFlags_BordersInner);
ImGui.CheckboxFlags("ImGuiTableFlags_BordersOuter", flags2, ImGuiTableFlags_BordersOuter);
ImGui.CheckboxFlags("ImGuiTableFlags_RowBg", flags2, ImGuiTableFlags_RowBg);
ImGui.CheckboxFlags("ImGuiTableFlags_Resizable", flags2, ImGuiTableFlags_Resizable);
ImGui.Checkbox("show_widget_frame_bg", show_widget_frame_bg);
ImGui.SliderFloat2("CellPadding", cell_padding.x, 0.0, 10.0, "%.0");
PopStyleCompact();
ImGui.PushStyleVar(ImGuiStyleVar_CellPadding, cell_padding);
if (ImGui.BeginTable("table_padding_2", 3, flags2))then
static char text_bufs[3 * 5][16]; -- Mini text storage for 3x5 cells
local init = true;
if (not show_widget_frame_bg)
ImGui.PushStyleColor(ImGuiCol_FrameBg, 0);
for (int cell = 0; cell < 3 * 5; cell++)then
ImGui.TableNextColumn();
if (init)
strcpy(text_bufs[cell], "edit me");
ImGui.SetNextItemWidth(-FLT_MIN);
ImGui.PushID(cell);
ImGui.InputText("----cell", text_bufs[cell], IM_ARRAYSIZE(text_bufs[cell]));
ImGui.PopID();
end
if (not show_widget_frame_bg)
ImGui.PopStyleColor();
init = false;
ImGui.EndTable();
end
ImGui.PopStyleVar();
ImGui.TreePop();
end
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Sizing policies"))then
static ImGuiTableFlags flags1 = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_RowBg | ImGuiTableFlags_ContextMenuInBody;
PushStyleCompact();
ImGui.CheckboxFlags("ImGuiTableFlags_Resizable", flags1, ImGuiTableFlags_Resizable);
ImGui.CheckboxFlags("ImGuiTableFlags_NoHostExtendX", flags1, ImGuiTableFlags_NoHostExtendX);
PopStyleCompact();
static ImGuiTableFlags sizing_policy_flags[4] = do ImGuiTableFlags_SizingFixedFit, ImGuiTableFlags_SizingFixedSame, ImGuiTableFlags_SizingStretchProp, ImGuiTableFlags_SizingStretchSame end;
for (int table_n = 0; table_n < 4; table_n++)then
ImGui.PushID(table_n);
ImGui.SetNextItemWidth(TEXT_BASE_WIDTH * 30);
EditTableSizingFlags(&sizing_policy_flags[table_n]);
-- To make it easier to understand the different sizing policy,
-- For each policy: we display one table where the columns have equal contents width, and one where the columns have different contents width.
if (ImGui.BeginTable("table1", 3, sizing_policy_flags[table_n] | flags1))then
for (int row = 0; row < 3; row++)then
ImGui.TableNextRow();
ImGui.TableNextColumn(); ImGui.Text("Oh dear");
ImGui.TableNextColumn(); ImGui.Text("Oh dear");
ImGui.TableNextColumn(); ImGui.Text("Oh dear");
end
ImGui.EndTable();
end
if (ImGui.BeginTable("table2", 3, sizing_policy_flags[table_n] | flags1))then
for (int row = 0; row < 3; row++)then
ImGui.TableNextRow();
ImGui.TableNextColumn(); ImGui.Text("AAAA");
ImGui.TableNextColumn(); ImGui.Text("BBBBBBBB");
ImGui.TableNextColumn(); ImGui.Text("CCCCCCCCCCCC");
end
ImGui.EndTable();
end
ImGui.PopID();
end
ImGui.Spacing();
ImGui.TextUnformatted("Advanced");
ImGui.SameLine();
HelpMarker("This section allows you to interact and see the effect of various sizing policies depending on whether Scroll is enabled and the contents of your columns.");
enum ContentsType do CT_ShowWidth, CT_ShortText, CT_LongText, CT_Button, CT_FillButton, CT_InputText end;
static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_Resizable;
static int contents_type = CT_ShowWidth;
static int column_count = 3;
PushStyleCompact();
ImGui.PushID("Advanced");
ImGui.PushItemWidth(TEXT_BASE_WIDTH * 30);
EditTableSizingFlags(&flags);
ImGui.Combo("Contents", contents_type, "Show width\0Short Text\0Long Text\0Button\0Fill Button\0InputText\0");
if (contents_type == CT_FillButton)then
ImGui.SameLine();
HelpMarker("Be mindful that using right-alignment (e.g. size.x = -FLT_MIN) creates a feedback loop where contents width can feed into auto-column width can feed into contents width.");
end
ImGui.DragInt("Columns", column_count, 0.1f, 1, 64, "%d", ImGuiSliderFlags_AlwaysClamp);
ImGui.CheckboxFlags("ImGuiTableFlags_Resizable", flags, ImGuiTableFlags_Resizable);
ImGui.CheckboxFlags("ImGuiTableFlags_PreciseWidths", flags, ImGuiTableFlags_PreciseWidths);
ImGui.SameLine(); HelpMarker("Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth.");
ImGui.CheckboxFlags("ImGuiTableFlags_ScrollX", flags, ImGuiTableFlags_ScrollX);
ImGui.CheckboxFlags("ImGuiTableFlags_ScrollY", flags, ImGuiTableFlags_ScrollY);
ImGui.CheckboxFlags("ImGuiTableFlags_NoClip", flags, ImGuiTableFlags_NoClip);
ImGui.PopItemWidth();
ImGui.PopID();
PopStyleCompact();
if (ImGui.BeginTable("table2", column_count, flags, ImVec2(0.0, TEXT_BASE_HEIGHT * 7)))then
for (int cell = 0; cell < 10 * column_count; cell++)then
ImGui.TableNextColumn();
int column = ImGui.TableGetColumnIndex();
int row = ImGui.TableGetRowIndex();
ImGui.PushID(cell);
char label[32];
static char text_buf[32] = "";
sprintf(label, "Hello %d,%d", column, row);
switch (contents_type)then
case CT_ShortText: ImGui.TextUnformatted(label); break;
case CT_LongText: ImGui.Text("Some %s text %d,%d\nOver two lines..", column == 0 ? "long" : "longeeer", column, row); break;
case CT_ShowWidth: ImGui.Text("W: %.1f", ImGui.GetContentRegionAvail().x); break;
case CT_Button: ImGui.Button(label); break;
case CT_FillButton: ImGui.Button(label, ImVec2(-FLT_MIN, 0.0)); break;
case CT_InputText: ImGui.SetNextItemWidth(-FLT_MIN); ImGui.InputText("----", text_buf, IM_ARRAYSIZE(text_buf)); break;
end
ImGui.PopID();
end
ImGui.EndTable();
end
ImGui.TreePop();
end
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Vertical scrolling, with clipping"))then
HelpMarker("Here we activate ScrollY, which will create a child window container to allow hosting scrollable contents.\n\nWe also demonstrate using ImGuiListClipper to virtualize the submission of many items.");
static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable;
PushStyleCompact();
ImGui.CheckboxFlags("ImGuiTableFlags_ScrollY", flags, ImGuiTableFlags_ScrollY);
PopStyleCompact();
-- When using ScrollX or ScrollY we need to specify a size for our table containernot
-- Otherwise by default the table will fit all available space, like a BeginChild() call.
ImVec2 outer_size = ImVec2(0.0, TEXT_BASE_HEIGHT * 8);
if (ImGui.BeginTable("table_scrolly", 3, flags, outer_size))then
ImGui.TableSetupScrollFreeze(0, 1); -- Make top row always visible
ImGui.TableSetupColumn("One", ImGuiTableColumnFlags_None);
ImGui.TableSetupColumn("Two", ImGuiTableColumnFlags_None);
ImGui.TableSetupColumn("Three", ImGuiTableColumnFlags_None);
ImGui.TableHeadersRow();
-- Demonstrate using clipper for large vertical lists
ImGuiListClipper clipper;
clipper.Begin(1000);
while (clipper.Step())then
for (int row = clipper.DisplayStart; row < clipper.DisplayEnd; row++)then
ImGui.TableNextRow();
for (int column = 0; column < 3; column++)then
ImGui.TableSetColumnIndex(column);
ImGui.Text("Hello %d,%d", column, row);
end
end
end
ImGui.EndTable();
end
ImGui.TreePop();
end
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Horizontal scrolling"))then
HelpMarker(
"When ScrollX is enabled, the default sizing policy becomes ImGuiTableFlags_SizingFixedFit, "
"as automatically stretching columns doesn't make much sense with horizontal scrolling.\n\n"
"Also note that as of the current version, you will almost always want to enable ScrollY along with ScrollX,"
"because the container window won't automatically extend vertically to fix contents (this may be improved in future versions).");
static ImGuiTableFlags flags = ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable;
static int freeze_cols = 1;
static int freeze_rows = 1;
PushStyleCompact();
ImGui.CheckboxFlags("ImGuiTableFlags_Resizable", flags, ImGuiTableFlags_Resizable);
ImGui.CheckboxFlags("ImGuiTableFlags_ScrollX", flags, ImGuiTableFlags_ScrollX);
ImGui.CheckboxFlags("ImGuiTableFlags_ScrollY", flags, ImGuiTableFlags_ScrollY);
ImGui.SetNextItemWidth(ImGui.GetFrameHeight());
ImGui.DragInt("freeze_cols", freeze_cols, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput);
ImGui.SetNextItemWidth(ImGui.GetFrameHeight());
ImGui.DragInt("freeze_rows", freeze_rows, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput);
PopStyleCompact();
-- When using ScrollX or ScrollY we need to specify a size for our table containernot
-- Otherwise by default the table will fit all available space, like a BeginChild() call.
ImVec2 outer_size = ImVec2(0.0, TEXT_BASE_HEIGHT * 8);
if (ImGui.BeginTable("table_scrollx", 7, flags, outer_size))then
ImGui.TableSetupScrollFreeze(freeze_cols, freeze_rows);
ImGui.TableSetupColumn("Line --", ImGuiTableColumnFlags_NoHide); -- Make the first column not hideable to match our use of TableSetupScrollFreeze()
ImGui.TableSetupColumn("One");
ImGui.TableSetupColumn("Two");
ImGui.TableSetupColumn("Three");
ImGui.TableSetupColumn("Four");
ImGui.TableSetupColumn("Five");
ImGui.TableSetupColumn("Six");
ImGui.TableHeadersRow();
for (int row = 0; row < 20; row++)then
ImGui.TableNextRow();
for (int column = 0; column < 7; column++)then
-- Both TableNextColumn() and TableSetColumnIndex() return true when a column is visible or performing width measurement.
-- Because here we know that:
-- - A) all our columns are contributing the same to row height
-- - B) column 0 is always visible,
-- We only always submit this one column and can skip others.
-- More advanced per-column clipping behaviors may benefit from polling the status flags via TableGetColumnFlags().
if (not ImGui.TableSetColumnIndex(column) and column > 0)
continue;
if (column == 0)
ImGui.Text("Line %d", row);
else
ImGui.Text("Hello world %d,%d", column, row);
end
end
ImGui.EndTable();
end
ImGui.Spacing();
ImGui.TextUnformatted("Stretch + ScrollX");
ImGui.SameLine();
HelpMarker(
"Showcase using Stretch columns + ScrollX together: "
"this is rather unusual and only makes sense when specifying an 'inner_width' for the tablenot \n"
"Without an explicit value, inner_width is == outer_size.x and therefore using Stretch columns + ScrollX together doesn't make sense.");
static ImGuiTableFlags flags2 = ImGuiTableFlags_SizingStretchSame | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_RowBg | ImGuiTableFlags_ContextMenuInBody;
static float inner_width = 1000.0;
PushStyleCompact();
ImGui.PushID("flags3");
ImGui.PushItemWidth(TEXT_BASE_WIDTH * 30);
ImGui.CheckboxFlags("ImGuiTableFlags_ScrollX", flags2, ImGuiTableFlags_ScrollX);
ImGui.DragFloat("inner_width", inner_width, 1.0, 0.0, FLT_MAX, "%.1f");
ImGui.PopItemWidth();
ImGui.PopID();
PopStyleCompact();
if (ImGui.BeginTable("table2", 7, flags2, outer_size, inner_width))then
for (int cell = 0; cell < 20 * 7; cell++)then
ImGui.TableNextColumn();
ImGui.Text("Hello world %d,%d", ImGui.TableGetColumnIndex(), ImGui.TableGetRowIndex());
end
ImGui.EndTable();
end
ImGui.TreePop();
end
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Columns flags"))then
-- Create a first table just to show all the options/flags we want to make visible in our examplenot
const int column_count = 3;
const char* column_names[column_count] = do "One", "Two", "Three" end;
static ImGuiTableColumnFlags column_flags[column_count] = do ImGuiTableColumnFlags_DefaultSort, ImGuiTableColumnFlags_None, ImGuiTableColumnFlags_DefaultHide end;
static ImGuiTableColumnFlags column_flags_out[column_count] = do 0, 0, 0 end; -- Output from TableGetColumnFlags()
if (ImGui.BeginTable("table_columns_flags_checkboxes", column_count, ImGuiTableFlags_None))then
PushStyleCompact();
for (int column = 0; column < column_count; column++)then
ImGui.TableNextColumn();
ImGui.PushID(column);
ImGui.AlignTextToFramePadding(); -- FIXME-TABLE: Workaround for wrong text baseline propagation
ImGui.Text("'%s'", column_names[column]);
ImGui.Spacing();
ImGui.Text("Input flags:");
EditTableColumnsFlags(&column_flags[column]);
ImGui.Spacing();
ImGui.Text("Output flags:");
ShowTableColumnsStatusFlags(column_flags_out[column]);
ImGui.PopID();
end
PopStyleCompact();
ImGui.EndTable();
end
-- Create the real table we care about for the examplenot
-- We use a scrolling table to be able to showcase the difference between the _IsEnabled and _IsVisible flags above, otherwise in
-- a non-scrolling table columns are always visible (unless using ImGuiTableFlags_NoKeepColumnsVisible + resizing the parent window down)
const ImGuiTableFlags flags
= ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY
| ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV
| ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Sortable;
ImVec2 outer_size = ImVec2(0.0, TEXT_BASE_HEIGHT * 9);
if (ImGui.BeginTable("table_columns_flags", column_count, flags, outer_size))then
for (int column = 0; column < column_count; column++)
ImGui.TableSetupColumn(column_names[column], column_flags[column]);
ImGui.TableHeadersRow();
for (int column = 0; column < column_count; column++)
column_flags_out[column] = ImGui.TableGetColumnFlags(column);
float indent_step = (float)((int)TEXT_BASE_WIDTH / 2);
for (int row = 0; row < 8; row++)then
ImGui.Indent(indent_step); -- Add some indentation to demonstrate usage of per-column IndentEnable/IndentDisable flags.
ImGui.TableNextRow();
for (int column = 0; column < column_count; column++)then
ImGui.TableSetColumnIndex(column);
ImGui.Text("%s %s", (column == 0) ? "Indented" : "Hello", ImGui.TableGetColumnName(column));
end
end
ImGui.Unindent(indent_step * 8.0);
ImGui.EndTable();
end
ImGui.TreePop();
end
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Columns widths"))then
HelpMarker("Using TableSetupColumn() to setup default width.");
static ImGuiTableFlags flags1 = ImGuiTableFlags_Borders | ImGuiTableFlags_NoBordersInBodyUntilResize;
PushStyleCompact();
ImGui.CheckboxFlags("ImGuiTableFlags_Resizable", flags1, ImGuiTableFlags_Resizable);
ImGui.CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", flags1, ImGuiTableFlags_NoBordersInBodyUntilResize);
PopStyleCompact();
if (ImGui.BeginTable("table1", 3, flags1))then
-- We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed.
ImGui.TableSetupColumn("one", ImGuiTableColumnFlags_WidthFixed, 100.0); -- Default to 100.0
ImGui.TableSetupColumn("two", ImGuiTableColumnFlags_WidthFixed, 200.0); -- Default to 200.0
ImGui.TableSetupColumn("three", ImGuiTableColumnFlags_WidthFixed); -- Default to auto
ImGui.TableHeadersRow();
for (int row = 0; row < 4; row++)then
ImGui.TableNextRow();
for (int column = 0; column < 3; column++)then
ImGui.TableSetColumnIndex(column);
if (row == 0)
ImGui.Text("(w: %5.1f)", ImGui.GetContentRegionAvail().x);
else
ImGui.Text("Hello %d,%d", column, row);
end
end
ImGui.EndTable();
end
HelpMarker("Using TableSetupColumn() to setup explicit width.\n\nUnless _NoKeepColumnsVisible is set, fixed columns with set width may still be shrunk down if there's not enough space in the host.");
static ImGuiTableFlags flags2 = ImGuiTableFlags_None;
PushStyleCompact();
ImGui.CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", flags2, ImGuiTableFlags_NoKeepColumnsVisible);
ImGui.CheckboxFlags("ImGuiTableFlags_BordersInnerV", flags2, ImGuiTableFlags_BordersInnerV);
ImGui.CheckboxFlags("ImGuiTableFlags_BordersOuterV", flags2, ImGuiTableFlags_BordersOuterV);
PopStyleCompact();
if (ImGui.BeginTable("table2", 4, flags2))then
-- We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed.
ImGui.TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 100.0);
ImGui.TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 15.0);
ImGui.TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 30.0);
ImGui.TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 15.0);
for (int row = 0; row < 5; row++)then
ImGui.TableNextRow();
for (int column = 0; column < 4; column++)then
ImGui.TableSetColumnIndex(column);
if (row == 0)
ImGui.Text("(w: %5.1f)", ImGui.GetContentRegionAvail().x);
else
ImGui.Text("Hello %d,%d", column, row);
end
end
ImGui.EndTable();
end
ImGui.TreePop();
end
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Nested tables"))then
HelpMarker("This demonstrate embedding a table into another table cell.");
if (ImGui.BeginTable("table_nested1", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable))then
ImGui.TableSetupColumn("A0");
ImGui.TableSetupColumn("A1");
ImGui.TableHeadersRow();
ImGui.TableNextColumn();
ImGui.Text("A0 Row 0");then
float rows_height = TEXT_BASE_HEIGHT * 2;
if (ImGui.BeginTable("table_nested2", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable))then
ImGui.TableSetupColumn("B0");
ImGui.TableSetupColumn("B1");
ImGui.TableHeadersRow();
ImGui.TableNextRow(ImGuiTableRowFlags_None, rows_height);
ImGui.TableNextColumn();
ImGui.Text("B0 Row 0");
ImGui.TableNextColumn();
ImGui.Text("B1 Row 0");
ImGui.TableNextRow(ImGuiTableRowFlags_None, rows_height);
ImGui.TableNextColumn();
ImGui.Text("B0 Row 1");
ImGui.TableNextColumn();
ImGui.Text("B1 Row 1");
ImGui.EndTable();
end
end
ImGui.TableNextColumn(); ImGui.Text("A1 Row 0");
ImGui.TableNextColumn(); ImGui.Text("A0 Row 1");
ImGui.TableNextColumn(); ImGui.Text("A1 Row 1");
ImGui.EndTable();
end
ImGui.TreePop();
end
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Row height"))then
HelpMarker("You can pass a 'min_row_height' to TableNextRow().\n\nRows are padded with 'style.CellPadding.y' on top and bottom, so effectively the minimum row height will always be >= 'style.CellPadding.y * 2.0'.\n\nWe cannot honor a _maximum_ row height as that would requires a unique clipping rectangle per row.");
if (ImGui.BeginTable("table_row_height", 1, ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersInnerV))then
for (int row = 0; row < 10; row++)then
float min_row_height = (float)(int)(TEXT_BASE_HEIGHT * 0..0 * row);
ImGui.TableNextRow(ImGuiTableRowFlags_None, min_row_height);
ImGui.TableNextColumn();
ImGui.Text("min_row_height = %.2f", min_row_height);
end
ImGui.EndTable();
end
ImGui.TreePop();
end
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Outer size"))then
-- Showcasing use of ImGuiTableFlags_NoHostExtendX and ImGuiTableFlags_NoHostExtendY
-- Important to that note how the two flags have slightly different behaviorsnot
ImGui.Text("Using NoHostExtendX and NoHostExtendY:");
PushStyleCompact();
static ImGuiTableFlags flags = ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_ContextMenuInBody | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_NoHostExtendX;
ImGui.CheckboxFlags("ImGuiTableFlags_NoHostExtendX", flags, ImGuiTableFlags_NoHostExtendX);
ImGui.SameLine(); HelpMarker("Make outer width auto-fit to columns, overriding outer_size.x value.\n\nOnly available when ScrollX/ScrollY are disabled and Stretch columns are not used.");
ImGui.CheckboxFlags("ImGuiTableFlags_NoHostExtendY", flags, ImGuiTableFlags_NoHostExtendY);
ImGui.SameLine(); HelpMarker("Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit).\n\nOnly available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible.");
PopStyleCompact();
ImVec2 outer_size = ImVec2(0.0, TEXT_BASE_HEIGHT * 5.5f);
if (ImGui.BeginTable("table1", 3, flags, outer_size))then
for (int row = 0; row < 10; row++)then
ImGui.TableNextRow();
for (int column = 0; column < 3; column++)then
ImGui.TableNextColumn();
ImGui.Text("Cell %d,%d", column, row);
end
end
ImGui.EndTable();
end
ImGui.SameLine();
ImGui.Text("Hellonot ");
ImGui.Spacing();
ImGui.Text("Using explicit size:");
if (ImGui.BeginTable("table2", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg, ImVec2(TEXT_BASE_WIDTH * 30, 0.0)))then
for (int row = 0; row < 5; row++)then
ImGui.TableNextRow();
for (int column = 0; column < 3; column++)then
ImGui.TableNextColumn();
ImGui.Text("Cell %d,%d", column, row);
end
end
ImGui.EndTable();
end
ImGui.SameLine();
if (ImGui.BeginTable("table3", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg, ImVec2(TEXT_BASE_WIDTH * 30, 0.0)))then
for (int row = 0; row < 3; row++)then
ImGui.TableNextRow(0, TEXT_BASE_HEIGHT * 1.5f);
for (int column = 0; column < 3; column++)then
ImGui.TableNextColumn();
ImGui.Text("Cell %d,%d", column, row);
end
end
ImGui.EndTable();
end
ImGui.TreePop();
end
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Background color"))then
static ImGuiTableFlags flags = ImGuiTableFlags_RowBg;
static int row_bg_type = 1;
static int row_bg_target = 1;
static int cell_bg_type = 1;
PushStyleCompact();
ImGui.CheckboxFlags("ImGuiTableFlags_Borders", flags, ImGuiTableFlags_Borders);
ImGui.CheckboxFlags("ImGuiTableFlags_RowBg", flags, ImGuiTableFlags_RowBg);
ImGui.SameLine(); HelpMarker("ImGuiTableFlags_RowBg automatically sets RowBg0 to alternative colors pulled from the Style.");
ImGui.Combo("row bg type", (int*)&row_bg_type, "None\0Red\0Gradient\0");
ImGui.Combo("row bg target", (int*)&row_bg_target, "RowBg0\0RowBg1\0"); ImGui.SameLine(); HelpMarker("Target RowBg0 to override the alternating odd/even colors,\nTarget RowBg1 to blend with them.");
ImGui.Combo("cell bg type", (int*)&cell_bg_type, "None\0Blue\0"); ImGui.SameLine(); HelpMarker("We are colorizing cells to B1->C2 here.");
IM_ASSERT(row_bg_type >= 0 and row_bg_type <= 2);
IM_ASSERT(row_bg_target >= 0 and row_bg_target <= 1);
IM_ASSERT(cell_bg_type >= 0 and cell_bg_type <= 1);
PopStyleCompact();
if (ImGui.BeginTable("table1", 5, flags))then
for (int row = 0; row < 6; row++)then
ImGui.TableNextRow();
-- Demonstrate setting a row background color with 'ImGui.TableSetBgColor(ImGuiTableBgTarget_RowBgX, ...)'
-- We use a transparent color so we can see the one behind in case our target is RowBg1 and RowBg0 was already targeted by the ImGuiTableFlags_RowBg flag.
if (row_bg_type ~= 0)then
ImU32 row_bg_color = ImGui.GetColorU32(row_bg_type == 1 ? ImVec4(0.7f, 0.3f, 0.3f, 0.65f) : ImVec4(0.2f + row * 0.1f, 0.2f, 0.2f, 0.65f)); -- Flat or Gradient?
ImGui.TableSetBgColor(ImGuiTableBgTarget_RowBg0 + row_bg_target, row_bg_color);
end
-- Fill cells
for (int column = 0; column < 5; column++)then
ImGui.TableSetColumnIndex(column);
ImGui.Text("%c%c", 'A' + row, '0' + column);
-- Change background of Cells B1->C2
-- Demonstrate setting a cell background color with 'ImGui.TableSetBgColor(ImGuiTableBgTarget_CellBg, ...)'
-- (the CellBg color will be blended over the RowBg and ColumnBg colors)
-- We can also pass a column number as a third parameter to TableSetBgColor() and do this outside the column loop.
if (row >= 1 and row <= 2 and column >= 1 and column <= 2 and cell_bg_type == 1)then
ImU32 cell_bg_color = ImGui.GetColorU32(ImVec4(0.3f, 0.3f, 0.7f, 0.65f));
ImGui.TableSetBgColor(ImGuiTableBgTarget_CellBg, cell_bg_color);
end
end
end
ImGui.EndTable();
end
ImGui.TreePop();
end
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Tree view"))then
static ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoBordersInBody;
if (ImGui.BeginTable("3ways", 3, flags))then
-- The first column will use the default _WidthStretch when ScrollX is Off and _WidthFixed when ScrollX is On
ImGui.TableSetupColumn("Name", ImGuiTableColumnFlags_NoHide);
ImGui.TableSetupColumn("Size", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 12.0);
ImGui.TableSetupColumn("Type", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 18.0);
ImGui.TableHeadersRow();
-- Simple storage to output a dummy file-system.
struct MyTreeNodethen
const char* Name;
const char* Type;
int Size;
int ChildIdx;
int ChildCount;
function DisplayNode(const MyTreeNode* node, const MyTreeNode* all_nodes)then
ImGui.TableNextRow();
ImGui.TableNextColumn();
const bool is_folder = (node->ChildCount > 0);
if (is_folder)then
bool open = ImGui.TreeNodeEx(node->Name, ImGuiTreeNodeFlags_SpanFullWidth);
ImGui.TableNextColumn();
ImGui.TextDisabled("--");
ImGui.TableNextColumn();
ImGui.TextUnformatted(node->Type);
if (open)then
for (int child_n = 0; child_n < node->ChildCount; child_n++)
DisplayNode(&all_nodes[node->ChildIdx + child_n], all_nodes);
ImGui.TreePop();
end
end
elsethen
ImGui.TreeNodeEx(node->Name, ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_SpanFullWidth);
ImGui.TableNextColumn();
ImGui.Text("%d", node->Size);
ImGui.TableNextColumn();
ImGui.TextUnformatted(node->Type);
end
end
end;
static const MyTreeNode nodes[] =thenthen "Root", "Folder", -1, 1, 3 end, -- 0then "Music", "Folder", -1, 4, 2 end, -- 1then "Textures", "Folder", -1, 6, 3 end, -- 2then "desktop.ini", "System file", 1024, -1,-1 end, -- 3then "File1_a.wav", "Audio file", 123000, -1,-1 end, -- 4then "File1_b.wav", "Audio file", 456000, -1,-1 end, -- 5then "Image001.png", "Image file", 203128, -1,-1 end, -- 6then "Copy of Image001.png", "Image file", 203256, -1,-1 end, -- 7then "Copy of Image001 (Final2).png","Image file", 203512, -1,-1 end, -- 8
end;
MyTreeNode.DisplayNode(&nodes[0], nodes);
ImGui.EndTable();
end
ImGui.TreePop();
end
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Item width"))then
HelpMarker(
"Showcase using PushItemWidth() and how it is preserved on a per-column basis.\n\n"
"Note that on auto-resizing non-resizable fixed columns, querying the content width for e.g. right-alignment doesn't make sense.");
if (ImGui.BeginTable("table_item_width", 3, ImGuiTableFlags_Borders))then
ImGui.TableSetupColumn("small");
ImGui.TableSetupColumn("half");
ImGui.TableSetupColumn("right-align");
ImGui.TableHeadersRow();
for (int row = 0; row < 3; row++)then
ImGui.TableNextRow();
if (row == 0)then
-- Setup ItemWidth once (instead of setting up every time, which is also possible but less efficient)
ImGui.TableSetColumnIndex(0);
ImGui.PushItemWidth(TEXT_BASE_WIDTH * 3.0); -- Small
ImGui.TableSetColumnIndex(1);
ImGui.PushItemWidth(-ImGui.GetContentRegionAvail().x * 0.5f);
ImGui.TableSetColumnIndex(2);
ImGui.PushItemWidth(-FLT_MIN); -- Right-aligned
end
-- Draw our contents
static float dummy_f = 0.0;
ImGui.PushID(row);
ImGui.TableSetColumnIndex(0);
ImGui.SliderFloat("float0", dummy_f, 0.0, 1.0);
ImGui.TableSetColumnIndex(1);
ImGui.SliderFloat("float1", dummy_f, 0.0, 1.0);
ImGui.TableSetColumnIndex(2);
ImGui.SliderFloat("float2", dummy_f, 0.0, 1.0);
ImGui.PopID();
end
ImGui.EndTable();
end
ImGui.TreePop();
end
-- Demonstrate using TableHeader() calls instead of TableHeadersRow()
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Custom headers"))then
const int COLUMNS_COUNT = 3;
if (ImGui.BeginTable("table_custom_headers", COLUMNS_COUNT, ImGuiTableFlags_Borders | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable))then
ImGui.TableSetupColumn("Apricot");
ImGui.TableSetupColumn("Banana");
ImGui.TableSetupColumn("Cherry");
-- Dummy entire-column selection storage
-- FIXME: It would be nice to actually demonstrate full-featured selection using those checkbox.
local column_selected[3] = do end;
-- Instead of calling TableHeadersRow() we'll submit custom headers ourselves
ImGui.TableNextRow(ImGuiTableRowFlags_Headers);
for (int column = 0; column < COLUMNS_COUNT; column++)then
ImGui.TableSetColumnIndex(column);
const char* column_name = ImGui.TableGetColumnName(column); -- Retrieve name passed to TableSetupColumn()
ImGui.PushID(column);
ImGui.PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui.Checkbox("----checkall", column_selected[column]);
ImGui.PopStyleVar();
ImGui.SameLine(0.0, ImGui.GetStyle().ItemInnerSpacing.x);
ImGui.TableHeader(column_name);
ImGui.PopID();
end
for (int row = 0; row < 5; row++)then
ImGui.TableNextRow();
for (int column = 0; column < 3; column++)then
char buf[32];
sprintf(buf, "Cell %d,%d", column, row);
ImGui.TableSetColumnIndex(column);
ImGui.Selectable(buf, column_selected[column]);
end
end
ImGui.EndTable();
end
ImGui.TreePop();
end
-- Demonstrate creating custom context menus inside columns, while playing it nice with context menus provided by TableHeadersRow()/TableHeader()
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Context menus"))then
HelpMarker("By default, right-clicking over a TableHeadersRow()/TableHeader() line will open the default context-menu.\nUsing ImGuiTableFlags_ContextMenuInBody we also allow right-clicking over columns body.");
static ImGuiTableFlags flags1 = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders | ImGuiTableFlags_ContextMenuInBody;
PushStyleCompact();
ImGui.CheckboxFlags("ImGuiTableFlags_ContextMenuInBody", flags1, ImGuiTableFlags_ContextMenuInBody);
PopStyleCompact();
-- Context Menus: first example
-- [1.1] Right-click on the TableHeadersRow() line to open the default table context menu.
-- [1.2] Right-click in columns also open the default table context menu (if ImGuiTableFlags_ContextMenuInBody is set)
const int COLUMNS_COUNT = 3;
if (ImGui.BeginTable("table_context_menu", COLUMNS_COUNT, flags1))then
ImGui.TableSetupColumn("One");
ImGui.TableSetupColumn("Two");
ImGui.TableSetupColumn("Three");
-- [1.1]] Right-click on the TableHeadersRow() line to open the default table context menu.
ImGui.TableHeadersRow();
-- Submit dummy contents
for (int row = 0; row < 4; row++)then
ImGui.TableNextRow();
for (int column = 0; column < COLUMNS_COUNT; column++)then
ImGui.TableSetColumnIndex(column);
ImGui.Text("Cell %d,%d", column, row);
end
end
ImGui.EndTable();
end
-- Context Menus: second example
-- [2.1] Right-click on the TableHeadersRow() line to open the default table context menu.
-- [2.2] Right-click on the ".." to open a custom popup
-- [2.3] Right-click in columns to open another custom popup
HelpMarker("Demonstrate mixing table context menu (over header), item context button (over button) and custom per-colum context menu (over column body).");
ImGuiTableFlags flags2 = ImGuiTableFlags_Resizable | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders;
if (ImGui.BeginTable("table_context_menu_2", COLUMNS_COUNT, flags2))then
ImGui.TableSetupColumn("One");
ImGui.TableSetupColumn("Two");
ImGui.TableSetupColumn("Three");
-- [2.1] Right-click on the TableHeadersRow() line to open the default table context menu.
ImGui.TableHeadersRow();
for (int row = 0; row < 4; row++)then
ImGui.TableNextRow();
for (int column = 0; column < COLUMNS_COUNT; column++)then
-- Submit dummy contents
ImGui.TableSetColumnIndex(column);
ImGui.Text("Cell %d,%d", column, row);
ImGui.SameLine();
-- [2.2] Right-click on the ".." to open a custom popup
ImGui.PushID(row * COLUMNS_COUNT + column);
ImGui.SmallButton("..");
if (ImGui.BeginPopupContextItem())then
ImGui.Text("This is the popup for Button(\"..\") in Cell %d,%d", column, row);
if (ImGui.Button("Close"))
ImGui.CloseCurrentPopup();
ImGui.EndPopup();
end
ImGui.PopID();
end
end
-- [2.3] Right-click anywhere in columns to open another custom popup
-- (instead of testing for not IsAnyItemHovered() we could also call OpenPopup() with ImGuiPopupFlags_NoOpenOverExistingPopup
-- to manage popup priority as the popups triggers, here "are we hovering a column" are overlapping)
int hovered_column = -1;
for (int column = 0; column < COLUMNS_COUNT + 1; column++)then
ImGui.PushID(column);
if (ImGui.TableGetColumnFlags(column) & ImGuiTableColumnFlags_IsHovered)
hovered_column = column;
if (hovered_column == column and not ImGui.IsAnyItemHovered() and ImGui.IsMouseReleased(1))
ImGui.OpenPopup("MyPopup");
if (ImGui.BeginPopup("MyPopup"))then
if (column == COLUMNS_COUNT)
ImGui.Text("This is a custom popup for unused space after the last column.");
else
ImGui.Text("This is a custom popup for Column %d", column);
if (ImGui.Button("Close"))
ImGui.CloseCurrentPopup();
ImGui.EndPopup();
end
ImGui.PopID();
end
ImGui.EndTable();
ImGui.Text("Hovered column: %d", hovered_column);
end
ImGui.TreePop();
end
-- Demonstrate creating multiple tables with the same ID
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Synced instances"))then
HelpMarker("Multiple tables with the same identifier will share their settings, width, visibility, order etc.");
for (int n = 0; n < 3; n++)then
char buf[32];
sprintf(buf, "Synced Table %d", n);
bool open = ImGui.CollapsingHeader(buf, ImGuiTreeNodeFlags_DefaultOpen);
if (open and ImGui.BeginTable("Table", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_NoSavedSettings))then
ImGui.TableSetupColumn("One");
ImGui.TableSetupColumn("Two");
ImGui.TableSetupColumn("Three");
ImGui.TableHeadersRow();
for (int cell = 0; cell < 9; cell++)then
ImGui.TableNextColumn();
ImGui.Text("this cell %d", cell);
end
ImGui.EndTable();
end
end
ImGui.TreePop();
end
-- Demonstrate using Sorting facilities
-- This is a simplified version of the "Advanced" example, where we mostly focus on the code necessary to handle sorting.
-- Note that the "Advanced" example also showcase manually triggering a sort (e.g. if item quantities have been modified)
static const char* template_items_names[] =then
"Banana", "Apple", "Cherry", "Watermelon", "Grapefruit", "Strawberry", "Mango",
"Kiwi", "Orange", "Pineapple", "Blueberry", "Plum", "Coconut", "Pear", "Apricot"
end;
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Sorting"))then
-- Create item list
static ImVector<MyItem> items;
if (items.Size == 0)then
items.resize(50, MyItem());
for (int n = 0; n < items.Size; n++)then
const int template_n = n % IM_ARRAYSIZE(template_items_names);
MyItem& item = items[n];
item.ID = n;
item.Name = template_items_names[template_n];
item.Quantity = (n * n - n) % 20; -- Assign default quantities
end
end
-- Options
static ImGuiTableFlags flags =
ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti
| ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_NoBordersInBody
| ImGuiTableFlags_ScrollY;
PushStyleCompact();
ImGui.CheckboxFlags("ImGuiTableFlags_SortMulti", flags, ImGuiTableFlags_SortMulti);
ImGui.SameLine(); HelpMarker("When sorting is enabled: hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1).");
ImGui.CheckboxFlags("ImGuiTableFlags_SortTristate", flags, ImGuiTableFlags_SortTristate);
ImGui.SameLine(); HelpMarker("When sorting is enabled: allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0).");
PopStyleCompact();
if (ImGui.BeginTable("table_sorting", 4, flags, ImVec2(0.0, TEXT_BASE_HEIGHT * 15), 0.0))then
-- Declare columns
-- We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications.
-- This is so our sort function can identify a column given our own identifier. We could also identify them based on their indexnot
-- Demonstrate using a mixture of flags among available sort-related flags:
-- - ImGuiTableColumnFlags_DefaultSort
-- - ImGuiTableColumnFlags_NoSort / ImGuiTableColumnFlags_NoSortAscending / ImGuiTableColumnFlags_NoSortDescending
-- - ImGuiTableColumnFlags_PreferSortAscending / ImGuiTableColumnFlags_PreferSortDescending
ImGui.TableSetupColumn("ID", ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_WidthFixed, 0.0, MyItemColumnID_ID);
ImGui.TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed, 0.0, MyItemColumnID_Name);
ImGui.TableSetupColumn("Action", ImGuiTableColumnFlags_NoSort | ImGuiTableColumnFlags_WidthFixed, 0.0, MyItemColumnID_Action);
ImGui.TableSetupColumn("Quantity", ImGuiTableColumnFlags_PreferSortDescending | ImGuiTableColumnFlags_WidthStretch, 0.0, MyItemColumnID_Quantity);
ImGui.TableSetupScrollFreeze(0, 1); -- Make row always visible
ImGui.TableHeadersRow();
-- Sort our data if sort specs have been changednot
if (ImGuiTableSortSpecs* sorts_specs = ImGui.TableGetSortSpecs())
if (sorts_specs->SpecsDirty)then
MyItem.s_current_sort_specs = sorts_specs; -- Store in variable accessible by the sort function.
if (items.Size > 1)
qsort(&items[0], (size_t)items.Size, sizeof(items[0]), MyItem.CompareWithSortSpecs);
MyItem.s_current_sort_specs = NULL;
sorts_specs->SpecsDirty = false;
end
-- Demonstrate using clipper for large vertical lists
ImGuiListClipper clipper;
clipper.Begin(items.Size);
while (clipper.Step())
for (int row_n = clipper.DisplayStart; row_n < clipper.DisplayEnd; row_n++)then
-- Display a data item
MyItem* item = &items[row_n];
ImGui.PushID(item->ID);
ImGui.TableNextRow();
ImGui.TableNextColumn();
ImGui.Text("%04d", item->ID);
ImGui.TableNextColumn();
ImGui.TextUnformatted(item->Name);
ImGui.TableNextColumn();
ImGui.SmallButton("None");
ImGui.TableNextColumn();
ImGui.Text("%d", item->Quantity);
ImGui.PopID();
end
ImGui.EndTable();
end
ImGui.TreePop();
end
-- In this example we'll expose most table flags and settings.
-- For specific flags and settings refer to the corresponding section for more detailed explanation.
-- This section is mostly useful to experiment with combining certain flags or settings with each others.
--ImGui.SetNextItemOpen(true, ImGuiCond_Once); -- [DEBUG]
if (open_action ~= -1)
ImGui.SetNextItemOpen(open_action ~= 0);
if (ImGui.TreeNode("Advanced"))then
static ImGuiTableFlags flags =
ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable
| ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti
| ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_NoBordersInBody
| ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY
| ImGuiTableFlags_SizingFixedFit;
enum ContentsType do CT_Text, CT_Button, CT_SmallButton, CT_FillButton, CT_Selectable, CT_SelectableSpanRow end;
static int contents_type = CT_SelectableSpanRow;
const char* contents_type_names[] = do "Text", "Button", "SmallButton", "FillButton", "Selectable", "Selectable (span row)" end;
static int freeze_cols = 1;
static int freeze_rows = 1;
static int items_count = IM_ARRAYSIZE(template_items_names) * 2;
static ImVec2 outer_size_value = ImVec2(0.0, TEXT_BASE_HEIGHT * 12);
static float row_min_height = 0.0; -- Auto
static float inner_width_with_scroll = 0.0; -- Auto-extend
local outer_size_enabled = true;
local show_headers = true;
local show_wrapped_text = false;
--static ImGuiTextFilter filter;
--ImGui.SetNextItemOpen(true, ImGuiCond_Once); -- FIXME-TABLE: Enabling this results in initial clipped first pass on table which tend to affects column sizing
if (ImGui.TreeNode("Options"))then
-- Make the UI compact because there are so many fields
PushStyleCompact();
ImGui.PushItemWidth(TEXT_BASE_WIDTH * 28.0);
if (ImGui.TreeNodeEx("Features:", ImGuiTreeNodeFlags_DefaultOpen))then
ImGui.CheckboxFlags("ImGuiTableFlags_Resizable", flags, ImGuiTableFlags_Resizable);
ImGui.CheckboxFlags("ImGuiTableFlags_Reorderable", flags, ImGuiTableFlags_Reorderable);
ImGui.CheckboxFlags("ImGuiTableFlags_Hideable", flags, ImGuiTableFlags_Hideable);
ImGui.CheckboxFlags("ImGuiTableFlags_Sortable", flags, ImGuiTableFlags_Sortable);
ImGui.CheckboxFlags("ImGuiTableFlags_NoSavedSettings", flags, ImGuiTableFlags_NoSavedSettings);
ImGui.CheckboxFlags("ImGuiTableFlags_ContextMenuInBody", flags, ImGuiTableFlags_ContextMenuInBody);
ImGui.TreePop();
end
if (ImGui.TreeNodeEx("Decorations:", ImGuiTreeNodeFlags_DefaultOpen))then
ImGui.CheckboxFlags("ImGuiTableFlags_RowBg", flags, ImGuiTableFlags_RowBg);
ImGui.CheckboxFlags("ImGuiTableFlags_BordersV", flags, ImGuiTableFlags_BordersV);
ImGui.CheckboxFlags("ImGuiTableFlags_BordersOuterV", flags, ImGuiTableFlags_BordersOuterV);
ImGui.CheckboxFlags("ImGuiTableFlags_BordersInnerV", flags, ImGuiTableFlags_BordersInnerV);
ImGui.CheckboxFlags("ImGuiTableFlags_BordersH", flags, ImGuiTableFlags_BordersH);
ImGui.CheckboxFlags("ImGuiTableFlags_BordersOuterH", flags, ImGuiTableFlags_BordersOuterH);
ImGui.CheckboxFlags("ImGuiTableFlags_BordersInnerH", flags, ImGuiTableFlags_BordersInnerH);
ImGui.CheckboxFlags("ImGuiTableFlags_NoBordersInBody", flags, ImGuiTableFlags_NoBordersInBody); ImGui.SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appears in Headers");
ImGui.CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", flags, ImGuiTableFlags_NoBordersInBodyUntilResize); ImGui.SameLine(); HelpMarker("Disable vertical borders in columns Body until hovered for resize (borders will always appears in Headers)");
ImGui.TreePop();
end
if (ImGui.TreeNodeEx("Sizing:", ImGuiTreeNodeFlags_DefaultOpen))then
EditTableSizingFlags(&flags);
ImGui.SameLine(); HelpMarker("In the Advanced demo we override the policy of each column so those table-wide settings have less effect that typical.");
ImGui.CheckboxFlags("ImGuiTableFlags_NoHostExtendX", flags, ImGuiTableFlags_NoHostExtendX);
ImGui.SameLine(); HelpMarker("Make outer width auto-fit to columns, overriding outer_size.x value.\n\nOnly available when ScrollX/ScrollY are disabled and Stretch columns are not used.");
ImGui.CheckboxFlags("ImGuiTableFlags_NoHostExtendY", flags, ImGuiTableFlags_NoHostExtendY);
ImGui.SameLine(); HelpMarker("Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit).\n\nOnly available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible.");
ImGui.CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", flags, ImGuiTableFlags_NoKeepColumnsVisible);
ImGui.SameLine(); HelpMarker("Only available if ScrollX is disabled.");
ImGui.CheckboxFlags("ImGuiTableFlags_PreciseWidths", flags, ImGuiTableFlags_PreciseWidths);
ImGui.SameLine(); HelpMarker("Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth.");
ImGui.CheckboxFlags("ImGuiTableFlags_NoClip", flags, ImGuiTableFlags_NoClip);
ImGui.SameLine(); HelpMarker("Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with ScrollFreeze options.");
ImGui.TreePop();
end
if (ImGui.TreeNodeEx("Padding:", ImGuiTreeNodeFlags_DefaultOpen))then
ImGui.CheckboxFlags("ImGuiTableFlags_PadOuterX", flags, ImGuiTableFlags_PadOuterX);
ImGui.CheckboxFlags("ImGuiTableFlags_NoPadOuterX", flags, ImGuiTableFlags_NoPadOuterX);
ImGui.CheckboxFlags("ImGuiTableFlags_NoPadInnerX", flags, ImGuiTableFlags_NoPadInnerX);
ImGui.TreePop();
end
if (ImGui.TreeNodeEx("Scrolling:", ImGuiTreeNodeFlags_DefaultOpen))then
ImGui.CheckboxFlags("ImGuiTableFlags_ScrollX", flags, ImGuiTableFlags_ScrollX);
ImGui.SameLine();
ImGui.SetNextItemWidth(ImGui.GetFrameHeight());
ImGui.DragInt("freeze_cols", freeze_cols, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput);
ImGui.CheckboxFlags("ImGuiTableFlags_ScrollY", flags, ImGuiTableFlags_ScrollY);
ImGui.SameLine();
ImGui.SetNextItemWidth(ImGui.GetFrameHeight());
ImGui.DragInt("freeze_rows", freeze_rows, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput);
ImGui.TreePop();
end
if (ImGui.TreeNodeEx("Sorting:", ImGuiTreeNodeFlags_DefaultOpen))then
ImGui.CheckboxFlags("ImGuiTableFlags_SortMulti", flags, ImGuiTableFlags_SortMulti);
ImGui.SameLine(); HelpMarker("When sorting is enabled: hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1).");
ImGui.CheckboxFlags("ImGuiTableFlags_SortTristate", flags, ImGuiTableFlags_SortTristate);
ImGui.SameLine(); HelpMarker("When sorting is enabled: allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0).");
ImGui.TreePop();
end
if (ImGui.TreeNodeEx("Other:", ImGuiTreeNodeFlags_DefaultOpen))then
ImGui.Checkbox("show_headers", show_headers);
ImGui.Checkbox("show_wrapped_text", show_wrapped_text);
ImGui.DragFloat2("----OuterSize", outer_size_value.x);
ImGui.SameLine(0.0, ImGui.GetStyle().ItemInnerSpacing.x);
ImGui.Checkbox("outer_size", outer_size_enabled);
ImGui.SameLine();
HelpMarker("If scrolling is disabled (ScrollX and ScrollY not set):\n"
"- The table is output directly in the parent window.\n"
"- OuterSize.x < 0.0 will right-align the table.\n"
"- OuterSize.x = 0.0 will narrow fit the table unless there are any Stretch column.\n"
"- OuterSize.y then becomes the minimum size for the table, which will extend vertically if there are more rows (unless NoHostExtendY is set).");
-- From a user point of view we will tend to use 'inner_width' differently depending on whether our table is embedding scrolling.
-- To facilitate toying with this demo we will actually pass 0.0 to the BeginTable() when ScrollX is disabled.
ImGui.DragFloat("inner_width (when ScrollX active)", inner_width_with_scroll, 1.0, 0.0, FLT_MAX);
ImGui.DragFloat("row_min_height", row_min_height, 1.0, 0.0, FLT_MAX);
ImGui.SameLine(); HelpMarker("Specify height of the Selectable item.");
ImGui.DragInt("items_count", items_count, 0.1f, 0, 9999);
ImGui.Combo("items_type (first column)", contents_type, contents_type_names, IM_ARRAYSIZE(contents_type_names));
--filter.Draw("filter");
ImGui.TreePop();
end
ImGui.PopItemWidth();
PopStyleCompact();
ImGui.Spacing();
ImGui.TreePop();
end
-- Update item list if we changed the number of items
static ImVector<MyItem> items;
static ImVector<int> selection;
local items_need_sort = false;
if (items.Size ~= items_count)then
items.resize(items_count, MyItem());
for (int n = 0; n < items_count; n++)then
const int template_n = n % IM_ARRAYSIZE(template_items_names);
MyItem& item = items[n];
item.ID = n;
item.Name = template_items_names[template_n];
item.Quantity = (template_n == 3) ? 10 : (template_n == 4) ? 20 : 0; -- Assign default quantities
end
end
const ImDrawList* parent_draw_list = ImGui.GetWindowDrawList();
const int parent_draw_list_draw_cmd_count = parent_draw_list->CmdBuffer.Size;
ImVec2 table_scroll_cur, table_scroll_max; -- For debug display
const ImDrawList* table_draw_list = NULL; -- "
-- Submit table
const float inner_width_to_use = (flags & ImGuiTableFlags_ScrollX) ? inner_width_with_scroll : 0.0;
if (ImGui.BeginTable("table_advanced", 6, flags, outer_size_enabled ? outer_size_value : ImVec2(0, 0), inner_width_to_use))then
-- Declare columns
-- We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications.
-- This is so our sort function can identify a column given our own identifier. We could also identify them based on their indexnot
ImGui.TableSetupColumn("ID", ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoHide, 0.0, MyItemColumnID_ID);
ImGui.TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed, 0.0, MyItemColumnID_Name);
ImGui.TableSetupColumn("Action", ImGuiTableColumnFlags_NoSort | ImGuiTableColumnFlags_WidthFixed, 0.0, MyItemColumnID_Action);
ImGui.TableSetupColumn("Quantity", ImGuiTableColumnFlags_PreferSortDescending, 0.0, MyItemColumnID_Quantity);
ImGui.TableSetupColumn("Description", (flags & ImGuiTableFlags_NoHostExtendX) ? 0 : ImGuiTableColumnFlags_WidthStretch, 0.0, MyItemColumnID_Description);
ImGui.TableSetupColumn("Hidden", ImGuiTableColumnFlags_DefaultHide | ImGuiTableColumnFlags_NoSort);
ImGui.TableSetupScrollFreeze(freeze_cols, freeze_rows);
-- Sort our data if sort specs have been changednot
ImGuiTableSortSpecs* sorts_specs = ImGui.TableGetSortSpecs();
if (sorts_specs and sorts_specs->SpecsDirty)
items_need_sort = true;
if (sorts_specs and items_need_sort and items.Size > 1)then
MyItem.s_current_sort_specs = sorts_specs; -- Store in variable accessible by the sort function.
qsort(&items[0], (size_t)items.Size, sizeof(items[0]), MyItem.CompareWithSortSpecs);
MyItem.s_current_sort_specs = NULL;
sorts_specs->SpecsDirty = false;
end
items_need_sort = false;
-- Take note of whether we are currently sorting based on the Quantity field,
-- we will use this to trigger sorting when we know the data of this column has been modified.
const bool sorts_specs_using_quantity = (ImGui.TableGetColumnFlags(3) & ImGuiTableColumnFlags_IsSorted) ~= 0;
-- Show headers
if (show_headers)
ImGui.TableHeadersRow();
-- Show data
-- FIXME-TABLE FIXME-NAV: How we can get decent up/down even though we have the buttons here?
ImGui.PushButtonRepeat(true);
--if 1
-- Demonstrate using clipper for large vertical lists
ImGuiListClipper clipper;
clipper.Begin(items.Size);
while (clipper.Step())then
for (int row_n = clipper.DisplayStart; row_n < clipper.DisplayEnd; row_n++)
--else
-- Without clipperthen
for (int row_n = 0; row_n < items.Size; row_n++)
--endifthen
MyItem* item = &items[row_n];
--if (not filter.PassFilter(item->Name))
-- continue;
const bool item_is_selected = selection.contains(item->ID);
ImGui.PushID(item->ID);
ImGui.TableNextRow(ImGuiTableRowFlags_None, row_min_height);
-- For the demo purpose we can select among different type of items submitted in the first column
ImGui.TableSetColumnIndex(0);
char label[32];
sprintf(label, "%04d", item->ID);
if (contents_type == CT_Text)
ImGui.TextUnformatted(label);
else if (contents_type == CT_Button)
ImGui.Button(label);
else if (contents_type == CT_SmallButton)
ImGui.SmallButton(label);
else if (contents_type == CT_FillButton)
ImGui.Button(label, ImVec2(-FLT_MIN, 0.0));
else if (contents_type == CT_Selectable or contents_type == CT_SelectableSpanRow)then
ImGuiSelectableFlags selectable_flags = (contents_type == CT_SelectableSpanRow) ? ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowItemOverlap : ImGuiSelectableFlags_None;
if (ImGui.Selectable(label, item_is_selected, selectable_flags, ImVec2(0, row_min_height)))then
if (ImGui.GetIO().KeyCtrl)then
if (item_is_selected)
selection.find_erase_unsorted(item->ID);
else
selection.push_back(item->ID);
end
elsethen
selection.clear();
selection.push_back(item->ID);
end
end
end
if (ImGui.TableSetColumnIndex(1))
ImGui.TextUnformatted(item->Name);
-- Here we demonstrate marking our data set as needing to be sorted again if we modified a quantity,
-- and we are currently sorting on the column showing the Quantity.
-- To avoid triggering a sort while holding the button, we only trigger it when the button has been released.
-- You will probably need a more advanced system in your code if you want to automatically sort when a specific entry changes.
if (ImGui.TableSetColumnIndex(2))then
if (ImGui.SmallButton("Chop")) do item->Quantity += 1; end
if (sorts_specs_using_quantity and ImGui.IsItemDeactivated()) do items_need_sort = true; end
ImGui.SameLine();
if (ImGui.SmallButton("Eat")) do item->Quantity -= 1; end
if (sorts_specs_using_quantity and ImGui.IsItemDeactivated()) do items_need_sort = true; end
end
if (ImGui.TableSetColumnIndex(3))
ImGui.Text("%d", item->Quantity);
ImGui.TableSetColumnIndex(4);
if (show_wrapped_text)
ImGui.TextWrapped("Lorem ipsum dolor sit amet");
else
ImGui.Text("Lorem ipsum dolor sit amet");
if (ImGui.TableSetColumnIndex(5))
ImGui.Text("1234");
ImGui.PopID();
end
end
ImGui.PopButtonRepeat();
-- Store some info to display debug details below
table_scroll_cur = ImVec2(ImGui.GetScrollX(), ImGui.GetScrollY());
table_scroll_max = ImVec2(ImGui.GetScrollMaxX(), ImGui.GetScrollMaxY());
table_draw_list = ImGui.GetWindowDrawList();
ImGui.EndTable();
end
local show_debug_details = false;
ImGui.Checkbox("Debug details", show_debug_details);
if (show_debug_details and table_draw_list)then
ImGui.SameLine(0.0, 0.0);
const int table_draw_list_draw_cmd_count = table_draw_list->CmdBuffer.Size;
if (table_draw_list == parent_draw_list)
ImGui.Text(": DrawCmd: +%d (in same window)",
table_draw_list_draw_cmd_count - parent_draw_list_draw_cmd_count);
else
ImGui.Text(": DrawCmd: +%d (in child window), Scroll: (%.f/%.f) (%.f/%.f)",
table_draw_list_draw_cmd_count - 1, table_scroll_cur.x, table_scroll_max.x, table_scroll_cur.y, table_scroll_max.y);
end
ImGui.TreePop();
end
ImGui.PopID();
ShowDemoWindowColumns();
if (disable_indent)
ImGui.PopStyleVar();
end
-- Demonstrate old/legacy Columns APInot
-- [2020: Columns are under-featured and not maintained. Prefer using the more flexible and powerful BeginTable() APInot ]
function ShowDemoWindowColumns()
bool open = ImGui.TreeNode("Legacy Columns API");
ImGui.SameLine();
HelpMarker("Columns() is an old APInot Prefer using the more flexible and powerful BeginTable() APInot ");
if (not open)
return;
-- Basic columns
if (ImGui.TreeNode("Basic"))then
ImGui.Text("Without border:");
ImGui.Columns(3, "mycolumns3", false); -- 3-ways, no border
ImGui.Separator();
for (int n = 0; n < 14; n++)then
char label[32];
sprintf(label, "Item %d", n);
if (ImGui.Selectable(label)) do end
--if (ImGui.Button(label, ImVec2(-FLT_MIN,0.0))) do end
ImGui.NextColumn();
end
ImGui.Columns(1);
ImGui.Separator();
ImGui.Text("With border:");
ImGui.Columns(4, "mycolumns"); -- 4-ways, with border
ImGui.Separator();
ImGui.Text("ID"); ImGui.NextColumn();
ImGui.Text("Name"); ImGui.NextColumn();
ImGui.Text("Path"); ImGui.NextColumn();
ImGui.Text("Hovered"); ImGui.NextColumn();
ImGui.Separator();
const char* names[3] = do "One", "Two", "Three" end;
const char* paths[3] = do "/path/one", "/path/two", "/path/three" end;
static int selected = -1;
for (int i = 0; i < 3; i++)then
char label[32];
sprintf(label, "%04d", i);
if (ImGui.Selectable(label, selected == i, ImGuiSelectableFlags_SpanAllColumns))
selected = i;
bool hovered = ImGui.IsItemHovered();
ImGui.NextColumn();
ImGui.Text(names[i]); ImGui.NextColumn();
ImGui.Text(paths[i]); ImGui.NextColumn();
ImGui.Text("%d", hovered); ImGui.NextColumn();
end
ImGui.Columns(1);
ImGui.Separator();
ImGui.TreePop();
end
if (ImGui.TreeNode("Borders"))then
-- NB: Future columns API should allow automatic horizontal borders.
local h_borders = true;
local v_borders = true;
static int columns_count = 4;
const int lines_count = 3;
ImGui.SetNextItemWidth(ImGui.GetFontSize() * 8);
ImGui.DragInt("----columns_count", columns_count, 0.1f, 2, 10, "%d columns");
if (columns_count < 2)
columns_count = 2;
ImGui.SameLine();
ImGui.Checkbox("horizontal", h_borders);
ImGui.SameLine();
ImGui.Checkbox("vertical", v_borders);
ImGui.Columns(columns_count, NULL, v_borders);
for (int i = 0; i < columns_count * lines_count; i++)then
if (h_borders and ImGui.GetColumnIndex() == 0)
ImGui.Separator();
ImGui.Text("%c%c%c", 'a' + i, 'a' + i, 'a' + i);
ImGui.Text("Width %.2f", ImGui.GetColumnWidth());
ImGui.Text("Avail %.2f", ImGui.GetContentRegionAvail().x);
ImGui.Text("Offset %.2f", ImGui.GetColumnOffset());
ImGui.Text("Long text that is likely to clip");
ImGui.Button("Button", ImVec2(-FLT_MIN, 0.0));
ImGui.NextColumn();
end
ImGui.Columns(1);
if (h_borders)
ImGui.Separator();
ImGui.TreePop();
end
-- Create multiple items in a same cell before switching to next column
if (ImGui.TreeNode("Mixed items"))then
ImGui.Columns(3, "mixed");
ImGui.Separator();
ImGui.Text("Hello");
ImGui.Button("Banana");
ImGui.NextColumn();
ImGui.Text("ImGui");
ImGui.Button("Apple");
static float foo = 1.0;
ImGui.InputFloat("red", foo, 0.05f, 0, "%.3f");
ImGui.Text("An extra line here.");
ImGui.NextColumn();
ImGui.Text("Sailor");
ImGui.Button("Corniflower");
static float bar = 1.0;
ImGui.InputFloat("blue", bar, 0.05f, 0, "%.3f");
ImGui.NextColumn();
if (ImGui.CollapsingHeader("Category A")) do ImGui.Text("Blah blah blah"); end ImGui.NextColumn();
if (ImGui.CollapsingHeader("Category B")) do ImGui.Text("Blah blah blah"); end ImGui.NextColumn();
if (ImGui.CollapsingHeader("Category C")) do ImGui.Text("Blah blah blah"); end ImGui.NextColumn();
ImGui.Columns(1);
ImGui.Separator();
ImGui.TreePop();
end
-- Word wrapping
if (ImGui.TreeNode("Word-wrapping"))then
ImGui.Columns(2, "word-wrapping");
ImGui.Separator();
ImGui.TextWrapped("The quick brown fox jumps over the lazy dog.");
ImGui.TextWrapped("Hello Left");
ImGui.NextColumn();
ImGui.TextWrapped("The quick brown fox jumps over the lazy dog.");
ImGui.TextWrapped("Hello Right");
ImGui.Columns(1);
ImGui.Separator();
ImGui.TreePop();
end
if (ImGui.TreeNode("Horizontal Scrolling"))then
ImGui.SetNextWindowContentSize(ImVec2(1500.0, 0.0));
ImVec2 child_size = ImVec2(0, ImGui.GetFontSize() * 20.0);
ImGui.BeginChild("----ScrollingRegion", child_size, false, ImGuiWindowFlags_HorizontalScrollbar);
ImGui.Columns(10);
-- Also demonstrate using clipper for large vertical lists
int ITEMS_COUNT = 2000;
ImGuiListClipper clipper;
clipper.Begin(ITEMS_COUNT);
while (clipper.Step())then
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
for (int j = 0; j < 10; j++)then
ImGui.Text("Line %d Column %d...", i, j);
ImGui.NextColumn();
end
end
ImGui.Columns(1);
ImGui.EndChild();
ImGui.TreePop();
end
if (ImGui.TreeNode("Tree"))then
ImGui.Columns(2, "tree", true);
for (int x = 0; x < 3; x++)then
bool open1 = ImGui.TreeNode((void*)(intptr_t)x, "Node%d", x);
ImGui.NextColumn();
ImGui.Text("Node contents");
ImGui.NextColumn();
if (open1)then
for (int y = 0; y < 3; y++)then
bool open2 = ImGui.TreeNode((void*)(intptr_t)y, "Node%d.%d", x, y);
ImGui.NextColumn();
ImGui.Text("Node contents");
if (open2)then
ImGui.Text("Even more contents");
if (ImGui.TreeNode("Tree in column"))then
ImGui.Text("The quick brown fox jumps over the lazy dog");
ImGui.TreePop();
end
end
ImGui.NextColumn();
if (open2)
ImGui.TreePop();
end
ImGui.TreePop();
end
end
ImGui.Columns(1);
ImGui.TreePop();
end
ImGui.TreePop();
end
-------------------------------------------------------------------------------
-- [SECTION] Style Editor / ShowStyleEditor()
-------------------------------------------------------------------------------
-- - ShowFontSelector()
-- - ShowStyleSelector()
-- - ShowStyleEditor()
-------------------------------------------------------------------------------
-- Forward declare ShowFontAtlas() which isn't worth putting in public API yet
namespace ImGui do IMGUI_API void ShowFontAtlas(ImFontAtlas* atlas); end
-- Demo helper function to select among loaded fonts.
-- Here we use the regular BeginCombo()/EndCombo() api which is more the more flexible one.
function ImGui.ShowFontSelector(const char* label)
ImGuiIO& io = ImGui.GetIO();
ImFont* font_current = ImGui.GetFont();
if (ImGui.BeginCombo(label, font_current->GetDebugName()))then
for (int n = 0; n < io.Fonts->Fonts.Size; n++)then
ImFont* font = io.Fonts->Fonts[n];
ImGui.PushID((void*)font);
if (ImGui.Selectable(font->GetDebugName(), font == font_current))
io.FontDefault = font;
ImGui.PopID();
end
ImGui.EndCombo();
end
ImGui.SameLine();
HelpMarker(
"- Load additional fonts with io.Fonts->AddFontFromFileTTF().\n"
"- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\n"
"- Read FAQ and docs/FONTS.md for more details.\n"
"- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame().");
end
-- Demo helper function to select among default colors. See ShowStyleEditor() for more advanced options.
-- Here we use the simplified Combo() api that packs items into a single literal string.
-- Useful for quick combo boxes where the choices are known locally.
bool ImGui.ShowStyleSelector(const char* label)
static int style_idx = -1;
if (ImGui.Combo(label, style_idx, "Dark\0Light\0Classic\0"))then
switch (style_idx)then
case 0: ImGui.StyleColorsDark(); break;
case 1: ImGui.StyleColorsLight(); break;
case 2: ImGui.StyleColorsClassic(); break;
end
return true;
end
return false;
end
function ImGui.ShowStyleEditor(ImGuiStyle* ref)
-- You can pass in a reference ImGuiStyle structure to compare to, revert to and save to
-- (without a reference style pointer, we will use one compared locally as a reference)
ImGuiStyle& style = ImGui.GetStyle();
static ImGuiStyle ref_saved_style;
-- Default to using internal storage as reference
local init = true;
if (init and ref == NULL)
ref_saved_style = style;
init = false;
if (ref == NULL)
ref = &ref_saved_style;
ImGui.PushItemWidth(ImGui.GetWindowWidth() * 0..0);
if (ImGui.ShowStyleSelector("Colors----Selector"))
ref_saved_style = style;
ImGui.ShowFontSelector("Fonts----Selector");
-- Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0 or 1.0)
if (ImGui.SliderFloat("FrameRounding", style.FrameRounding, 0.0, 12.0, "%.0"))
style.GrabRounding = style.FrameRounding; -- Make GrabRounding always the same value as FrameRoundingthen bool border = (style.WindowBorderSize > 0.0); if (ImGui.Checkbox("WindowBorder", border)) do style.WindowBorderSize = border ? 1.0 : 0.0; end end
ImGui.SameLine();then bool border = (style.FrameBorderSize > 0.0); if (ImGui.Checkbox("FrameBorder", &border)) do style.FrameBorderSize = border ? 1.0 : 0.0; end end
ImGui.SameLine();then bool border = (style.PopupBorderSize > 0.0); if (ImGui.Checkbox("PopupBorder", &border)) do style.PopupBorderSize = border ? 1.0 : 0.0; end end
-- Save/Revert button
if (ImGui.Button("Save Ref"))
*ref = ref_saved_style = style;
ImGui.SameLine();
if (ImGui.Button("Revert Ref"))
style = *ref;
ImGui.SameLine();
HelpMarker(
"Save/Revert in local non-persistent storage. Default Colors definition are not affected. "
"Use \"Export\" below to save them somewhere.");
ImGui.Separator();
if (ImGui.BeginTabBar("----tabs", ImGuiTabBarFlags_None))then
if (ImGui.BeginTabItem("Sizes"))then
ImGui.Text("Main");
ImGui.SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0, 20.0, "%.0");
ImGui.SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0, 20.0, "%.0");
ImGui.SliderFloat2("CellPadding", (float*)&style.CellPadding, 0.0, 20.0, "%.0");
ImGui.SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0, 20.0, "%.0");
ImGui.SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0, 20.0, "%.0");
ImGui.SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0, 10.0, "%.0");
ImGui.SliderFloat("IndentSpacing", style.IndentSpacing, 0.0, 30.0, "%.0");
ImGui.SliderFloat("ScrollbarSize", style.ScrollbarSize, 1.0, 20.0, "%.0");
ImGui.SliderFloat("GrabMinSize", style.GrabMinSize, 1.0, 20.0, "%.0");
ImGui.Text("Borders");
ImGui.SliderFloat("WindowBorderSize", style.WindowBorderSize, 0.0, 1.0, "%.0");
ImGui.SliderFloat("ChildBorderSize", style.ChildBorderSize, 0.0, 1.0, "%.0");
ImGui.SliderFloat("PopupBorderSize", style.PopupBorderSize, 0.0, 1.0, "%.0");
ImGui.SliderFloat("FrameBorderSize", style.FrameBorderSize, 0.0, 1.0, "%.0");
ImGui.SliderFloat("TabBorderSize", style.TabBorderSize, 0.0, 1.0, "%.0");
ImGui.Text("Rounding");
ImGui.SliderFloat("WindowRounding", style.WindowRounding, 0.0, 12.0, "%.0");
ImGui.SliderFloat("ChildRounding", style.ChildRounding, 0.0, 12.0, "%.0");
ImGui.SliderFloat("FrameRounding", style.FrameRounding, 0.0, 12.0, "%.0");
ImGui.SliderFloat("PopupRounding", style.PopupRounding, 0.0, 12.0, "%.0");
ImGui.SliderFloat("ScrollbarRounding", style.ScrollbarRounding, 0.0, 12.0, "%.0");
ImGui.SliderFloat("GrabRounding", style.GrabRounding, 0.0, 12.0, "%.0");
ImGui.SliderFloat("LogSliderDeadzone", style.LogSliderDeadzone, 0.0, 12.0, "%.0");
ImGui.SliderFloat("TabRounding", style.TabRounding, 0.0, 12.0, "%.0");
ImGui.Text("Alignment");
ImGui.SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0, 1.0, "%.2f");
int window_menu_button_position = style.WindowMenuButtonPosition + 1;
if (ImGui.Combo("WindowMenuButtonPosition", (int*)&window_menu_button_position, "None\0Left\0Right\0"))
style.WindowMenuButtonPosition = window_menu_button_position - 1;
ImGui.Combo("ColorButtonPosition", (int*)&style.ColorButtonPosition, "Left\0Right\0");
ImGui.SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0, 1.0, "%.2f");
ImGui.SameLine(); HelpMarker("Alignment applies when a button is larger than its text content.");
ImGui.SliderFloat2("SelectableTextAlign", (float*)&style.SelectableTextAlign, 0.0, 1.0, "%.2f");
ImGui.SameLine(); HelpMarker("Alignment applies when a selectable is larger than its text content.");
ImGui.Text("Safe Area Padding");
ImGui.SameLine(); HelpMarker("Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured).");
ImGui.SliderFloat2("DisplaySafeAreaPadding", (float*)&style.DisplaySafeAreaPadding, 0.0, 30.0, "%.0");
ImGui.EndTabItem();
end
if (ImGui.BeginTabItem("Colors"))then
static int output_dest = 0;
local output_only_modified = true;
if (ImGui.Button("Export"))then
if (output_dest == 0)
ImGui.LogToClipboard();
else
ImGui.LogToTTY();
ImGui.LogText("ImVec4* colors = ImGui.GetStyle().Colors;" IM_NEWLINE);
for (int i = 0; i < ImGuiCol_COUNT; i++)then
const ImVec4& col = style.Colors[i];
const char* name = ImGui.GetStyleColorName(i);
if (not output_only_modified or memcmp(&col, ref->Colors[i], sizeof(ImVec4)) ~= 0)
ImGui.LogText("colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE,
name, 23 - (int)strlen(name), "", col.x, col.y, col.z, col.w);
end
ImGui.LogFinish();
end
ImGui.SameLine(); ImGui.SetNextItemWidth(120); ImGui.Combo("----output_type", output_dest, "To Clipboard\0To TTY\0");
ImGui.SameLine(); ImGui.Checkbox("Only Modified Colors", output_only_modified);
static ImGuiTextFilter filter;
filter.Draw("Filter colors", ImGui.GetFontSize() * 16);
static ImGuiColorEditFlags alpha_flags = 0;
if (ImGui.RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_None)) then alpha_flags = ImGuiColorEditFlags_None; end ImGui.SameLine();
if (ImGui.RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_AlphaPreview)) then alpha_flags = ImGuiColorEditFlags_AlphaPreview; end ImGui.SameLine();
if (ImGui.RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) do alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; end ImGui.SameLine();
HelpMarker(
"In the color list:\n"
"Left-click on color square to open color picker,\n"
"Right-click to open edit options menu.");
ImGui.BeginChild("----colors", ImVec2(0, 0), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar | ImGuiWindowFlags_NavFlattened);
ImGui.PushItemWidth(-160);
for (int i = 0; i < ImGuiCol_COUNT; i++)then
const char* name = ImGui.GetStyleColorName(i);
if (not filter.PassFilter(name))
continue;
ImGui.PushID(i);
ImGui.ColorEdit4("----color", (float*)&style.Colors[i], ImGuiColorEditFlags_AlphaBar | alpha_flags);
if (memcmp(&style.Colors[i], ref->Colors[i], sizeof(ImVec4)) ~= 0)then
-- Tips: in a real user application, you may want to merge and use an icon font into the main font,
-- so instead of "Save"/"Revert" you'd use iconsnot
-- Read the FAQ and docs/FONTS.md about using icon fonts. It's really easy and super convenientnot
ImGui.SameLine(0.0, style.ItemInnerSpacing.x); if (ImGui.Button("Save")) do ref->Colors[i] = style.Colors[i]; end
ImGui.SameLine(0.0, style.ItemInnerSpacing.x); if (ImGui.Button("Revert")) do style.Colors[i] = ref->Colors[i]; end
end
ImGui.SameLine(0.0, style.ItemInnerSpacing.x);
ImGui.TextUnformatted(name);
ImGui.PopID();
end
ImGui.PopItemWidth();
ImGui.EndChild();
ImGui.EndTabItem();
end
if (ImGui.BeginTabItem("Fonts"))then
ImGuiIO& io = ImGui.GetIO();
ImFontAtlas* atlas = io.Fonts;
HelpMarker("Read FAQ and docs/FONTS.md for details on font loading.");
ImGui.ShowFontAtlas(atlas);
-- Post-baking font scaling. Note that this is NOT the nice way of scaling fonts, read below.
-- (we enforce hard clamping manually as by default DragFloat/SliderFloat allows CTRL+Click text to get out of bounds).
const float MIN_SCALE = 0.3f;
const float MAX_SCALE = 2.0;
HelpMarker(
"Those are old settings provided for convenience.\n"
"However, the _correct_ way of scaling your UI is currently to reload your font at the designed size, "
"rebuild the font atlas, and call style.ScaleAllSizes() on a reference ImGuiStyle structure.\n"
"Using those settings here will give you poor quality results.");
static float window_scale = 1.0;
ImGui.PushItemWidth(ImGui.GetFontSize() * 8);
if (ImGui.DragFloat("window scale", window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp)) -- Scale only this window
ImGui.SetWindowFontScale(window_scale);
ImGui.DragFloat("global scale", io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp); -- Scale everything
ImGui.PopItemWidth();
ImGui.EndTabItem();
end
if (ImGui.BeginTabItem("Rendering"))then
ImGui.Checkbox("Anti-aliased lines", style.AntiAliasedLines);
ImGui.SameLine();
HelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well.");
ImGui.Checkbox("Anti-aliased lines use texture", style.AntiAliasedLinesUseTex);
ImGui.SameLine();
HelpMarker("Faster lines using texture data. Require backend to render with bilinear filtering (not point/nearest filtering).");
ImGui.Checkbox("Anti-aliased fill", style.AntiAliasedFill);
ImGui.PushItemWidth(ImGui.GetFontSize() * 8);
ImGui.DragFloat("Curve Tessellation Tolerance", style.CurveTessellationTol, 0.02f, 0..0, 10.0, "%.2f");
if (style.CurveTessellationTol < 0..0) style.CurveTessellationTol = 0..0;
-- When editing the "Circle Segment Max Error" value, draw a preview of its effect on auto-tessellated circles.
ImGui.DragFloat("Circle Tessellation Max Error", style.CircleTessellationMaxError , 0.005f, 0..0, 5.0, "%.2f", ImGuiSliderFlags_AlwaysClamp);
if (ImGui.IsItemActive())then
ImGui.SetNextWindowPos(ImGui.GetCursorScreenPos());
ImGui.BeginTooltip();
ImGui.TextUnformatted("(R = radius, N = number of segments)");
ImGui.Spacing();
ImDrawList* draw_list = ImGui.GetWindowDrawList();
const float min_widget_width = ImGui.CalcTextSize("N: MMM\nR: MMM").x;
for (int n = 0; n < 8; n++)then
const float RAD_MIN = 5.0;
const float RAD_MAX = 70.0;
const float rad = RAD_MIN + (RAD_MAX - RAD_MIN) * (float)n / (8.0 - 1.0);
ImGui.BeginGroup();
ImGui.Text("R: %.f\nN: %d", rad, draw_list->_CalcCircleAutoSegmentCount(rad));
const float canvas_width = IM_MAX(min_widget_width, rad * 2.0);
const float offset_x = floorf(canvas_width * 0.5f);
const float offset_y = floorf(RAD_MAX);
const ImVec2 p1 = ImGui.GetCursorScreenPos();
draw_list->AddCircle(ImVec2(p1.x + offset_x, p1.y + offset_y), rad, ImGui.GetColorU32(ImGuiCol_Text));
ImGui.Dummy(ImVec2(canvas_width, RAD_MAX * 2));
--
const ImVec2 p2 = ImGui.GetCursorScreenPos();
draw_list->AddCircleFilled(ImVec2(p2.x + offset_x, p2.y + offset_y), rad, ImGui.GetColorU32(ImGuiCol_Text));
ImGui.Dummy(ImVec2(canvas_width, RAD_MAX * 2));
--
ImGui.EndGroup();
ImGui.SameLine();
end
ImGui.EndTooltip();
end
ImGui.SameLine();
HelpMarker("When drawing circle primitives with \"num_segments == 0\" tesselation will be calculated automatically.");
ImGui.DragFloat("Global Alpha", style.Alpha, 0.005f, 0..0, 1.0, "%.2f"); -- Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero.
ImGui.DragFloat("Disabled Alpha", style.DisabledAlpha, 0.005f, 0.0, 1.0, "%.2f"); ImGui.SameLine(); HelpMarker("Additional alpha multiplier for disabled items (multiply over current value of Alpha).");
ImGui.PopItemWidth();
ImGui.EndTabItem();
end
ImGui.EndTabBar();
end
ImGui.PopItemWidth();
end
-------------------------------------------------------------------------------
-- [SECTION] Example App: Debug Console / ShowExampleAppConsole()
-------------------------------------------------------------------------------
-- Demonstrate creating a simple console window, with scrolling, filtering, completion and history.
-- For the console example, we are using a more C++ like approach of declaring a class to hold both data and functions.
struct ExampleAppConsole
char InputBuf[256];
ImVector<char*> Items;
ImVector<const char*> Commands;
ImVector<char*> History;
int HistoryPos; -- -1: new line, 0..History.Size-1 browsing history.
ImGuiTextFilter Filter;
bool AutoScroll;
bool ScrollToBottom;
ExampleAppConsole()then
ClearLog();
memset(InputBuf, 0, sizeof(InputBuf));
HistoryPos = -1;
-- "CLASSIFY" is here to provide the test case where "C"+[tab] completes to "CL" and display multiple matches.
Commands.push_back("HELP");
Commands.push_back("HISTORY");
Commands.push_back("CLEAR");
Commands.push_back("CLASSIFY");
AutoScroll = true;
ScrollToBottom = false;
AddLog("Welcome to Dear ImGuinot ");
end
~ExampleAppConsole()then
ClearLog();
for (int i = 0; i < History.Size; i++)
free(History[i]);
end
-- Portable helpers
static int Stricmp(const char* s1, const char* s2) then int d; while ((d = toupper(*s2) - toupper(*s1)) == 0 and *s1) do s1++; s2++; end return d; end
static int Strnicmp(const char* s1, const char* s2, int n) do int d = 0; while (n > 0 and (d = toupper(*s2) - toupper(*s1)) == 0 and *s1) do s1++; s2++; n--; end return d; end
static char* Strdup(const char* s) then IM_ASSERT(s); size_t len = strlen(s) + 1; void* buf = malloc(len); IM_ASSERT(buf); return (char*)memcpy(buf, (const void*)s, len); end
function Strtrim(char* s) then char* str_end = s + strlen(s); while (str_end > s and str_end[-1] == ' ') str_end--; *str_end = 0; end
void ClearLog()then
for (int i = 0; i < Items.Size; i++)
free(Items[i]);
Items.clear();
end
void AddLog(const char* fmt, ...) IM_FMTARGS(2)then
-- FIXME-OPT
char buf[1024];
va_list args;
va_start(args, fmt);
vsnprintf(buf, IM_ARRAYSIZE(buf), fmt, args);
buf[IM_ARRAYSIZE(buf)-1] = 0;
va_end(args);
Items.push_back(Strdup(buf));
end
void Draw(const char* title, bool* p_open)then
ImGui.SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver);
if (not ImGui.Begin(title, p_open))then
ImGui.End();
return;
end
-- As a specific feature guaranteed by the library, after calling Begin() the last Item represent the title bar.
-- So e.g. IsItemHovered() will return true when hovering the title bar.
-- Here we create a context menu only available from the title bar.
if (ImGui.BeginPopupContextItem())then
if (ImGui.MenuItem("Close Console"))
*p_open = false;
ImGui.EndPopup();
end
ImGui.TextWrapped(
"This example implements a console with basic coloring, completion (TAB key) and history (Up/Down keys). A more elaborate "
"implementation may want to store entries along with extra data such as timestamp, emitter, etc.");
ImGui.TextWrapped("Enter 'HELP' for help.");
-- TODO: display items starting from the bottom
if (ImGui.SmallButton("Add Debug Text")) do AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message herenot "); end
ImGui.SameLine();
if (ImGui.SmallButton("Add Debug Error")) do AddLog("[error] something went wrong"); end
ImGui.SameLine();
if (ImGui.SmallButton("Clear")) then ClearLog(); end
ImGui.SameLine();
bool copy_to_clipboard = ImGui.SmallButton("Copy");
--static float t = 0.0; if (ImGui.GetTime() - t > 0.02f) do t = ImGui.GetTime(); AddLog("Spam %f", t); end
ImGui.Separator();
-- Options menu
if (ImGui.BeginPopup("Options"))then
ImGui.Checkbox("Auto-scroll", AutoScroll);
ImGui.EndPopup();
end
-- Options, Filter
if (ImGui.Button("Options"))
ImGui.OpenPopup("Options");
ImGui.SameLine();
Filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180);
ImGui.Separator();
-- Reserve enough left-over height for 1 separator + 1 input text
const float footer_height_to_reserve = ImGui.GetStyle().ItemSpacing.y + ImGui.GetFrameHeightWithSpacing();
ImGui.BeginChild("ScrollingRegion", ImVec2(0, -footer_height_to_reserve), false, ImGuiWindowFlags_HorizontalScrollbar);
if (ImGui.BeginPopupContextWindow())then
if (ImGui.Selectable("Clear")) ClearLog();
ImGui.EndPopup();
end
-- Display every line as a separate entry so we can change their color or add custom widgets.
-- If you only want raw text you can use ImGui.TextUnformatted(log.begin(), log.end());
-- NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping
-- to only process visible items. The clipper will automatically measure the height of your first item and then
-- "seek" to display only items in the visible area.
-- To use the clipper we can replace your standard loop:
-- for (int i = 0; i < Items.Size; i++)
-- With:
-- ImGuiListClipper clipper;
-- clipper.Begin(Items.Size);
-- while (clipper.Step())
-- for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
-- - That your items are evenly spaced (same height)
-- - That you have cheap random access to your elements (you can access them given their index,
-- without processing all the ones before)
-- You cannot this code as-is if a filter is active because it breaks the 'cheap random-access' property.
-- We would need random-access on the post-filtered list.
-- A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices
-- or offsets of items that passed the filtering test, recomputing this array when user changes the filter,
-- and appending newly elements as they are inserted. This is left as a task to the user until we can manage
-- to improve this example codenot
-- If your items are of variable height:
-- - Split them into same height items would be simpler and facilitate random-seeking into your list.
-- - Consider using manual call to IsRectVisible() and skipping extraneous decoration from your items.
ImGui.PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 1)); -- Tighten spacing
if (copy_to_clipboard)
ImGui.LogToClipboard();
for (int i = 0; i < Items.Size; i++)then
const char* item = Items[i];
if (not Filter.PassFilter(item))
continue;
-- Normally you would store more information in your item than just a string.
-- (e.g. make Items[] an array of structure, store color/type etc.)
ImVec4 color;
bool has_color = false;
if (strstr(item, "[error]")) then color = ImVec4(1.0, 0.4f, 0.4f, 1.0); has_color = true; end
else if (strncmp(item, "-- ", 2) == 0) do color = ImVec4(1.0, 0.8f, 0.6f, 1.0); has_color = true; end
if (has_color)
ImGui.PushStyleColor(ImGuiCol_Text, color);
ImGui.TextUnformatted(item);
if (has_color)
ImGui.PopStyleColor();
end
if (copy_to_clipboard)
ImGui.LogFinish();
if (ScrollToBottom or (AutoScroll and ImGui.GetScrollY() >= ImGui.GetScrollMaxY()))
ImGui.SetScrollHereY(1.0);
ScrollToBottom = false;
ImGui.PopStyleVar();
ImGui.EndChild();
ImGui.Separator();
-- Command-line
bool reclaim_focus = false;
ImGuiInputTextFlags input_text_flags = ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory;
if (ImGui.InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), input_text_flags, TextEditCallbackStub, (void*)this))then
char* s = InputBuf;
Strtrim(s);
if (s[0])
ExecCommand(s);
strcpy(s, "");
reclaim_focus = true;
end
-- Auto-focus on window apparition
ImGui.SetItemDefaultFocus();
if (reclaim_focus)
ImGui.SetKeyboardFocusHere(-1); -- Auto focus previous widget
ImGui.End();
end
void ExecCommand(const char* command_line)then
AddLog("-- %s\n", command_line);
-- Insert into history. First find match and delete it so it can be pushed to the back.
-- This isn't trying to be smart or optimal.
HistoryPos = -1;
for (int i = History.Size - 1; i >= 0; i--)
if (Stricmp(History[i], command_line) == 0)then
free(History[i]);
History.erase(History.begin() + i);
break;
end
History.push_back(Strdup(command_line));
-- Process command
if (Stricmp(command_line, "CLEAR") == 0)then
ClearLog();
end
else if (Stricmp(command_line, "HELP") == 0)then
AddLog("Commands:");
for (int i = 0; i < Commands.Size; i++)
AddLog("- %s", Commands[i]);
end
else if (Stricmp(command_line, "HISTORY") == 0)then
int first = History.Size - 10;
for (int i = first > 0 ? first : 0; i < History.Size; i++)
AddLog("%3d: %s\n", i, History[i]);
end
elsethen
AddLog("Unknown command: '%s'\n", command_line);
end
-- On command input, we scroll to bottom even if AutoScroll==false
ScrollToBottom = true;
end
-- In C++11 you'd be better off using lambdas for this sort of forwarding callbacks
static int TextEditCallbackStub(ImGuiInputTextCallbackData* data)then
ExampleAppConsole* console = (ExampleAppConsole*)data->UserData;
return console->TextEditCallback(data);
end
int TextEditCallback(ImGuiInputTextCallbackData* data)then
--AddLog("cursor: %d, selection: %d-%d", data->CursorPos, data->SelectionStart, data->SelectionEnd);
switch (data->EventFlag)then
case ImGuiInputTextFlags_CallbackCompletion:then
-- Example of TEXT COMPLETION
-- Locate beginning of current word
const char* word_end = data->Buf + data->CursorPos;
const char* word_start = word_end;
while (word_start > data->Buf)then
const char c = word_start[-1];
if (c == ' ' or c == '\t' or c == ',' or c == ';')
break;
word_start--;
end
-- Build a list of candidates
ImVector<const char*> candidates;
for (int i = 0; i < Commands.Size; i++)
if (Strnicmp(Commands[i], word_start, (int)(word_end - word_start)) == 0)
candidates.push_back(Commands[i]);
if (candidates.Size == 0)then
-- No match
AddLog("No match for \"%.*s\"not \n", (int)(word_end - word_start), word_start);
end
else if (candidates.Size == 1)then
-- Single match. Delete the beginning of the word and replace it entirely so we've got nice casing.
data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start));
data->InsertChars(data->CursorPos, candidates[0]);
data->InsertChars(data->CursorPos, " ");
end
elsethen
-- Multiple matches. Complete as much as we can..
-- So inputing "C"+Tab will complete to "CL" then display "CLEAR" and "CLASSIFY" as matches.
int match_len = (int)(word_end - word_start);
for (;;)then
int c = 0;
bool all_candidates_matches = true;
for (int i = 0; i < candidates.Size and all_candidates_matches; i++)
if (i == 0)
c = toupper(candidates[i][match_len]);
else if (c == 0 or c ~= toupper(candidates[i][match_len]))
all_candidates_matches = false;
if (not all_candidates_matches)
break;
match_len++;
end
if (match_len > 0)then
data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start));
data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len);
end
-- List matches
AddLog("Possible matches:\n");
for (int i = 0; i < candidates.Size; i++)
AddLog("- %s\n", candidates[i]);
end
break;
end
case ImGuiInputTextFlags_CallbackHistory:then
-- Example of HISTORY
const int prev_history_pos = HistoryPos;
if (data->EventKey == ImGuiKey_UpArrow)then
if (HistoryPos == -1)
HistoryPos = History.Size - 1;
else if (HistoryPos > 0)
HistoryPos--;
end
else if (data->EventKey == ImGuiKey_DownArrow)then
if (HistoryPos ~= -1)
if (++HistoryPos >= History.Size)
HistoryPos = -1;
end
-- A better implementation would preserve the data on the current input line along with cursor position.
if (prev_history_pos ~= HistoryPos)then
const char* history_str = (HistoryPos >= 0) ? History[HistoryPos] : "";
data->DeleteChars(0, data->BufTextLen);
data->InsertChars(0, history_str);
end
end
end
return 0;
end
end;
function ShowExampleAppConsole(bool* p_open)
static ExampleAppConsole console;
console.Draw("Example: Console", p_open);
end
-------------------------------------------------------------------------------
-- [SECTION] Example App: Debug Log / ShowExampleAppLog()
-------------------------------------------------------------------------------
-- Usage:
-- static ExampleAppLog my_log;
-- my_log.AddLog("Hello %d world\n", 123);
-- my_log.Draw("title");
struct ExampleAppLog
ImGuiTextBuffer Buf;
ImGuiTextFilter Filter;
ImVector<int> LineOffsets; -- Index to lines offset. We maintain this with AddLog() calls.
bool AutoScroll; -- Keep scrolling if already at the bottom.
ExampleAppLog()then
AutoScroll = true;
Clear();
end
void Clear()then
Buf.clear();
LineOffsets.clear();
LineOffsets.push_back(0);
end
void AddLog(const char* fmt, ...) IM_FMTARGS(2)then
int old_size = Buf.size();
va_list args;
va_start(args, fmt);
Buf.appendfv(fmt, args);
va_end(args);
for (int new_size = Buf.size(); old_size < new_size; old_size++)
if (Buf[old_size] == '\n')
LineOffsets.push_back(old_size + 1);
end
void Draw(const char* title, bool* p_open = NULL)then
if (not ImGui.Begin(title, p_open))then
ImGui.End();
return;
end
-- Options menu
if (ImGui.BeginPopup("Options"))then
ImGui.Checkbox("Auto-scroll", AutoScroll);
ImGui.EndPopup();
end
-- Main window
if (ImGui.Button("Options"))
ImGui.OpenPopup("Options");
ImGui.SameLine();
bool clear = ImGui.Button("Clear");
ImGui.SameLine();
bool copy = ImGui.Button("Copy");
ImGui.SameLine();
Filter.Draw("Filter", -100.0);
ImGui.Separator();
ImGui.BeginChild("scrolling", ImVec2(0, 0), false, ImGuiWindowFlags_HorizontalScrollbar);
if (clear)
Clear();
if (copy)
ImGui.LogToClipboard();
ImGui.PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
const char* buf = Buf.begin();
const char* buf_end = Buf.end();
if (Filter.IsActive())then
-- In this example we don't use the clipper when Filter is enabled.
-- This is because we don't have a random access on the result on our filter.
-- A real application processing logs with ten of thousands of entries may want to store the result of
-- search/filter.. especially if the filtering function is not trivial (e.g. reg-exp).
for (int line_no = 0; line_no < LineOffsets.Size; line_no++)then
const char* line_start = buf + LineOffsets[line_no];
const char* line_end = (line_no + 1 < LineOffsets.Size) ? (buf + LineOffsets[line_no + 1] - 1) : buf_end;
if (Filter.PassFilter(line_start, line_end))
ImGui.TextUnformatted(line_start, line_end);
end
end
elsethen
-- The simplest and easy way to display the entire buffer:
-- ImGui.TextUnformatted(buf_begin, buf_end);
-- And it'll just work. TextUnformatted() has specialization for large blob of text and will fast-forward
-- to skip non-visible lines. Here we instead demonstrate using the clipper to only process lines that are
-- within the visible area.
-- If you have tens of thousands of items and their processing cost is non-negligible, coarse clipping them
-- on your side is recommended. Using ImGuiListClipper requires
-- - A) random access into your data
-- - B) items all being the same height,
-- both of which we can handle since we an array pointing to the beginning of each line of text.
-- When using the filter (in the block of code above) we don't have random access into the data to display
-- anymore, which is why we don't use the clipper. Storing or skimming through the search result would make
-- it possible (and would be recommended if you want to search through tens of thousands of entries).
ImGuiListClipper clipper;
clipper.Begin(LineOffsets.Size);
while (clipper.Step())then
for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)then
const char* line_start = buf + LineOffsets[line_no];
const char* line_end = (line_no + 1 < LineOffsets.Size) ? (buf + LineOffsets[line_no + 1] - 1) : buf_end;
ImGui.TextUnformatted(line_start, line_end);
end
end
clipper.End();
end
ImGui.PopStyleVar();
if (AutoScroll and ImGui.GetScrollY() >= ImGui.GetScrollMaxY())
ImGui.SetScrollHereY(1.0);
ImGui.EndChild();
ImGui.End();
end
end;
-- Demonstrate creating a simple log window with basic filtering.
function ShowExampleAppLog(bool* p_open)
static ExampleAppLog log;
-- For the demo: add a debug button _BEFORE_ the normal log window contents
-- We take advantage of a rarely used feature: multiple calls to Begin()/End() are appending to the _same_ window.
-- Most of the contents of the window will be added by the log.Draw() call.
ImGui.SetNextWindowSize(ImVec2(500, 400), ImGuiCond_FirstUseEver);
ImGui.Begin("Example: Log", p_open);
if (ImGui.SmallButton("[Debug] Add 5 entries"))then
static int counter = 0;
const char* categories[3] = do "info", "warn", "error" end;
const char* words[] = do "Bumfuzzled", "Cattywampus", "Snickersnee", "Abibliophobia", "Absquatulate", "Nincompoop", "Pauciloquent" end;
for (int n = 0; n < 5; n++)then
const char* category = categories[counter % IM_ARRAYSIZE(categories)];
const char* word = words[counter % IM_ARRAYSIZE(words)];
log.AddLog("[%05d] [%s] Hello, current time is %.1f, here's a word: '%s'\n",
ImGui.GetFrameCount(), category, ImGui.GetTime(), word);
counter++;
end
end
ImGui.End();
-- Actually call in the regular Log helper (which will Begin() into the same window as we just did)
log.Draw("Example: Log", p_open);
end
-------------------------------------------------------------------------------
-- [SECTION] Example App: Simple Layout / ShowExampleAppLayout()
-------------------------------------------------------------------------------
-- Demonstrate create a window with multiple child windows.
function ShowExampleAppLayout(bool* p_open)
ImGui.SetNextWindowSize(ImVec2(500, 440), ImGuiCond_FirstUseEver);
if (ImGui.Begin("Example: Simple layout", p_open, ImGuiWindowFlags_MenuBar))then
if (ImGui.BeginMenuBar())then
if (ImGui.BeginMenu("File"))then
if (ImGui.MenuItem("Close")) *p_open = false;
ImGui.EndMenu();
end
ImGui.EndMenuBar();
end
-- Left
static int selected = 0;then
ImGui.BeginChild("left pane", ImVec2(150, 0), true);
for (int i = 0; i < 100; i++)then
-- FIXME: Good candidate to use ImGuiSelectableFlags_SelectOnNav
char label[128];
sprintf(label, "MyObject %d", i);
if (ImGui.Selectable(label, selected == i))
selected = i;
end
ImGui.EndChild();
end
ImGui.SameLine();
-- Rightthen
ImGui.BeginGroup();
ImGui.BeginChild("item view", ImVec2(0, -ImGui.GetFrameHeightWithSpacing())); -- Leave room for 1 line below us
ImGui.Text("MyObject: %d", selected);
ImGui.Separator();
if (ImGui.BeginTabBar("----Tabs", ImGuiTabBarFlags_None))then
if (ImGui.BeginTabItem("Description"))then
ImGui.TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ");
ImGui.EndTabItem();
end
if (ImGui.BeginTabItem("Details"))then
ImGui.Text("ID: 0123456789");
ImGui.EndTabItem();
end
ImGui.EndTabBar();
end
ImGui.EndChild();
if (ImGui.Button("Revert")) do end
ImGui.SameLine();
if (ImGui.Button("Save")) do end
ImGui.EndGroup();
end
end
ImGui.End();
end
-------------------------------------------------------------------------------
-- [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor()
-------------------------------------------------------------------------------
function ShowPlaceholderObject(const char* prefix, int uid)
-- Use object uid as identifier. Most commonly you could also use the object pointer as a base ID.
ImGui.PushID(uid);
-- Text and Tree nodes are less high than framed widgets, using AlignTextToFramePadding() we add vertical spacing to make the tree lines equal high.
ImGui.TableNextRow();
ImGui.TableSetColumnIndex(0);
ImGui.AlignTextToFramePadding();
bool node_open = ImGui.TreeNode("Object", "%s_%u", prefix, uid);
ImGui.TableSetColumnIndex(1);
ImGui.Text("my sailor is rich");
if (node_open)then
static float placeholder_members[8] = do 0.0, 0.0, 1.0, 3.1416f, 100.0, 999.0 end;
for (int i = 0; i < 8; i++)then
ImGui.PushID(i); -- Use field index as identifier.
if (i < 2)then
ShowPlaceholderObject("Child", 424242);
end
elsethen
-- Here we use a TreeNode to highlight on hover (we could use e.g. Selectable as well)
ImGui.TableNextRow();
ImGui.TableSetColumnIndex(0);
ImGui.AlignTextToFramePadding();
ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_Bullet;
ImGui.TreeNodeEx("Field", flags, "Field_%d", i);
ImGui.TableSetColumnIndex(1);
ImGui.SetNextItemWidth(-FLT_MIN);
if (i >= 5)
ImGui.InputFloat("----value", placeholder_members[i], 1.0);
else
ImGui.DragFloat("----value", placeholder_members[i], 0.01f);
ImGui.NextColumn();
end
ImGui.PopID();
end
ImGui.TreePop();
end
ImGui.PopID();
end
-- Demonstrate create a simple property editor.
function ShowExampleAppPropertyEditor(bool* p_open)
ImGui.SetNextWindowSize(ImVec2(430, 450), ImGuiCond_FirstUseEver);
if (not ImGui.Begin("Example: Property editor", p_open))then
ImGui.End();
return;
end
HelpMarker(
"This example shows how you may implement a property editor using two columns.\n"
"All objects/fields data are dummies here.\n"
"Remember that in many simple cases, you can use ImGui.SameLine(xxx) to position\n"
"your cursor horizontally instead of using the Columns() API.");
ImGui.PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 2));
if (ImGui.BeginTable("split", 2, ImGuiTableFlags_BordersOuter | ImGuiTableFlags_Resizable))then
-- Iterate placeholder objects (all the same data)
for (int obj_i = 0; obj_i < 4; obj_i++)then
ShowPlaceholderObject("Object", obj_i);
--ImGui.Separator();
end
ImGui.EndTable();
end
ImGui.PopStyleVar();
ImGui.End();
end
-------------------------------------------------------------------------------
-- [SECTION] Example App: Long Text / ShowExampleAppLongText()
-------------------------------------------------------------------------------
-- Demonstrate/test rendering huge amount of text, and the incidence of clipping.
function ShowExampleAppLongText(bool* p_open)
ImGui.SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver);
if (not ImGui.Begin("Example: Long text display", p_open))then
ImGui.End();
return;
end
static int test_type = 0;
static ImGuiTextBuffer log;
static int lines = 0;
ImGui.Text("Printing unusually long amount of text.");
ImGui.Combo("Test type", test_type,
"Single call to TextUnformatted()\0"
"Multiple calls to Text(), clipped\0"
"Multiple calls to Text(), not clipped (slow)\0");
ImGui.Text("Buffer contents: %d lines, %d bytes", lines, log.size());
if (ImGui.Button("Clear")) do log.clear(); lines = 0; end
ImGui.SameLine();
if (ImGui.Button("Add 1000 lines"))then
for (int i = 0; i < 1000; i++)
log.appendf("%i The quick brown fox jumps over the lazy dog\n", lines + i);
lines += 1000;
end
ImGui.BeginChild("Log");
switch (test_type)then
case 0:
-- Single call to TextUnformatted() with a big buffer
ImGui.TextUnformatted(log.begin(), log.end());
break;
case 1:then
-- Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper.
ImGui.PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
ImGuiListClipper clipper;
clipper.Begin(lines);
while (clipper.Step())
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
ImGui.Text("%i The quick brown fox jumps over the lazy dog", i);
ImGui.PopStyleVar();
break;
end
case 2:
-- Multiple calls to Text(), not clipped (slow)
ImGui.PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
for (int i = 0; i < lines; i++)
ImGui.Text("%i The quick brown fox jumps over the lazy dog", i);
ImGui.PopStyleVar();
break;
end
ImGui.EndChild();
ImGui.End();
end
-------------------------------------------------------------------------------
-- [SECTION] Example App: Auto Resize / ShowExampleAppAutoResize()
-------------------------------------------------------------------------------
-- Demonstrate creating a window which gets auto-resized according to its content.
function ShowExampleAppAutoResize(bool* p_open)
if (not ImGui.Begin("Example: Auto-resizing window", p_open, ImGuiWindowFlags_AlwaysAutoResize))then
ImGui.End();
return;
end
static int lines = 10;
ImGui.TextUnformatted(
"Window will resize every-frame to the size of its content.\n"
"Note that you probably don't want to query the window size to\n"
"output your content because that would create a feedback loop.");
ImGui.SliderInt("Number of lines", lines, 1, 20);
for (int i = 0; i < lines; i++)
ImGui.Text("%*sThis is line %d", i * 4, "", i); -- Pad with space to extend size horizontally
ImGui.End();
end
-------------------------------------------------------------------------------
-- [SECTION] Example App: Constrained Resize / ShowExampleAppConstrainedResize()
-------------------------------------------------------------------------------
-- Demonstrate creating a window with custom resize constraints.
function ShowExampleAppConstrainedResize(bool* p_open)
struct CustomConstraintsthen
-- Helper functions to demonstrate programmatic constraints
function Square(ImGuiSizeCallbackData* data) do data->DesiredSize.x = data->DesiredSize.y = IM_MAX(data->DesiredSize.x, data->DesiredSize.y); end
function Step(ImGuiSizeCallbackData* data) do float step = (float)(int)(intptr_t)data->UserData; data->DesiredSize = ImVec2((int)(data->DesiredSize.x / step + 0.5f) * step, (int)(data->DesiredSize.y / step + 0.5f) * step); end
end;
const char* test_desc[] =then
"Resize vertical only",
"Resize horizontal only",
"Width > 100, Height > 100",
"Width 400-500",
"Height 400-500",
"Custom: Always Square",
"Custom: Fixed Steps (100)",
end;
local auto_resize = false;
static int type = 0;
static int display_lines = 10;
if (type == 0) ImGui.SetNextWindowSizeConstraints(ImVec2(-1, 0), ImVec2(-1, FLT_MAX)); -- Vertical only
if (type == 1) ImGui.SetNextWindowSizeConstraints(ImVec2(0, -1), ImVec2(FLT_MAX, -1)); -- Horizontal only
if (type == 2) ImGui.SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(FLT_MAX, FLT_MAX)); -- Width > 100, Height > 100
if (type == 3) ImGui.SetNextWindowSizeConstraints(ImVec2(400, -1), ImVec2(500, -1)); -- Width 400-500
if (type == 4) ImGui.SetNextWindowSizeConstraints(ImVec2(-1, 400), ImVec2(-1, 500)); -- Height 400-500
if (type == 5) ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints.Square); -- Always Square
if (type == 6) ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints.Step, (void*)(intptr_t)100); -- Fixed Step
ImGuiWindowFlags flags = auto_resize ? ImGuiWindowFlags_AlwaysAutoResize : 0;
if (ImGui.Begin("Example: Constrained Resize", p_open, flags))then
if (ImGui.IsWindowDocked())
ImGui.Text("Warning: Sizing Constraints won't work if the window is dockednot ");
if (ImGui.Button("200x200")) do ImGui.SetWindowSize(ImVec2(200, 200)); end ImGui.SameLine();
if (ImGui.Button("500x500")) do ImGui.SetWindowSize(ImVec2(500, 500)); end ImGui.SameLine();
if (ImGui.Button("800x200")) do ImGui.SetWindowSize(ImVec2(800, 200)); end
ImGui.SetNextItemWidth(200);
ImGui.Combo("Constraint", type, test_desc, IM_ARRAYSIZE(test_desc));
ImGui.SetNextItemWidth(200);
ImGui.DragInt("Lines", display_lines, 0.2f, 1, 100);
ImGui.Checkbox("Auto-resize", auto_resize);
for (int i = 0; i < display_lines; i++)
ImGui.Text("%*sHello, sailornot Making this line long enough for the example.", i * 4, "");
end
ImGui.End();
end
-------------------------------------------------------------------------------
-- [SECTION] Example App: Simple overlay / ShowExampleAppSimpleOverlay()
-------------------------------------------------------------------------------
-- Demonstrate creating a simple static window with no decoration
-- + a context-menu to choose which corner of the screen to use.
function ShowExampleAppSimpleOverlay(bool* p_open)
static int corner = 0;
ImGuiIO& io = ImGui.GetIO();
ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav;
if (corner ~= -1)then
const float PAD = 10.0;
const ImGuiViewport* viewport = ImGui.GetMainViewport();
ImVec2 work_pos = viewport->WorkPos; -- Use work area to avoid menu-bar/task-bar, if anynot
ImVec2 work_size = viewport->WorkSize;
ImVec2 window_pos, window_pos_pivot;
window_pos.x = (corner & 1) ? (work_pos.x + work_size.x - PAD) : (work_pos.x + PAD);
window_pos.y = (corner & 2) ? (work_pos.y + work_size.y - PAD) : (work_pos.y + PAD);
window_pos_pivot.x = (corner & 1) ? 1.0 : 0.0;
window_pos_pivot.y = (corner & 2) ? 1.0 : 0.0;
ImGui.SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot);
ImGui.SetNextWindowViewport(viewport->ID);
window_flags |= ImGuiWindowFlags_NoMove;
end
ImGui.SetNextWindowBgAlpha(0.35f); -- Transparent background
if (ImGui.Begin("Example: Simple overlay", p_open, window_flags))then
ImGui.Text("Simple overlay\n" "in the corner of the screen.\n" "(right-click to change position)");
ImGui.Separator();
if (ImGui.IsMousePosValid())
ImGui.Text("Mouse Position: (%.1f,%.1f)", io.MousePos.x, io.MousePos.y);
else
ImGui.Text("Mouse Position: <invalid>");
if (ImGui.BeginPopupContextWindow())then
if (ImGui.MenuItem("Custom", NULL, corner == -1)) corner = -1;
if (ImGui.MenuItem("Top-left", NULL, corner == 0)) corner = 0;
if (ImGui.MenuItem("Top-right", NULL, corner == 1)) corner = 1;
if (ImGui.MenuItem("Bottom-left", NULL, corner == 2)) corner = 2;
if (ImGui.MenuItem("Bottom-right", NULL, corner == 3)) corner = 3;
if (p_open and ImGui.MenuItem("Close")) *p_open = false;
ImGui.EndPopup();
end
end
ImGui.End();
end
-------------------------------------------------------------------------------
-- [SECTION] Example App: Fullscreen window / ShowExampleAppFullscreen()
-------------------------------------------------------------------------------
-- Demonstrate creating a window covering the entire screen/viewport
function ShowExampleAppFullscreen(bool* p_open)
local use_work_area = true;
static ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
-- We demonstrate using the full viewport area or the work area (without menu-bars, task-bars etc.)
-- Based on your use case you may want one of the other.
const ImGuiViewport* viewport = ImGui.GetMainViewport();
ImGui.SetNextWindowPos(use_work_area ? viewport->WorkPos : viewport->Pos);
ImGui.SetNextWindowSize(use_work_area ? viewport->WorkSize : viewport->Size);
if (ImGui.Begin("Example: Fullscreen window", p_open, flags))then
ImGui.Checkbox("Use work area instead of main area", use_work_area);
ImGui.SameLine();
HelpMarker("Main Area = entire viewport,\nWork Area = entire viewport minus sections used by the main menu bars, task bars etc.\n\nEnable the main-menu bar in Examples menu to see the difference.");
ImGui.CheckboxFlags("ImGuiWindowFlags_NoBackground", flags, ImGuiWindowFlags_NoBackground);
ImGui.CheckboxFlags("ImGuiWindowFlags_NoDecoration", flags, ImGuiWindowFlags_NoDecoration);
ImGui.Indent();
ImGui.CheckboxFlags("ImGuiWindowFlags_NoTitleBar", flags, ImGuiWindowFlags_NoTitleBar);
ImGui.CheckboxFlags("ImGuiWindowFlags_NoCollapse", flags, ImGuiWindowFlags_NoCollapse);
ImGui.CheckboxFlags("ImGuiWindowFlags_NoScrollbar", flags, ImGuiWindowFlags_NoScrollbar);
ImGui.Unindent();
if (p_open and ImGui.Button("Close this window"))
*p_open = false;
end
ImGui.End();
end
-------------------------------------------------------------------------------
-- [SECTION] Example App: Manipulating Window Titles / ShowExampleAppWindowTitles()
-------------------------------------------------------------------------------
-- Demonstrate using "----" and "------" in identifiers to manipulate ID generation.
-- This apply to all regular items as well.
-- Read FAQ section "How can I have multiple widgets with the same label?" for details.
function ShowExampleAppWindowTitles(bool*)
const ImGuiViewport* viewport = ImGui.GetMainViewport();
const ImVec2 base_pos = viewport->Pos;
-- By default, Windows are uniquely identified by their title.
-- You can use the "----" and "------" markers to manipulate the display/ID.
-- Using "----" to display same title but have unique identifier.
ImGui.SetNextWindowPos(ImVec2(base_pos.x + 100, base_pos.y + 100), ImGuiCond_FirstUseEver);
ImGui.Begin("Same title as another window----1");
ImGui.Text("This is window 1.\nMy title is the same as window 2, but my identifier is unique.");
ImGui.End();
ImGui.SetNextWindowPos(ImVec2(base_pos.x + 100, base_pos.y + 200), ImGuiCond_FirstUseEver);
ImGui.Begin("Same title as another window----2");
ImGui.Text("This is window 2.\nMy title is the same as window 1, but my identifier is unique.");
ImGui.End();
-- Using "------" to display a changing title but keep a static identifier "AnimatedTitle"
char buf[128];
sprintf(buf, "Animated title %c %d------AnimatedTitle", "|/-\\"[(int)(ImGui.GetTime() / 0.25f) & 3], ImGui.GetFrameCount());
ImGui.SetNextWindowPos(ImVec2(base_pos.x + 100, base_pos.y + 300), ImGuiCond_FirstUseEver);
ImGui.Begin(buf);
ImGui.Text("This window has a changing title.");
ImGui.End();
end
-------------------------------------------------------------------------------
-- [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering()
-------------------------------------------------------------------------------
-- Demonstrate using the low-level ImDrawList to draw custom shapes.
function ShowExampleAppCustomRendering(bool* p_open)
if (not ImGui.Begin("Example: Custom rendering", p_open))then
ImGui.End();
return;
end
-- Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of
-- overloaded operators, etc. Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your
-- types and ImVec2/ImVec4. Dear ImGui defines overloaded operators but they are internal to imgui.cpp and not
-- exposed outside (to avoid messing with your types) In this example we are not using the maths operatorsnot
if (ImGui.BeginTabBar("----TabBar"))then
if (ImGui.BeginTabItem("Primitives"))then
ImGui.PushItemWidth(-ImGui.GetFontSize() * 15);
ImDrawList* draw_list = ImGui.GetWindowDrawList();
-- Draw gradients
-- (note that those are currently exacerbating our sRGB/Linear issues)
-- Calling ImGui.GetColorU32() multiplies the given colors by the current Style Alpha, but you may pass the IM_COL32() directly as well..
ImGui.Text("Gradients");
ImVec2 gradient_size = ImVec2(ImGui.CalcItemWidth(), ImGui.GetFrameHeight());then
ImVec2 p0 = ImGui.GetCursorScreenPos();
ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y);
ImU32 col_a = ImGui.GetColorU32(IM_COL32(0, 0, 0, 255));
ImU32 col_b = ImGui.GetColorU32(IM_COL32(255, 255, 255, 255));
draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a);
ImGui.InvisibleButton("----gradient1", gradient_size);
endthen
ImVec2 p0 = ImGui.GetCursorScreenPos();
ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y);
ImU32 col_a = ImGui.GetColorU32(IM_COL32(0, 255, 0, 255));
ImU32 col_b = ImGui.GetColorU32(IM_COL32(255, 0, 0, 255));
draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a);
ImGui.InvisibleButton("----gradient2", gradient_size);
end
-- Draw a bunch of primitives
ImGui.Text("All primitives");
static float sz = 36.0;
static float thickness = 3.0;
static int ngon_sides = 6;
local circle_segments_override = false;
static int circle_segments_override_v = 12;
local curve_segments_override = false;
static int curve_segments_override_v = 8;
static ImVec4 colf = ImVec4(1.0, 1.0, 0.4f, 1.0);
ImGui.DragFloat("Size", sz, 0.2f, 2.0, 100.0, "%.0");
ImGui.DragFloat("Thickness", thickness, 0.05f, 1.0, 8.0, "%.02f");
ImGui.SliderInt("N-gon sides", ngon_sides, 3, 12);
ImGui.Checkbox("----circlesegmentoverride", circle_segments_override);
ImGui.SameLine(0.0, ImGui.GetStyle().ItemInnerSpacing.x);
circle_segments_override |= ImGui.SliderInt("Circle segments override", circle_segments_override_v, 3, 40);
ImGui.Checkbox("----curvessegmentoverride", curve_segments_override);
ImGui.SameLine(0.0, ImGui.GetStyle().ItemInnerSpacing.x);
curve_segments_override |= ImGui.SliderInt("Curves segments override", curve_segments_override_v, 3, 40);
ImGui.ColorEdit4("Color", colf.x);
const ImVec2 p = ImGui.GetCursorScreenPos();
const ImU32 col = ImColor(colf);
const float spacing = 10.0;
const ImDrawFlags corners_tl_br = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersBottomRight;
const float rounding = sz / 5.0;
const int circle_segments = circle_segments_override ? circle_segments_override_v : 0;
const int curve_segments = curve_segments_override ? curve_segments_override_v : 0;
float x = p.x + 4.0;
float y = p.y + 4.0;
for (int n = 0; n < 2; n++)then
-- First line uses a thickness of 1.0, second line uses the configurable thickness
float th = (n == 0) ? 1.0 : thickness;
draw_list->AddNgon(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, ngon_sides, th); x += sz + spacing; -- N-gon
draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments, th); x += sz + spacing; -- Circle
draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0, ImDrawFlags_None, th); x += sz + spacing; -- Square
draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, ImDrawFlags_None, th); x += sz + spacing; -- Square with all rounded corners
draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, corners_tl_br, th); x += sz + spacing; -- Square with two rounded corners
draw_list->AddTriangle(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col, th);x += sz + spacing; -- Triangle
--draw_list->AddTriangle(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col, th);x+= sz*0.4f + spacing; -- Thin triangle
draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th); x += sz + spacing; -- Horizontal line (note: drawing a filled rectangle will be fasternot )
draw_list->AddLine(ImVec2(x, y), ImVec2(x, y + sz), col, th); x += spacing; -- Vertical line (note: drawing a filled rectangle will be fasternot )
draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col, th); x += sz + spacing; -- Diagonal line
-- Quadratic Bezier Curve (3 control points)
ImVec2 cp3[3] = do ImVec2(x, y + sz * 0.6f), ImVec2(x + sz * 0.5f, y - sz * 0.4f), ImVec2(x + sz, y + sz) end;
draw_list->AddBezierQuadratic(cp3[0], cp3[1], cp3[2], col, th, curve_segments); x += sz + spacing;
-- Cubic Bezier Curve (4 control points)
ImVec2 cp4[4] = do ImVec2(x, y), ImVec2(x + sz * 1.3f, y + sz * 0.3f), ImVec2(x + sz - sz * 1.3f, y + sz - sz * 0.3f), ImVec2(x + sz, y + sz) end;
draw_list->AddBezierCubic(cp4[0], cp4[1], cp4[2], cp4[3], col, th, curve_segments);
x = p.x + 4;
y += sz + spacing;
end
draw_list->AddNgonFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz*0.5f, col, ngon_sides); x += sz + spacing; -- N-gon
draw_list->AddCircleFilled(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments); x += sz + spacing; -- Circle
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col); x += sz + spacing; -- Square
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0); x += sz + spacing; -- Square with all rounded corners
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0, corners_tl_br); x += sz + spacing; -- Square with two rounded corners
draw_list->AddTriangleFilled(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col); x += sz + spacing; -- Triangle
--draw_list->AddTriangleFilled(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col); x += sz*0.4f + spacing; -- Thin triangle
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col); x += sz + spacing; -- Horizontal line (faster than AddLine, but only handle integer thickness)
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col); x += spacing * 2.0;-- Vertical line (faster than AddLine, but only handle integer thickness)
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + 1, y + 1), col); x += sz; -- Pixel (faster than AddLine)
draw_list->AddRectFilledMultiColor(ImVec2(x, y), ImVec2(x + sz, y + sz), IM_COL32(0, 0, 0, 255), IM_COL32(255, 0, 0, 255), IM_COL32(255, 255, 0, 255), IM_COL32(0, 255, 0, 255));
ImGui.Dummy(ImVec2((sz + spacing) * 10.2f, (sz + spacing) * 3.0));
ImGui.PopItemWidth();
ImGui.EndTabItem();
end
if (ImGui.BeginTabItem("Canvas"))then
static ImVector<ImVec2> points;
static ImVec2 scrolling(0.0, 0.0);
local opt_enable_grid = true;
local opt_enable_context_menu = true;
local adding_line = false;
ImGui.Checkbox("Enable grid", opt_enable_grid);
ImGui.Checkbox("Enable context menu", opt_enable_context_menu);
ImGui.Text("Mouse Left: drag to add lines,\nMouse Right: drag to scroll, click for context menu.");
-- Typically you would use a BeginChild()/EndChild() pair to benefit from a clipping region + own scrolling.
-- Here we demonstrate that this can be replaced by simple offsetting + custom drawing + PushClipRect/PopClipRect() calls.
-- To use a child window instead we could use, e.g:
-- ImGui.PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); -- Disable padding
-- ImGui.PushStyleColor(ImGuiCol_ChildBg, IM_COL32(50, 50, 50, 255)); -- Set a background color
-- ImGui.BeginChild("canvas", ImVec2(0.0, 0.0), true, ImGuiWindowFlags_NoMove);
-- ImGui.PopStyleColor();
-- ImGui.PopStyleVar();
-- [...]
-- ImGui.EndChild();
-- Using InvisibleButton() as a convenience 1) it will advance the layout cursor and 2) allows us to use IsItemHovered()/IsItemActive()
ImVec2 canvas_p0 = ImGui.GetCursorScreenPos(); -- ImDrawList API uses screen coordinatesnot
ImVec2 canvas_sz = ImGui.GetContentRegionAvail(); -- Resize canvas to what's available
if (canvas_sz.x < 50.0) canvas_sz.x = 50.0;
if (canvas_sz.y < 50.0) canvas_sz.y = 50.0;
ImVec2 canvas_p1 = ImVec2(canvas_p0.x + canvas_sz.x, canvas_p0.y + canvas_sz.y);
-- Draw border and background color
ImGuiIO& io = ImGui.GetIO();
ImDrawList* draw_list = ImGui.GetWindowDrawList();
draw_list->AddRectFilled(canvas_p0, canvas_p1, IM_COL32(50, 50, 50, 255));
draw_list->AddRect(canvas_p0, canvas_p1, IM_COL32(255, 255, 255, 255));
-- This will catch our interactions
ImGui.InvisibleButton("canvas", canvas_sz, ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight);
const bool is_hovered = ImGui.IsItemHovered(); -- Hovered
const bool is_active = ImGui.IsItemActive(); -- Held
const ImVec2 origin(canvas_p0.x + scrolling.x, canvas_p0.y + scrolling.y); -- Lock scrolled origin
const ImVec2 mouse_pos_in_canvas(io.MousePos.x - origin.x, io.MousePos.y - origin.y);
-- Add first and second point
if (is_hovered and not adding_line and ImGui.IsMouseClicked(ImGuiMouseButton_Left))then
points.push_back(mouse_pos_in_canvas);
points.push_back(mouse_pos_in_canvas);
adding_line = true;
end
if (adding_line)then
points.back() = mouse_pos_in_canvas;
if (not ImGui.IsMouseDown(ImGuiMouseButton_Left))
adding_line = false;
end
-- Pan (we use a zero mouse threshold when there's no context menu)
-- You may decide to make that threshold dynamic based on whether the mouse is hovering something etc.
const float mouse_threshold_for_pan = opt_enable_context_menu ? -1.0 : 0.0;
if (is_active and ImGui.IsMouseDragging(ImGuiMouseButton_Right, mouse_threshold_for_pan))then
scrolling.x += io.MouseDelta.x;
scrolling.y += io.MouseDelta.y;
end
-- Context menu (under default mouse threshold)
ImVec2 drag_delta = ImGui.GetMouseDragDelta(ImGuiMouseButton_Right);
if (opt_enable_context_menu and ImGui.IsMouseReleased(ImGuiMouseButton_Right) and drag_delta.x == 0.0 and drag_delta.y == 0.0)
ImGui.OpenPopupOnItemClick("context");
if (ImGui.BeginPopup("context"))then
if (adding_line)
points.resize(points.size() - 2);
adding_line = false;
if (ImGui.MenuItem("Remove one", NULL, false, points.Size > 0)) do points.resize(points.size() - 2); end
if (ImGui.MenuItem("Remove all", NULL, false, points.Size > 0)) do points.clear(); end
ImGui.EndPopup();
end
-- Draw grid + all lines in the canvas
draw_list->PushClipRect(canvas_p0, canvas_p1, true);
if (opt_enable_grid)then
const float GRID_STEP = 64.0;
for (float x = fmodf(scrolling.x, GRID_STEP); x < canvas_sz.x; x += GRID_STEP)
draw_list->AddLine(ImVec2(canvas_p0.x + x, canvas_p0.y), ImVec2(canvas_p0.x + x, canvas_p1.y), IM_COL32(200, 200, 200, 40));
for (float y = fmodf(scrolling.y, GRID_STEP); y < canvas_sz.y; y += GRID_STEP)
draw_list->AddLine(ImVec2(canvas_p0.x, canvas_p0.y + y), ImVec2(canvas_p1.x, canvas_p0.y + y), IM_COL32(200, 200, 200, 40));
end
for (int n = 0; n < points.Size; n += 2)
draw_list->AddLine(ImVec2(origin.x + points[n].x, origin.y + points[n].y), ImVec2(origin.x + points[n + 1].x, origin.y + points[n + 1].y), IM_COL32(255, 255, 0, 255), 2.0);
draw_list->PopClipRect();
ImGui.EndTabItem();
end
if (ImGui.BeginTabItem("BG/FG draw lists"))then
local draw_bg = true;
local draw_fg = true;
ImGui.Checkbox("Draw in Background draw list", draw_bg);
ImGui.SameLine(); HelpMarker("The Background draw list will be rendered below every Dear ImGui windows.");
ImGui.Checkbox("Draw in Foreground draw list", draw_fg);
ImGui.SameLine(); HelpMarker("The Foreground draw list will be rendered over every Dear ImGui windows.");
ImVec2 window_pos = ImGui.GetWindowPos();
ImVec2 window_size = ImGui.GetWindowSize();
ImVec2 window_center = ImVec2(window_pos.x + window_size.x * 0.5f, window_pos.y + window_size.y * 0.5f);
if (draw_bg)
ImGui.GetBackgroundDrawList()->AddCircle(window_center, window_size.x * 0.6f, IM_COL32(255, 0, 0, 200), 0, 10 + 4);
if (draw_fg)
ImGui.GetForegroundDrawList()->AddCircle(window_center, window_size.y * 0.6f, IM_COL32(0, 255, 0, 200), 0, 10);
ImGui.EndTabItem();
end
ImGui.EndTabBar();
end
ImGui.End();
end
-------------------------------------------------------------------------------
-- [SECTION] Example App: Docking, DockSpace / ShowExampleAppDockSpace()
-------------------------------------------------------------------------------
-- Demonstrate using DockSpace() to create an explicit docking node within an existing window.
-- Note: You can use most Docking facilities without calling any API. You DO NOT need to call DockSpace() to use Dockingnot
-- - Drag from window title bar or their tab to dock/undock. Hold SHIFT to disable docking.
-- - Drag from window menu button (upper-left button) to undock an entire node (all windows).
-- About dockspaces:
-- - Use DockSpace() to create an explicit dock node _within_ an existing window.
-- - Use DockSpaceOverViewport() to create an explicit dock node covering the screen or a specific viewport.
-- This is often used with ImGuiDockNodeFlags_PassthruCentralNode.
-- - Important: Dockspaces need to be submitted _before_ any window they can host. Submit it early in your framenot (*)
-- - Important: Dockspaces need to be kept alive if hidden, otherwise windows docked into it will be undocked.
-- e.g. if you have multiple tabs with a dockspace inside each tab: submit the non-visible dockspaces with ImGuiDockNodeFlags_KeepAliveOnly.
-- (*) because of this constraint, the implicit \"Debug\" window can not be docked into an explicit DockSpace() node,
-- because that window is submitted as part of the part of the NewFrame() call. An easy workaround is that you can create
-- your own implicit "Debug----2" window after calling DockSpace() and leave it in the window stack for anyone to use.
function ShowExampleAppDockSpace(bool* p_open)
-- If you strip some features of, this demo is pretty much equivalent to calling DockSpaceOverViewport()not
-- In most cases you should be able to just call DockSpaceOverViewport() and ignore all the code belownot
-- In this specific demo, we are not using DockSpaceOverViewport() because:
-- - we allow the host window to be floating/moveable instead of filling the viewport (when opt_fullscreen == false)
-- - we allow the host window to have padding (when opt_padding == true)
-- - we have a local menu bar in the host window (vs. you could use BeginMainMenuBar() + DockSpaceOverViewport() in your codenot )
-- TL;DR; this demo is more complicated than what you would normally use.
-- If we removed all the options we are showcasing, this demo would become:
-- void ShowExampleAppDockSpace()
-- then
-- ImGui.DockSpaceOverViewport(ImGui.GetMainViewport());
-- end
local opt_fullscreen = true;
local opt_padding = false;
static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None;
-- We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into,
-- because it would be confusing to have two docking targets within each others.
ImGuiWindowFlags window_flags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking;
if (opt_fullscreen)then
const ImGuiViewport* viewport = ImGui.GetMainViewport();
ImGui.SetNextWindowPos(viewport->WorkPos);
ImGui.SetNextWindowSize(viewport->WorkSize);
ImGui.SetNextWindowViewport(viewport->ID);
ImGui.PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0);
ImGui.PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0);
window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
end
elsethenthenckspace_flags &= ~ImGuiDockNodeFlags_PassthruCentralNode;
end
-- When using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our background
-- and handle the pass-thru hole, so we ask Begin() to not render a background.
if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
window_flags |= ImGuiWindowFlags_NoBackground;
-- Important: note that we proceed even if Begin() returns false (aka window is collapsed).
-- This is because we want to keep our DockSpace() active. If a DockSpace() is inactive,
-- all active windows docked into it will lose their parent and become undocked.
-- We cannot preserve the docking relationship between an active window and an inactive docking, otherwise
-- any change of dockspace/settings would lead to windows being stuck in limbo and never being visible.
if (not opt_padding)
ImGui.PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0, 0.0));
ImGui.Begin("DockSpace Demo", p_open, window_flags);
if (not opt_padding)
ImGui.PopStyleVar();
if (opt_fullscreen)
ImGui.PopStyleVar(2);
-- Submit the DockSpace
ImGuiIO& io = ImGui.GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable)then
ImGuiID dockspace_id = ImGui.GetID("MyDockSpace");
ImGui.DockSpace(dockspace_id, ImVec2(0.0, 0.0), dockspace_flags);
end
elsethen
ShowDockingDisabledMessage();
end
if (ImGui.BeginMenuBar())then
if (ImGui.BeginMenu("Options"))then
-- Disabling fullscreen would allow the window to be moved to the front of other windows,
-- which we can't undo at the moment without finer window depth/z control.
ImGui.MenuItem("Fullscreen", NULL, opt_fullscreen);
ImGui.MenuItem("Padding", NULL, opt_padding);
ImGui.Separator();
if (ImGui.MenuItem("Flag: NoSplit", "", (dockspace_flags & ImGuiDockNodeFlags_NoSplit) ~= 0)) then dockspace_flags ^= ImGuiDockNodeFlags_NoSplit; end
if (ImGui.MenuItem("Flag: NoResize", "", (dockspace_flags & ImGuiDockNodeFlags_NoResize) ~= 0)) then dockspace_flags ^= ImGuiDockNodeFlags_NoResize; end
if (ImGui.MenuItem("Flag: NoDockingInCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) ~= 0)) do dockspace_flags ^= ImGuiDockNodeFlags_NoDockingInCentralNode; end
if (ImGui.MenuItem("Flag: AutoHideTabBar", "", (dockspace_flags & ImGuiDockNodeFlags_AutoHideTabBar) ~= 0)) then dockspace_flags ^= ImGuiDockNodeFlags_AutoHideTabBar; end
if (ImGui.MenuItem("Flag: PassthruCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) ~= 0, opt_fullscreen)) do dockspace_flags ^= ImGuiDockNodeFlags_PassthruCentralNode; end
ImGui.Separator();
if (ImGui.MenuItem("Close", NULL, false, p_open ~= NULL))
*p_open = false;
ImGui.EndMenu();
end
HelpMarker(
"When docking is enabled, you can ALWAYS dock MOST window into anothernot Try it nownot " "\n"
"- Drag from window title bar or their tab to dock/undock." "\n"
"- Drag from window menu button (upper-left button) to undock an entire node (all windows)." "\n"
"- Hold SHIFT to disable docking." "\n"
"This demo app has nothing to do with itnot " "\n\n"
"This demo app only demonstrate the use of ImGui.DockSpace() which allows you to manually create a docking node _within_ another window." "\n\n"
"Read comments in ShowExampleAppDockSpace() for more details.");
ImGui.EndMenuBar();
end
ImGui.End();
end
-------------------------------------------------------------------------------
-- [SECTION] Example App: Documents Handling / ShowExampleAppDocuments()
-------------------------------------------------------------------------------
-- Simplified structure to mimic a Document model
struct MyDocument
const char* Name; -- Document title
bool Open; -- Set when open (we keep an array of all available documents to simplify demo codenot )
bool OpenPrev; -- Copy of Open from last update.
bool Dirty; -- Set when the document has been modified
bool WantClose; -- Set when the document
ImVec4 Color; -- An arbitrary variable associated to the document
MyDocument(const char* name, bool open = true, const ImVec4& color = ImVec4(1.0, 1.0, 1.0, 1.0))then
Name = name;
Open = OpenPrev = open;
Dirty = false;
WantClose = false;
Color = color;
end
void DoOpen() then Open = true; end
void DoQueueClose() do WantClose = true; end
void DoForceClose() do Open = false; Dirty = false; end
void DoSave() then Dirty = false; end
-- Display placeholder contents for the Document
function DisplayContents(MyDocument* doc)then
ImGui.PushID(doc);
ImGui.Text("Document \"%s\"", doc->Name);
ImGui.PushStyleColor(ImGuiCol_Text, doc->Color);
ImGui.TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
ImGui.PopStyleColor();
if (ImGui.Button("Modify", ImVec2(100, 0)))thenc->Dirty = true;
ImGui.SameLine();
if (ImGui.Button("Save", ImVec2(100, 0)))thenc->DoSave();
ImGui.ColorEdit3("color", doc->Color.x); -- Useful to test drag and drop and hold-dragged-to-open-tab behavior.
ImGui.PopID();
end
-- Display context menu for the Document
function DisplayContextMenu(MyDocument* doc)then
if (not ImGui.BeginPopupContextItem())
return;
char buf[256];
sprintf(buf, "Save %s", doc->Name);
if (ImGui.MenuItem(buf, "CTRL+S", false, doc->Open))thenc->DoSave();
if (ImGui.MenuItem("Close", "CTRL+W", false, doc->Open))thenc->DoQueueClose();
ImGui.EndPopup();
end
end;
struct ExampleAppDocuments
ImVector<MyDocument> Documents;
ExampleAppDocuments()thenthencuments.push_back(MyDocument("Lettuce", true, ImVec4(0.4f, 0.8f, 0.4f, 1.0)));thencuments.push_back(MyDocument("Eggplant", true, ImVec4(0.8f, 0.5f, 1.0, 1.0)));thencuments.push_back(MyDocument("Carrot", true, ImVec4(1.0, 0.8f, 0.5f, 1.0)));thencuments.push_back(MyDocument("Tomato", false, ImVec4(1.0, 0.3f, 0.4f, 1.0)));thencuments.push_back(MyDocument("A Rather Long Title", false));thencuments.push_back(MyDocument("Some Document", false));
end
end;
-- [Optional] Notify the system of Tabs/Windows closure that happened outside the regular tab interface.
-- If a tab has been closed programmatically (aka closed from another source such as the Checkbox() in the demo,
-- as opposed to clicking on the regular tab closing button) and stops being submitted, it will take a frame for
-- the tab bar to notice its absence. During this frame there will be a gap in the tab bar, and if the tab that has
-- disappeared was the selected one, the tab bar will report no selected tab during the frame. This will effectively
-- give the impression of a flicker for one frame.
-- We call SetTabItemClosed() to manually notify the Tab Bar or Docking system of removed tabs to avoid this glitch.
-- Note that this completely optional, and only affect tab bars with the ImGuiTabBarFlags_Reorderable flag.
function NotifyOfDocumentsClosedElsewhere(ExampleAppDocuments& app)
for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)then
MyDocument* doc = &app.Documents[doc_n];
if (not doc->Open and doc->OpenPrev)
ImGui.SetTabItemClosed(doc->Name);thenc->OpenPrev = doc->Open;
end
end
function ShowExampleAppDocuments(bool* p_open)
static ExampleAppDocuments app;
-- Options
enum Targetthen
Target_None,
Target_Tab, -- Create documents as local tab into a local tab bar
Target_DockSpaceAndWindow -- Create documents as regular windows, and create an embedded dockspace
end;
static Target opt_target = Target_Tab;
local opt_reorderable = true;
static ImGuiTabBarFlags opt_fitting_flags = ImGuiTabBarFlags_FittingPolicyDefault_;
-- When (opt_target == Target_DockSpaceAndWindow) there is the possibily that one of our child Document window (e.g. "Eggplant")
-- that we emit gets docked into the same spot as the parent window ("Example: Documents").
-- This would create a problematic feedback loop because selecting the "Eggplant" tab would make the "Example: Documents" tab
-- not visible, which in turn would stop submitting the "Eggplant" window.
-- We avoid this problem by submitting our documents window even if our parent window is not currently visible.
-- Another solution may be to make the "Example: Documents" window use the ImGuiWindowFlags_NoDocking.
bool window_contents_visible = ImGui.Begin("Example: Documents", p_open, ImGuiWindowFlags_MenuBar);
if (not window_contents_visible and opt_target ~= Target_DockSpaceAndWindow)then
ImGui.End();
return;
end
-- Menu
if (ImGui.BeginMenuBar())then
if (ImGui.BeginMenu("File"))then
int open_count = 0;
for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)
open_count += app.Documents[doc_n].Open ? 1 : 0;
if (ImGui.BeginMenu("Open", open_count < app.Documents.Size))then
for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)then
MyDocument* doc = &app.Documents[doc_n];
if (not doc->Open)
if (ImGui.MenuItem(doc->Name))thenc->DoOpen();
end
ImGui.EndMenu();
end
if (ImGui.MenuItem("Close All Documents", NULL, false, open_count > 0))
for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)
app.Documents[doc_n].DoQueueClose();
if (ImGui.MenuItem("Exit", "Alt+F4")) do end
ImGui.EndMenu();
end
ImGui.EndMenuBar();
end
-- [Debug] List documents with one checkbox for each
for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)then
MyDocument* doc = &app.Documents[doc_n];
if (doc_n > 0)
ImGui.SameLine();
ImGui.PushID(doc);
if (ImGui.Checkbox(doc->Name, doc->Open))
if (not doc->Open)thenc->DoForceClose();
ImGui.PopID();
end
ImGui.PushItemWidth(ImGui.GetFontSize() * 12);
ImGui.Combo("Output", (int*)&opt_target, "None\0TabBar+Tabs\0DockSpace+Window\0");
ImGui.PopItemWidth();
bool redock_all = false;
if (opt_target == Target_Tab) then ImGui.SameLine(); ImGui.Checkbox("Reorderable Tabs", opt_reorderable); end
if (opt_target == Target_DockSpaceAndWindow) do ImGui.SameLine(); redock_all = ImGui.Button("Redock all"); end
ImGui.Separator();
-- About the ImGuiWindowFlags_UnsavedDocument / ImGuiTabItemFlags_UnsavedDocument flags.
-- They have multiple effects:
-- - Display a dot next to the title.
-- - Tab is selected when clicking the X close button.
-- - Closure is not assumed (will wait for user to stop submitting the tab).
-- Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar.
-- We need to assume closure by default otherwise waiting for "lack of submission" on the next frame would leave an empty
-- hole for one-frame, both in the tab-bar and in tab-contents when closing a tab/window.
-- The rarely used SetTabItemClosed() function is a way to notify of programmatic closure to avoid the one-frame hole.
-- Tabs
if (opt_target == Target_Tab)then
ImGuiTabBarFlags tab_bar_flags = (opt_fitting_flags) | (opt_reorderable ? ImGuiTabBarFlags_Reorderable : 0);
if (ImGui.BeginTabBar("----tabs", tab_bar_flags))then
if (opt_reorderable)
NotifyOfDocumentsClosedElsewhere(app);
-- [DEBUG] Stress tests
--if ((ImGui.GetFrameCount() % 30) == 0) docs[1].Open ^= 1; -- [DEBUG] Automatically show/hide a tab. Test various interactions e.g. dragging with this on.
--if (ImGui.GetIO().KeyCtrl) ImGui.SetTabItemSelected(docs[1].Name); -- [DEBUG] Test SetTabItemSelected(), probably not very useful as-is anyway..
-- Submit Tabs
for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)then
MyDocument* doc = &app.Documents[doc_n];
if (not doc->Open)
continue;
ImGuiTabItemFlags tab_flags = (doc->Dirty ? ImGuiTabItemFlags_UnsavedDocument : 0);
bool visible = ImGui.BeginTabItem(doc->Name, doc->Open, tab_flags);
-- Cancel attempt to close when unsaved add to save queue so we can display a popup.
if (not doc->Open and doc->Dirty)thenthenc->Open = true;thenc->DoQueueClose();
end
MyDocument.DisplayContextMenu(doc);
if (visible)then
MyDocument.DisplayContents(doc);
ImGui.EndTabItem();
end
end
ImGui.EndTabBar();
end
end
else if (opt_target == Target_DockSpaceAndWindow)then
if (ImGui.GetIO().ConfigFlags & ImGuiConfigFlags_DockingEnable)then
NotifyOfDocumentsClosedElsewhere(app);
-- Create a DockSpace node where any window can be docked
ImGuiID dockspace_id = ImGui.GetID("MyDockSpace");
ImGui.DockSpace(dockspace_id);
-- Create Windows
for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)then
MyDocument* doc = &app.Documents[doc_n];
if (not doc->Open)
continue;
ImGui.SetNextWindowDockID(dockspace_id, redock_all ? ImGuiCond_Always : ImGuiCond_FirstUseEver);
ImGuiWindowFlags window_flags = (doc->Dirty ? ImGuiWindowFlags_UnsavedDocument : 0);
bool visible = ImGui.Begin(doc->Name, doc->Open, window_flags);
-- Cancel attempt to close when unsaved add to save queue so we can display a popup.
if (not doc->Open and doc->Dirty)thenthenc->Open = true;thenc->DoQueueClose();
end
MyDocument.DisplayContextMenu(doc);
if (visible)
MyDocument.DisplayContents(doc);
ImGui.End();
end
end
elsethen
ShowDockingDisabledMessage();
end
end
-- Early out other contents
if (not window_contents_visible)then
ImGui.End();
return;
end
-- Update closing queue
static ImVector<MyDocument*> close_queue;
if (close_queue.empty())then
-- Close queue is locked once we started a popup
for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)then
MyDocument* doc = &app.Documents[doc_n];
if (doc->WantClose)thenthenc->WantClose = false;
close_queue.push_back(doc);
end
end
end
-- Display closing confirmation UI
if (not close_queue.empty())then
int close_queue_unsaved_documents = 0;
for (int n = 0; n < close_queue.Size; n++)
if (close_queue[n]->Dirty)
close_queue_unsaved_documents++;
if (close_queue_unsaved_documents == 0)then
-- Close documents when all are unsaved
for (int n = 0; n < close_queue.Size; n++)
close_queue[n]->DoForceClose();
close_queue.clear();
end
elsethen
if (not ImGui.IsPopupOpen("Save?"))
ImGui.OpenPopup("Save?");
if (ImGui.BeginPopupModal("Save?", NULL, ImGuiWindowFlags_AlwaysAutoResize))then
ImGui.Text("Save change to the following items?");
float item_height = ImGui.GetTextLineHeightWithSpacing();
if (ImGui.BeginChildFrame(ImGui.GetID("frame"), ImVec2(-FLT_MIN, 6.25f * item_height)))then
for (int n = 0; n < close_queue.Size; n++)
if (close_queue[n]->Dirty)
ImGui.Text("%s", close_queue[n]->Name);
ImGui.EndChildFrame();
end
ImVec2 button_size(ImGui.GetFontSize() * 7.0, 0.0);
if (ImGui.Button("Yes", button_size))then
for (int n = 0; n < close_queue.Size; n++)then
if (close_queue[n]->Dirty)
close_queue[n]->DoSave();
close_queue[n]->DoForceClose();
end
close_queue.clear();
ImGui.CloseCurrentPopup();
end
ImGui.SameLine();
if (ImGui.Button("No", button_size))then
for (int n = 0; n < close_queue.Size; n++)
close_queue[n]->DoForceClose();
close_queue.clear();
ImGui.CloseCurrentPopup();
end
ImGui.SameLine();
if (ImGui.Button("Cancel", button_size))then
close_queue.clear();
ImGui.CloseCurrentPopup();
end
ImGui.EndPopup();
end
end
end
ImGui.End();
end
|
-- /user/bin/python
local pythonPath = '/home/dave/anaconda3/bin/python'
vim.api.nvim_command("command! LspFormat lua vim.lsp.buf.formatting_sync(nil, 1000)")
-- vim.api.nvim_command("command! -range LspFormat '<,'> lua vim.lsp.buf.range_formatting()")
-- require('dap-python').setup('~/.virtualenvs/debugpy/bin/python')
-- require('dap-python').setup('/home/dave/anaconda3/bin/python')
local dap = require('dap')
dap.adapters.python = {
type = 'executable';
-- command = 'path/to/virtualenvs/debugpy/bin/python';
command = pythonPath;
args = { '-m', 'debugpy.adapter' };
}
dap.configurations.python = {
{
-- The first three options are required by nvim-dap
type = 'python'; -- the type here established the link to the adapter definition: `dap.adapters.python`
request = 'launch';
name = "Launch file";
-- Options below are for debugpy, see https://github.com/microsoft/debugpy/wiki/Debug-configuration-settings for supported options
program = "${file}"; -- This configuration will launch the current file if used.
pythonPath = function()
-- debugpy supports launching an application with a different interpreter then the one used to launch debugpy itself.
-- The code below looks for a `venv` or `.venv` folder in the current directly and uses the python within.
-- You could adapt this - to for example use the `VIRTUAL_ENV` environment variable.
local cwd = vim.fn.getcwd()
if vim.fn.executable(cwd .. '/venv/bin/python') == 1 then
return cwd .. '/venv/bin/python'
elseif vim.fn.executable(cwd .. '/.venv/bin/python') == 1 then
return cwd .. '/.venv/bin/python'
else
-- return '/usr/bin/python'
return pythonPath
end
end;
},
}
local dap_install = require "dap-install"
dap_install.config("python", {})
local opts = {
root_dir = function(fname)
local util = require "lspconfig.util"
local root_files = {
"pyproject.toml",
"setup.py",
"setup.cfg",
"requirements.txt",
"Pipfile",
"manage.py",
"pyrightconfig.json",
}
return util.root_pattern(unpack(root_files))(fname) or util.root_pattern ".git"(fname) or util.path.dirname(fname)
end,
settings = {
pyright = {
disableLanguageServices = false,
disableOrganizeImports = false,
},
python = {
analysis = {
autoSearchPaths = true,
diagnosticMode = "workspace",
useLibraryCodeForTypes = true,
},
},
},
single_file_support = true,
}
local servers = require "nvim-lsp-installer.servers"
local server_available, requested_server = servers.get_server "pyright"
if server_available then
opts.cmd_env = requested_server:get_default_options().cmd_env
end
require("lvim.lsp.manager").setup("pyright", opts)
|
ITEM.name = "Casual Cloth (Manual)"
ITEM.desc = "Manually Created Cloth"
ITEM.sheet = {1, 15} -- sheetdata [1]<male> index [2]<fancy>
ITEM.isCloth = true
|
if (AAPClassic.Faction == "Horde") then
AAPClassic.PathH2 = {
--------- 30-32 Stranglethorn Vale & Thousand Needles ---
["30-32STV-TN"] = {
{
["PickUp"] = {
194, -- [1]
},
["TT"] = {
["y"] = -11628.3,
["x"] = -55.2,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [1]
{
["PickUp"] = {
185, -- [1]
},
["TT"] = {
["y"] = -11620.6,
["x"] = -52,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [2]
{
["PickUp"] = {
190, -- [1]
},
["TT"] = {
["y"] = -11617.4,
["x"] = -48.4,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [3]
{
["Qpart"] = {
[185] = {
["1"] = "1",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -11579.6,
["x"] = 142.1,
},
["Range"] = 126.58,
["TT"] = {
["y"] = -11579.6,
["x"] = 142.1,
},
}, -- [4]
{
["Done"] = {
185, -- [1]
},
["TT"] = {
["y"] = -11620.5,
["x"] = -51.7,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [5]
{
["PickUp"] = {
186, -- [1]
},
["TT"] = {
["y"] = -11620.5,
["x"] = -51.7,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [6]
{
["Qpart"] = {
[190] = {
["1"] = "1",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -11597,
["x"] = -446.6,
},
["Range"] = 87.21,
["TT"] = {
["y"] = -11597,
["x"] = -446.6,
},
}, -- [7]
{
["Qpart"] = {
[186] = {
["1"] = "1",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -11821.6,
["x"] = -774.6,
},
["Range"] = 66.94,
["TT"] = {
["y"] = -11821.6,
["x"] = -774.6,
},
}, -- [8]
{
["Done"] = {
190, -- [1]
186, -- [2]
},
["TT"] = {
["y"] = -11620.9,
["x"] = -51.4,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [9]
{
["PickUp"] = {
191, -- [1]
187, -- [2]
},
["TT"] = {
["y"] = -11619.1,
["x"] = -50.4,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [10]
{
["Qpart"] = {
[191] = {
["1"] = "1",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -11583.7,
["x"] = 340.5,
},
["Range"] = 69.04,
["TT"] = {
["y"] = -11583.7,
["x"] = 340.5,
},
}, -- [11]
{
["Qpart"] = {
[194] = {
["1"] = "1",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -11846.6,
["x"] = 598.4,
},
["Range"] = 60.31,
["TT"] = {
["y"] = -11846.6,
["x"] = 598.4,
},
}, -- [12]
{
["Done"] = {
191, -- [1]
194, -- [2]
},
["TT"] = {
["y"] = -11621.1,
["x"] = -50.8,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [13]
{
["PickUp"] = {
195, -- [1]
},
["TT"] = {
["y"] = -11628.2,
["x"] = -54.6,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [14]
{
["PickUp"] = {
192, -- [1]
},
["TT"] = {
["y"] = -11617.7,
["x"] = -48.4,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [15]
{
["TT"] = {
["y"] = -11617.7,
["x"] = -48.4,
},
["xp"] = 1,
["Trigger"] = {
["y"] = -11617.7,
["x"] = -48.4,
},
["level"] = 31,
["Range"] = 442.15,
["Grind"] = 11951,
}, -- [16]
{
["TT"] = {
["y"] = -11622.5,
["x"] = -53.9,
},
["UseHS"] = 1361,
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [17]
{
["TT"] = {
["y"] = 1676.3,
["x"] = -4313.9,
},
["UseFlightPath"] = 1361,
["Name"] = "Crossroads, The Barrens",
["Zone"] = "1637 (Orgrimmar)",
}, -- [18]
{
["PickUp"] = {
1145, -- [1]
},
["TT"] = {
["y"] = -389.6,
["x"] = -2552.8,
},
["Zone"] = "17 (The Barrens)",
}, -- [19]
{
["Done"] = {
1361, -- [1]
},
["TT"] = {
["y"] = -307.3,
["x"] = -1971.9,
},
["Zone"] = "17 (The Barrens)",
}, -- [20]
{
["PickUp"] = {
1362, -- [1]
},
["TT"] = {
["y"] = -307.3,
["x"] = -1971.9,
},
["Zone"] = "17 (The Barrens)",
}, -- [21]
{
["TT"] = {
["y"] = -437.2,
["x"] = -2595.7,
},
["UseFlightPath"] = 1110,
["Name"] = "Freewind Post, Thousand Needles",
["Zone"] = "17 (The Barrens)",
}, -- [22]
{
["ExtraLine"] = "Time for Shimmering Flats",
["CRange"] = 1110,
["Zone"] = "400 (Thousand Needles)",
["Trigger"] = {
["y"] = -5813,
["x"] = -3434.5,
},
["LeaveQuests"] = {
4021, -- [1]
701, -- [2]
671, -- [3]
},
["Range"] = 111.44,
["TT"] = {
["y"] = -5813,
["x"] = -3434.5,
},
}, -- [23]
{
["PickUp"] = {
1110, -- [1]
},
["TT"] = {
["y"] = -6233.1,
["x"] = -3855.5,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [24]
{
["PickUp"] = {
1104, -- [1]
1105, -- [2]
},
["TT"] = {
["y"] = -6228.5,
["x"] = -3869.9,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [25]
{
["PickUp"] = {
1176, -- [1]
},
["TT"] = {
["y"] = -6192.3,
["x"] = -3961.1,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [26]
{
["PickUp"] = {
1175, -- [1]
},
["TT"] = {
["y"] = -6251.6,
["x"] = -4025.6,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [27]
{
["Qpart"] = {
[1104] = {
["1"] = "1",
},
[1105] = {
["1"] = "1",
},
[1176] = {
["1"] = "1",
},
[1110] = {
["1"] = "1",
},
[1175] = {
["1"] = "1",
["3"] = "3",
["2"] = "2",
},
},
["Zone"] = "400 (Thousand Needles)",
["Trigger"] = {
["y"] = -6251.6,
["x"] = -4025.6,
},
["Range"] = 767.69,
["TT"] = {
["y"] = -6251.6,
["x"] = -4025.6,
},
}, -- [28]
{
["Done"] = {
1110, -- [1]
},
["TT"] = {
["y"] = -6232.8,
["x"] = -3856.4,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [29]
{
["PickUp"] = {
5762, -- [1]
1111, -- [2]
},
["TT"] = {
["y"] = -6232.8,
["x"] = -3856.4,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [30]
{
["Done"] = {
1104, -- [1]
1105, -- [2]
},
["TT"] = {
["y"] = -6228.8,
["x"] = -3870.2,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [31]
{
["Done"] = {
1176, -- [1]
},
["TT"] = {
["y"] = -6190.9,
["x"] = -3960.7,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [32]
{
["PickUp"] = {
1178, -- [1]
},
["TT"] = {
["y"] = -6190.9,
["x"] = -3960.7,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [33]
{
["Done"] = {
1175, -- [1]
},
["TT"] = {
["y"] = -6253,
["x"] = -4025.4,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [34]
{
["TT"] = {
["y"] = -6253,
["x"] = -4025.4,
},
["xp"] = 1,
["Trigger"] = {
["y"] = -6253,
["x"] = -4025.4,
},
["level"] = 32,
["Range"] = 442.15,
["Grind"] = 11951,
}, -- [35]
{
["ExtraLine"] = "Go to Tanaris",
["CRange"] = 1145,
["Zone"] = "400 (Thousand Needles)",
["Trigger"] = {
["y"] = -6715.6,
["x"] = -3700.9,
},
["Range"] = 28.9,
["TT"] = {
["y"] = -6715.6,
["x"] = -3700.9,
},
}, -- [36]
{
["CRange"] = 1145,
["Zone"] = "440 (Tanaris)",
["Trigger"] = {
["y"] = -6891.7,
["x"] = -3774.5,
},
["Range"] = 22.41,
["TT"] = {
["y"] = -6891.7,
["x"] = -3774.5,
},
}, -- [37]
{
["TT"] = {
["y"] = -7045.1,
["x"] = -3779.4,
},
["UseFlightPath"] = 1145,
["Name"] = "Freewind Post, Thousand Needles",
["Zone"] = "440 (Tanaris)",
}, -- [38]
{
["PickUp"] = {
5361, -- [1]
},
["TT"] = {
["y"] = -5454.8,
["x"] = -2442.8,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [39]
{
["TT"] = {
["y"] = -5454.8,
["x"] = -2442.8,
},
["UseHS"] = 1145,
["Zone"] = "400 (Thousand Needles)",
}, -- [40]
{
["TT"] = {
["y"] = 1953.8,
["x"] = -4735.7,
},
["Done"] = {
1145, -- [1]
},
["LeaveQuests"] = {
1106, -- [1]
1107, -- [2]
},
["Zone"] = "1637 (Orgrimmar)",
}, -- [41]
{
["UpdMapID"] = 1,
},
},
--------- 32-34 Desolace ---
["32-34Desolace"] = {
{
["PickUp"] = {
1146, -- [1]
},
["TT"] = {
["y"] = 1953.8,
["x"] = -4735.8,
},
["Zone"] = "1637 (Orgrimmar)",
}, -- [1]
{
["ExtraLine"] = "Go to Cleft of shadows",
["CRange"] = 1362,
["Zone"] = "1637 (Orgrimmar)",
["Trigger"] = {
["y"] = 1891.7,
["x"] = -4476.3,
},
["Range"] = 14.52,
["TT"] = {
["y"] = 1891.7,
["x"] = -4476.3,
},
}, -- [2]
{
["CRange"] = 1362,
["Zone"] = "1637 (Orgrimmar)",
["Trigger"] = {
["y"] = 1840.7,
["x"] = -4401.4,
},
["Range"] = 15.83,
["TT"] = {
["y"] = 1840.7,
["x"] = -4401.4,
},
}, -- [3]
{
["PickUp"] = {
1431, -- [1]
},
["Zone"] = "1637 (Orgrimmar)",
["RaidIcon"] = 5639,
["ExtraLine"] = "Craven Patrols",
["TT"] = {
["y"] = 1799.4,
["x"] = -4333.9,
},
}, -- [4]
{
["CRange"] = 1431,
["Zone"] = "1637 (Orgrimmar)",
["Trigger"] = {
["y"] = 1740.3,
["x"] = -4293.1,
},
["Range"] = 15.86,
["TT"] = {
["y"] = 1740.3,
["x"] = -4293.1,
},
}, -- [5]
{
["CRange"] = 1431,
["Zone"] = "1637 (Orgrimmar)",
["Trigger"] = {
["y"] = 1773.9,
["x"] = -4230,
},
["Range"] = 15.17,
["TT"] = {
["y"] = 1773.9,
["x"] = -4230,
},
}, -- [6]
{
["CRange"] = 1431,
["Zone"] = "1637 (Orgrimmar)",
["Trigger"] = {
["y"] = 1640.4,
["x"] = -4265.9,
},
["Range"] = 17.02,
["TT"] = {
["y"] = 1640.4,
["x"] = -4265.9,
},
}, -- [7]
{
["Done"] = {
1431, -- [1]
},
["TT"] = {
["y"] = 1780.5,
["x"] = -3997,
},
["Zone"] = "1637 (Orgrimmar)",
}, -- [8]
{
["PickUp"] = {
1432, -- [1]
},
["TT"] = {
["y"] = 1780.5,
["x"] = -3997,
},
["Zone"] = "1637 (Orgrimmar)",
}, -- [9]
{
["TT"] = {
["y"] = 1676.4,
["x"] = -4313.5,
},
["UseFlightPath"] = 1362,
["Name"] = "Sun Rock Retreat, Stonetalon Mountains",
["Zone"] = "1637 (Orgrimmar)",
}, -- [10]
{
["ExtraLine"] = "Time to go to Desolace",
["CRange"] = 1362,
["Zone"] = "406 (Stonetalon Mountains)",
["Trigger"] = {
["y"] = 844,
["x"] = 1074.5,
},
["Range"] = 18.81,
["TT"] = {
["y"] = 844,
["x"] = 1074.5,
},
}, -- [11]
{
["ExtraLine"] = "Time to go to Desolace",
["CRange"] = 1362,
["Zone"] = "406 (Stonetalon Mountains)",
["Trigger"] = {
["y"] = 783.7,
["x"] = 1126.9,
},
["Range"] = 19.71,
["TT"] = {
["y"] = 783.7,
["x"] = 1126.9,
},
}, -- [12]
{
["ExtraLine"] = "Time to go to Desolace",
["CRange"] = 1362,
["Zone"] = "406 (Stonetalon Mountains)",
["Trigger"] = {
["y"] = 449.3,
["x"] = 1768.7,
},
["Range"] = 17.03,
["TT"] = {
["y"] = 449.3,
["x"] = 1768.7,
},
}, -- [13]
{
["ExtraLine"] = "Time to go to Desolace",
["CRange"] = 1362,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = 271.1,
["x"] = 1831.7,
},
["Range"] = 18.43,
["TT"] = {
["y"] = 271.1,
["x"] = 1831.7,
},
}, -- [14]
{
["PickUp"] = {
5561, -- [1]
},
["TT"] = {
["y"] = -1402.9,
["x"] = 1496.8,
},
["Zone"] = "405 (Desolace)",
}, -- [15]
{
["ExtraLine"] = "Bring Kodos back to Smeed and talk to kodo",
["Qpart"] = {
[5561] = {
["1"] = "1",
},
},
["Button"] = 13892,
["Trigger"] = {
["y"] = -1439.6,
["x"] = 1768,
},
["ExtraLine2"] = "1 at a time",
["Range"] = 32.41,
["TT"] = {
["y"] = -1440.9,
["x"] = 1765.5,
},
}, -- [16]
{
["TT"] = {
["y"] = -1402.5,
["x"] = 1497.4,
},
["Done"] = {
5561, -- [1]
},
}, -- [17]
{
["CRange"] = 1362,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -1245.7,
["x"] = 1641.7,
},
["Range"] = 14.53,
["TT"] = {
["y"] = -1245.7,
["x"] = 1641.7,
},
}, -- [18]
{
["CRange"] = 1362,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -1263.7,
["x"] = 1699.3,
},
["Range"] = 19.67,
["TT"] = {
["y"] = -1263.7,
["x"] = 1699.3,
},
}, -- [19]
{
["Done"] = {
1362, -- [1]
},
["TT"] = {
["y"] = -1333.8,
["x"] = 1706.9,
},
["Zone"] = "405 (Desolace)",
}, -- [20]
{
["PickUp"] = {
1365, -- [1]
},
["TT"] = {
["y"] = -1333.8,
["x"] = 1706.9,
},
["Zone"] = "405 (Desolace)",
}, -- [21]
{
["PickUp"] = {
1368, -- [1]
},
["TT"] = {
["y"] = -1336.4,
["x"] = 1703.4,
},
["Zone"] = "405 (Desolace)",
}, -- [22]
{
["Done"] = {
5361, -- [1]
},
["TT"] = {
["y"] = -1221.6,
["x"] = 1741.5,
},
["Zone"] = "405 (Desolace)",
}, -- [23]
{
["Done"] = {
1432, -- [1]
},
["TT"] = {
["y"] = -1176.4,
["x"] = 1870.6,
},
["Zone"] = "405 (Desolace)",
}, -- [24]
{
["PickUp"] = {
1433, -- [1]
1434, -- [2]
},
["TT"] = {
["y"] = -1176.4,
["x"] = 1870.6,
},
["Zone"] = "405 (Desolace)",
}, -- [25]
{
["Done"] = {
1433, -- [1]
},
["TT"] = {
["y"] = -1150,
["x"] = 1885.4,
},
["Zone"] = "405 (Desolace)",
}, -- [26]
{
["PickUp"] = {
1435, -- [1]
},
["TT"] = {
["y"] = -1150,
["x"] = 1885.4,
},
["Zone"] = "405 (Desolace)",
}, -- [27]
{
["Qpart"] = {
[1365] = {
["1"] = "1",
},
},
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -793.6,
["x"] = 933.9,
},
["LeaveQuests"] = {
1367, -- [1]
},
["Range"] = 0.14,
["TT"] = {
["y"] = -795.6,
["x"] = 934.1,
},
}, -- [28]
{
["Qpart"] = {
[1368] = {
["1"] = "1",
},
},
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -1766.6,
["x"] = 1039.5,
},
["Range"] = 115.64,
["TT"] = {
["y"] = -1766.6,
["x"] = 1039.5,
},
}, -- [29]
{
["CRange"] = 1365,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -1247,
["x"] = 1634.1,
},
["Range"] = 17.7,
["TT"] = {
["y"] = -1247,
["x"] = 1634.1,
},
}, -- [30]
{
["Done"] = {
1365, -- [1]
},
["TT"] = {
["y"] = -1333.2,
["x"] = 1706,
},
["Zone"] = "405 (Desolace)",
}, -- [31]
{
["PickUp"] = {
1366, -- [1]
},
["TT"] = {
["y"] = -1333.2,
["x"] = 1706,
},
["Zone"] = "405 (Desolace)",
}, -- [32]
{
["CRange"] = 1368,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -1818.1,
["x"] = 2042.3,
},
["Range"] = 31.59,
["TT"] = {
["y"] = -1818.1,
["x"] = 2042.3,
},
}, -- [33]
{
["Done"] = {
1368, -- [1]
},
["TT"] = {
["y"] = -1923.8,
["x"] = 2604.6,
},
["Zone"] = "405 (Desolace)",
}, -- [34]
{
["PickUp"] = {
1370, -- [1]
},
["TT"] = {
["y"] = -1923.8,
["x"] = 2604.6,
},
["Zone"] = "405 (Desolace)",
}, -- [35]
{
["CRange"] = 1370,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -1792.1,
["x"] = 3049.4,
},
["Range"] = 19.23,
["TT"] = {
["y"] = -1792.1,
["x"] = 3049.4,
},
}, -- [36]
{
["PickUp"] = {
5763, -- [1]
},
["LeaveQuests"] = {
5386, -- [1]
1153, -- [2]
1150, -- [3]
},
["TT"] = {
["y"] = -1714.9,
["x"] = 3106.3,
},
["Zone"] = "405 (Desolace)",
}, -- [37]
{
["PickUp"] = {
5381, -- [1]
},
["TT"] = {
["y"] = -1593.2,
["x"] = 3072.9,
},
["Zone"] = "405 (Desolace)",
}, -- [38]
{
["SetHS"] = 5381,
["TT"] = {
["y"] = -1593.5,
["x"] = 3150.3,
},
["Zone"] = "405 (Desolace)",
}, -- [39]
{
["PickUp"] = {
6143, -- [1]
},
["TT"] = {
["y"] = -1732.8,
["x"] = 3185.1,
},
["Zone"] = "405 (Desolace)",
}, -- [40]
{
["PickUp"] = {
6142, -- [1]
},
["TT"] = {
["y"] = -1705.7,
["x"] = 3214.9,
},
["Zone"] = "405 (Desolace)",
}, -- [41]
{
["GetFP"] = 5381,
["TT"] = {
["y"] = -1770.2,
["x"] = 3262.7,
},
["Zone"] = "405 (Desolace)",
}, -- [42]
{
["ExtraLine"] = "Open Shellfish Traps",
["TT"] = {
["y"] = -1922.3,
["x"] = 3178,
},
["ItemID"] = 13545,
["Qid"] = 5381,
["Trigger"] = {
["y"] = -1922.3,
["x"] = 3178,
},
["Ammount"] = 10,
["Range"] = 72.88,
["ExtraQpart"] = "Shellfish",
}, -- [43]
{
["ExtraLine"] = "Handin to get Fish (don't sell or eat them)",
["TT"] = {
["y"] = -1740,
["x"] = 3224,
},
["ItemID"] = 13546,
["Qid"] = 5381,
["Trigger"] = {
["y"] = -1740,
["x"] = 3224,
},
["Ammount"] = 2,
["Range"] = 0.08,
["ExtraQpart"] = "Bloodbelly Fish",
}, -- [44]
{
["CRange"] = 1370,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -1641.4,
["x"] = 3234.8,
},
["Range"] = 19.49,
["TT"] = {
["y"] = -1641.4,
["x"] = 3234.8,
},
}, -- [45]
{
["CRange"] = 1370,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -1304.9,
["x"] = 3207.1,
},
["Range"] = 28.42,
["TT"] = {
["y"] = -1304.9,
["x"] = 3207.1,
},
}, -- [46]
{
["CRange"] = 1370,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -1020.4,
["x"] = 3178.5,
},
["Range"] = 24.92,
["TT"] = {
["y"] = -1020.4,
["x"] = 3178.5,
},
}, -- [47]
{
["CRange"] = 1370,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -857,
["x"] = 3105.5,
},
["Range"] = 23.98,
["TT"] = {
["y"] = -857,
["x"] = 3105.5,
},
}, -- [48]
{
["CRange"] = 1370,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -669.7,
["x"] = 2953.3,
},
["Range"] = 30.12,
["TT"] = {
["y"] = -669.7,
["x"] = 2953.3,
},
}, -- [49]
{
["PickUp"] = {
6161, -- [1]
},
["TT"] = {
["y"] = -460.7,
["x"] = 2611.9,
},
["Zone"] = "405 (Desolace)",
}, -- [50]
{
["CRange"] = 1370,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -560.1,
["x"] = 2401.8,
},
["Range"] = 10.52,
["TT"] = {
["y"] = -560.1,
["x"] = 2401.8,
},
}, -- [51]
{
["CRange"] = 1370,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -496.8,
["x"] = 2401.2,
},
["Range"] = 15.58,
["TT"] = {
["y"] = -496.8,
["x"] = 2401.2,
},
}, -- [52]
{
["PickUp"] = {
5741, -- [1]
},
["TT"] = {
["y"] = -362.7,
["x"] = 2485.1,
},
["Zone"] = "405 (Desolace)",
}, -- [53]
{
["CRange"] = 1370,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -527.7,
["x"] = 1932.8,
},
["Range"] = 18.38,
["TT"] = {
["y"] = -527.7,
["x"] = 1932.8,
},
}, -- [54]
{
["CRange"] = 1370,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -486.3,
["x"] = 1723,
},
["Range"] = 20.44,
["TT"] = {
["y"] = -486.3,
["x"] = 1723,
},
}, -- [55]
{
["CRange"] = 1370,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -433.5,
["x"] = 1714,
},
["Range"] = 7.41,
["TT"] = {
["y"] = -433.5,
["x"] = 1714,
},
}, -- [56]
{
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -451.7,
["x"] = 1752.3,
},
["Range"] = 0.09,
["ExtraLine"] = "Go up tower and kill Seer",
["Qpart"] = {
[5741] = {
["1"] = "1",
},
},
["Fillers"] = {
[1435] = {
["1"] = "1",
},
},
["ExtraLine2"] = "(Use Burning Gem to kill mobs)",
["Button"] = 6436,
["TT"] = {
["y"] = -451.7,
["x"] = 1752.3,
},
}, -- [57]
{
["ExtraLine"] = "(Use Burning Gem to kill mobs)",
["Button"] = 6436,
["CRange"] = 5741,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -383.6,
["x"] = 1737.6,
},
["Fillers"] = {
[1435] = {
["1"] = "1",
},
},
["Range"] = 5.51,
["TT"] = {
["y"] = -383.6,
["x"] = 1737.6,
},
}, -- [58]
{
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -346.3,
["x"] = 1763.2,
},
["Range"] = 0.07,
["ExtraLine"] = "Click crystal and kill Demon",
["Qpart"] = {
[5381] = {
["1"] = "1",
},
},
["Fillers"] = {
[1435] = {
["1"] = "1",
},
},
["ExtraLine2"] = "(Use Burning Gem to kill mobs)",
["Button"] = 6436,
["TT"] = {
["y"] = -346.3,
["x"] = 1763.2,
},
}, -- [59]
{
["ExtraLine"] = "Use Burning Gem to kill mobs",
["Qpart"] = {
[1435] = {
["1"] = "1",
},
},
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -344.9,
["x"] = 1758.8,
},
["Range"] = 87.18,
["TT"] = {
["y"] = -344.9,
["x"] = 1758.8,
},
}, -- [60]
{
["ExtraLine"] = "Kill Burning Blade mobs for the drop",
["TT"] = {
["y"] = -414.5,
["x"] = 1722.5,
},
["ItemID"] = 20310,
["Qid"] = 5741,
["Trigger"] = {
["y"] = -414.5,
["x"] = 1722.5,
},
["Ammount"] = 1,
["Range"] = 0.01,
["ExtraQpart"] = "Flayed Demon Skin",
}, -- [61]
{
["ExtraLine"] = "Click the Flayed Demon Skin",
["TT"] = {
["y"] = -415.1,
["x"] = 1722.1,
},
["PickUp"] = {
1480, -- [1]
},
["Zone"] = "405 (Desolace)",
}, -- [62]
{
["CRange"] = 1435,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -1242,
["x"] = 1662,
},
["Range"] = 14.49,
["TT"] = {
["y"] = -1242,
["x"] = 1662,
},
}, -- [63]
{
["Done"] = {
1480, -- [1]
1435, -- [2]
},
["TT"] = {
["y"] = -1150,
["x"] = 1884.8,
},
["Zone"] = "405 (Desolace)",
}, -- [64]
{
["PickUp"] = {
1481, -- [1]
},
["TT"] = {
["y"] = -1150,
["x"] = 1884.8,
},
["Zone"] = "405 (Desolace)",
}, -- [65]
{
["PickUp"] = {
5386, -- [1]
},
["TT"] = {
["y"] = -1220.6,
["x"] = 1742.5,
},
["Zone"] = "405 (Desolace)",
}, -- [66]
{
["Done"] = {
5386, -- [1]
},
["TT"] = {
["y"] = -1220.6,
["x"] = 1742.5,
},
["Zone"] = "405 (Desolace)",
}, -- [67]
{
["ExtraLine"] = "Kill Shadowstalkers for Scalp",
["Qpart"] = {
[1481] = {
["1"] = "1",
},
[1434] = {
["1"] = "1",
["4"] = "4",
["3"] = "3",
["2"] = "2",
},
},
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -101.6,
["x"] = 851.7,
},
["Range"] = 193.29,
["TT"] = {
["y"] = -101.6,
["x"] = 851.7,
},
}, -- [68]
{
["PickUp"] = {
5501, -- [1]
},
["TT"] = {
["y"] = -715.6,
["x"] = 1431.4,
},
["Zone"] = "405 (Desolace)",
}, -- [69]
{
["CRange"] = 1434,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -1241.7,
["x"] = 1660.8,
},
["Range"] = 15.55,
["TT"] = {
["y"] = -1241.7,
["x"] = 1660.8,
},
}, -- [70]
{
["Done"] = {
1434, -- [1]
},
["TT"] = {
["y"] = -1177.7,
["x"] = 1870.4,
},
["Zone"] = "405 (Desolace)",
}, -- [71]
{
["PickUp"] = {
1436, -- [1]
},
["TT"] = {
["y"] = -1177.7,
["x"] = 1870.4,
},
["Zone"] = "405 (Desolace)",
}, -- [72]
{
["Done"] = {
1481, -- [1]
},
["TT"] = {
["y"] = -1150.5,
["x"] = 1884.7,
},
["Zone"] = "405 (Desolace)",
}, -- [73]
{
["PickUp"] = {
1482, -- [1]
},
["TT"] = {
["y"] = -1150.5,
["x"] = 1884.7,
},
["Zone"] = "405 (Desolace)",
}, -- [74]
{
["Done"] = {
5741, -- [1]
},
["TT"] = {
["y"] = -362.3,
["x"] = 2485,
},
["Zone"] = "405 (Desolace)",
}, -- [75]
{
["PickUp"] = {
6027, -- [1]
},
["TT"] = {
["y"] = -362.3,
["x"] = 2485,
},
["Zone"] = "405 (Desolace)",
}, -- [76]
{
["ExtraLine"] = "Kill Drysnaps for Key",
["Qpart"] = {
[6142] = {
["1"] = "1",
},
[6161] = {
["1"] = "1",
},
},
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -550,
["x"] = 2785.3,
},
["ExtraLine2"] = "Loot Giant Softshell Clams",
["Range"] = 179.37,
["TT"] = {
["y"] = -550,
["x"] = 2785.3,
},
}, -- [77]
{
["ExtraLine"] = "Click Statue and kill Kragaru",
["Qpart"] = {
[6027] = {
["1"] = "1",
},
},
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = 253.6,
["x"] = 2965.1,
},
["Fillers"] = {
[1482] = {
["1"] = "1",
},
[6161] = {
["2"] = "2",
},
},
["Range"] = 0.11,
["TT"] = {
["y"] = 253.6,
["x"] = 2965.1,
},
}, -- [78]
{
["ExtraLine"] = "Kill Slitherblade mobs for key",
["Qpart"] = {
[6161] = {
["2"] = "2",
},
},
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = 256.8,
["x"] = 2970.5,
},
["Fillers"] = {
[1482] = {
["1"] = "1",
},
},
["Range"] = 107.06,
["TT"] = {
["y"] = 256.8,
["x"] = 2970.5,
},
}, -- [79]
{
["ExtraLine"] = "Click Chest",
["Zone"] = "405 (Desolace)",
["Fillers"] = {
[1482] = {
["1"] = "1",
},
},
["Done"] = {
6161, -- [1]
},
["TT"] = {
["y"] = 191.5,
["x"] = 2883.5,
},
}, -- [80]
{
["ExtraLine"] = "Kill Oracles for Crystal",
["Qpart"] = {
[1482] = {
["1"] = "1",
},
},
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = 202,
["x"] = 2879.4,
},
["Range"] = 179.04,
["TT"] = {
["y"] = 202,
["x"] = 2879.4,
},
}, -- [81]
{
["Qpart"] = {
[6143] = {
["1"] = "1",
["3"] = "3",
["2"] = "2",
},
},
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = 219.2,
["x"] = 2955.2,
},
["Range"] = 621.99,
["TT"] = {
["y"] = 219.2,
["x"] = 2955.2,
},
}, -- [82]
{
["Done"] = {
6027, -- [1]
},
["TT"] = {
["y"] = -362.7,
["x"] = 2484.6,
},
["Zone"] = "405 (Desolace)",
}, -- [83]
{
["CRange"] = 1482,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -1240,
["x"] = 1651.6,
},
["Range"] = 16.86,
["TT"] = {
["y"] = -1240,
["x"] = 1651.6,
},
}, -- [84]
{
["Done"] = {
1482, -- [1]
},
["TT"] = {
["y"] = -1150.5,
["x"] = 1884.7,
},
["Zone"] = "405 (Desolace)",
}, -- [85]
{
["ExtraLine"] = "Wait a few secs",
["TT"] = {
["y"] = -1151.1,
["x"] = 1884.7,
},
["PickUp"] = {
1484, -- [1]
},
["Zone"] = "405 (Desolace)",
}, -- [86]
{
["Done"] = {
1484, -- [1]
},
["TT"] = {
["y"] = -1179.1,
["x"] = 1869.5,
},
["Zone"] = "405 (Desolace)",
}, -- [87]
{
["ExtraLine"] = "Loot bones off the ground",
["Qpart"] = {
[5501] = {
["1"] = "1",
},
},
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -1339.5,
["x"] = 1859,
},
["Range"] = 122.07,
["TT"] = {
["y"] = -1339.5,
["x"] = 1859,
},
}, -- [88]
{
["Qpart"] = {
[1370] = {
["1"] = "1",
},
[1366] = {
["1"] = "1",
},
},
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -1789.1,
["x"] = 1128.2,
},
["Range"] = 159.18,
["TT"] = {
["y"] = -1789.1,
["x"] = 1128.2,
},
}, -- [89]
{
["CRange"] = 1366,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -1242.8,
["x"] = 1658.7,
},
["Range"] = 18.45,
["TT"] = {
["y"] = -1242.8,
["x"] = 1658.7,
},
}, -- [90]
{
["Done"] = {
1366, -- [1]
},
["TT"] = {
["y"] = -1333.1,
["x"] = 1707.4,
},
["Zone"] = "405 (Desolace)",
}, -- [91]
{
["ExtraLine"] = "Grind your way north",
["Done"] = {
5501, -- [1]
},
["TT"] = {
["y"] = -716.6,
["x"] = 1431.2,
},
["Zone"] = "405 (Desolace)",
}, -- [92]
{
["TT"] = {
["y"] = -715.4,
["x"] = 1432.5,
},
["UseHS"] = 5381,
["Zone"] = "405 (Desolace)",
}, -- [93]
{
["Done"] = {
5381, -- [1]
},
["TT"] = {
["y"] = -1593.4,
["x"] = 3072.7,
},
["Zone"] = "405 (Desolace)",
}, -- [94]
{
["Done"] = {
1370, -- [1]
},
["TT"] = {
["y"] = -1923.4,
["x"] = 2603.5,
},
["Zone"] = "405 (Desolace)",
}, -- [95]
{
["PickUp"] = {
1373, -- [1]
},
["TT"] = {
["y"] = -1923.4,
["x"] = 2603.5,
},
["Zone"] = "405 (Desolace)",
}, -- [96]
{
["CRange"] = 6143,
["Zone"] = "405 (Desolace)",
["Trigger"] = {
["y"] = -1786.2,
["x"] = 3053.6,
},
["Range"] = 15.78,
["TT"] = {
["y"] = -1786.2,
["x"] = 3053.6,
},
}, -- [97]
{
["Done"] = {
6143, -- [1]
},
["TT"] = {
["y"] = -1732.5,
["x"] = 3184.7,
},
["Zone"] = "405 (Desolace)",
}, -- [98]
{
["TT"] = {
["y"] = -1705.2,
["x"] = 3214.7,
},
["LeaveQuests"] = {
5581, -- [1]
1488, -- [2]
},
["Done"] = {
6142, -- [1]
},
["Zone"] = "405 (Desolace)",
}, -- [99]
{
["TT"] = {
["y"] = -1770.3,
["x"] = 3261.9,
},
["UseFlightPath"] = 1178,
["Name"] = "Camp Taurajo, The Barrens",
["Zone"] = "405 (Desolace)",
}, -- [100]
{
["CRange"] = 1178,
["Zone"] = "17 (The Barrens)",
["Trigger"] = {
["y"] = -3083.4,
["x"] = -2137.1,
},
["Range"] = 43.45,
["TT"] = {
["y"] = -3083.4,
["x"] = -2137.1,
},
}, -- [101]
{
["PickUp"] = {
1268, -- [1]
},
["TT"] = {
["y"] = -3700.7,
["x"] = -2534,
},
["ExtraLine"] = "Click Hoofprints",
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [102]
{
["PickUp"] = {
1269, -- [1]
},
["TT"] = {
["y"] = -3721.9,
["x"] = -2541.2,
},
["ExtraLine"] = "Click Badge on plank",
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [103]
{
["PickUp"] = {
1251, -- [1]
},
["TT"] = {
["y"] = -3734.2,
["x"] = -2530.5,
},
["ExtraLine"] = "Click Shield on the fireplace",
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [104]
{
["Done"] = {
1268, -- [1]
1269, -- [2]
1251, -- [3]
},
["TT"] = {
["y"] = -3148.8,
["x"] = -2886.6,
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [105]
{
["PickUp"] = {
1321, -- [1]
},
["TT"] = {
["y"] = -3148.8,
["x"] = -2886.6,
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [106]
{
["Done"] = {
1321, -- [1]
},
["TT"] = {
["y"] = -3111.6,
["x"] = -2892.7,
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [107]
{
["ExtraLine"] = "buy First Aid Recipys",
["CRange"] = 1178,
["Zone"] = "15 (Dustwallow Marsh)",
["Trigger"] = {
["y"] = -3095.8,
["x"] = -2890.1,
},
["RaidIcon"] = 13476,
["Range"] = 1.92,
["TT"] = {
["y"] = -3095.8,
["x"] = -2890.1,
},
}, -- [108]
{
["TT"] = {
["y"] = -3149.7,
["x"] = -2842.3,
},
["UseFlightPath"] = 1178,
["Name"] = "Ratchet, The Barrens",
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [109]
{
["Done"] = {
1178, -- [1]
},
["TT"] = {
["y"] = -835.6,
["x"] = -3728.9,
},
["Zone"] = "17 (The Barrens)",
}, -- [110]
{
["PickUp"] = {
1180, -- [1]
},
["TT"] = {
["y"] = -835.6,
["x"] = -3728.9,
},
["Zone"] = "17 (The Barrens)",
}, -- [111]
{
["Done"] = {
1111, -- [1]
},
["TT"] = {
["y"] = -985.6,
["x"] = -3796.6,
},
["Zone"] = "17 (The Barrens)",
}, -- [112]
{
["PickUp"] = {
1112, -- [1]
},
["TT"] = {
["y"] = -985.6,
["x"] = -3796.6,
},
["Zone"] = "17 (The Barrens)",
}, -- [113]
{
["ExtraLine"] = "Use Boat to Booty Bay",
["CRange"] = 1180,
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -14334.2,
["x"] = 1039.4,
},
["Range"] = 438.52,
["TT"] = {
["y"] = -999.6,
["x"] = -3828.4,
},
}, -- [114]
{
["Done"] = {
1180, -- [1]
},
["TT"] = {
["y"] = -14297.9,
["x"] = 539.4,
},
["Zone"] = "33 (Stranglethorn Vale)",
["LeaveQuests"] = {
1322,
1201,
},
}, -- [115]
{
["UpdMapID"] = 1,
},
},
["34-37"] = {
{
["PickUp"] = {
1181, -- [1]
},
["TT"] = {
["y"] = -14297.8,
["x"] = 539.7,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [1]
{
["SetHS"] = 1181,
["TT"] = {
["y"] = -14457.9,
["x"] = 495.1,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [2]
{
["PickUp"] = {
605, -- [1]
},
["TT"] = {
["y"] = -14453.7,
["x"] = 490.7,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [3]
{
["ExtraLine"] = "Upstairs",
["TT"] = {
["y"] = -14453.2,
["x"] = 500.1,
},
["PickUp"] = {
201, -- [1]
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [4]
{
["PickUp"] = {
189, -- [1]
213, -- [2]
},
["TT"] = {
["y"] = -14450,
["x"] = 497.5,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [5]
{
["Done"] = {
1181, -- [1]
},
["TT"] = {
["y"] = -14438.8,
["x"] = 483.1,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [6]
{
["PickUp"] = {
1182, -- [1]
},
["TT"] = {
["y"] = -14438.8,
["x"] = 483.1,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [7]
{
["PickUp"] = {
575, -- [1]
},
["TT"] = {
["y"] = -14468.9,
["x"] = 416.6,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [8]
{
["TT"] = {
["y"] = -14448.5,
["x"] = 506.9,
},
["UseFlightPath"] = 605,
["Name"] = "Grom'gol, Stranglethorn",
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [9]
{
["PickUp"] = {
568, -- [1]
},
["TT"] = {
["y"] = -12399.1,
["x"] = 169.5,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [10]
{
["PickUp"] = {
570, -- [1]
},
["TT"] = {
["y"] = -12411.7,
["x"] = 171.6,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [11]
{
["PickUp"] = {
596, -- [1]
},
["TT"] = {
["y"] = -12349.3,
["x"] = 164.8,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [12]
{
["CRange"] = 605,
["Zone"] = "33 (Stranglethorn Vale)",
["Fillers"] = {
[605] = {
["1"] = "1",
},
},
["Trigger"] = {
["y"] = -11888.3,
["x"] = 724.8,
},
["Range"] = 24.72,
["TT"] = {
["y"] = -11888.3,
["x"] = 724.8,
},
}, -- [13]
{
["Qpart"] = {
[189] = {
["1"] = "1",
},
[581] = {
["1"] = "1",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -11964.6,
["x"] = 293.7,
},
["Fillers"] = {
[596] = {
["1"] = "1",
},
},
["Range"] = 130.43,
["TT"] = {
["y"] = -11964.6,
["x"] = 293.7,
},
}, -- [14]
{
["Qpart"] = {
[187] = {
["1"] = "1",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -11975.3,
["x"] = 157.2,
},
["Range"] = 89.09,
["TT"] = {
["y"] = -11975.3,
["x"] = 157.2,
},
}, -- [15]
{
["Qpart"] = {
[568] = {
["1"] = "1",
},
[195] = {
["1"] = "1",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -12201.4,
["x"] = 160.6,
},
["Range"] = 88.99,
["TT"] = {
["y"] = -12201.4,
["x"] = 160.6,
},
}, -- [16]
{
["Done"] = {
581, -- [1]
},
["TT"] = {
["y"] = -12348.2,
["x"] = 168.9,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [17]
{
["PickUp"] = {
582, -- [1]
},
["TT"] = {
["y"] = -12348.2,
["x"] = 168.9,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [18]
{
["Done"] = {
568, -- [1]
},
["TT"] = {
["y"] = -12398,
["x"] = 168,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [19]
{
["PickUp"] = {
569, -- [1]
},
["TT"] = {
["y"] = -12398,
["x"] = 168,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [20]
{
["CRange"] = 582,
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -12051.7,
["x"] = 435.4,
},
["Range"] = 30.04,
["TT"] = {
["y"] = -12051.7,
["x"] = 435.4,
},
}, -- [21]
{
["CRange"] = 582,
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -11903.9,
["x"] = 798.6,
},
["Fillers"] = {
[605] = {
["1"] = "1",
},
},
["Range"] = 41.99,
["TT"] = {
["y"] = -11903.9,
["x"] = 798.6,
},
}, -- [22]
{
["Qpart"] = {
[582] = {
["1"] = "1",
},
[596] = {
["1"] = "1",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -11528.9,
["x"] = 781.7,
},
["Range"] = 109.62,
["TT"] = {
["y"] = -11528.9,
["x"] = 781.7,
},
}, -- [23]
{
["Done"] = {
5763, -- [2]
},
["TT"] = {
["y"] = -11624.4,
["x"] = -54.3,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [24]
{
["Done"] = {
195, -- [1]
187, -- [3]
5762, -- [4]
},
["TT"] = {
["y"] = -11624.4,
["x"] = -54.3,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [24]
{
["PickUp"] = {
188, -- [1]
196, -- [2]
},
["TT"] = {
["y"] = -11624.4,
["x"] = -54.3,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [25]
{
["PickUp"] = {
192, -- [1]
},
["TT"] = {
["y"] = -11617.3,
["x"] = -48,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [26]
{
["Qpart"] = {
[188] = {
["1"] = "1",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -11905.6,
["x"] = 164.3,
},
["Range"] = 0.16,
["TT"] = {
["y"] = -11905.6,
["x"] = 164.3,
},
["LeaveQuests"] = {
629, -- [1]
2932, -- [2]
584, -- [3]
600, -- [4]
621, -- [5]
572, -- [6]
},
}, -- [27]
{
["Done"] = {
188, -- [1]
},
["TT"] = {
["y"] = -11620.6,
["x"] = -52,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [28]
{
["Qpart"] = {
[575] = {
["1"] = "1",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Fillers"] = {
[605] = {
["1"] = "1",
},
},
["Trigger"] = {
["y"] = -11556.6,
["x"] = 33.9,
},
["Range"] = 92.88,
["TT"] = {
["y"] = -11556.6,
["x"] = 33.9,
},
}, -- [29]
{
["Trigger"] = {
["y"] = -11948.8,
["x"] = -500.4,
},
["Ammount"] = 1,
["Range"] = 0.01,
["ExtraQpart"] = "Cozzle's Key",
["ExtraLine"] = "Kill Foreman Cozzle on top of platform",
["ItemID"] = 5851,
["Qid"] = 1182,
["RaidIcon"] = 4723,
["TT"] = {
["y"] = -11948.8,
["x"] = -500.4,
},
}, -- [30]
{
["ExtraLine"] = "Open chest",
["Qpart"] = {
[1182] = {
["1"] = "1",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -12034,
["x"] = -544.8,
},
["Fillers"] = {
[213] = {
["1"] = "1",
},
},
["Range"] = 0.15,
["TT"] = {
["y"] = -12034,
["x"] = -544.8,
},
}, -- [31]
{
["Qpart"] = {
[213] = {
["1"] = "1",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -12034,
["x"] = -544.8,
},
["Range"] = 113.49,
["TT"] = {
["y"] = -12034,
["x"] = -544.8,
},
}, -- [32]
{
["Qpart"] = {
[570] = {
["1"] = "1",
["2"] = "2",
},
[192] = {
["1"] = "1",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -12145.5,
["x"] = -903.9,
},
["Range"] = 106.44,
["TT"] = {
["y"] = -12145.5,
["x"] = -903.9,
},
}, -- [33]
{
["Qpart"] = {
[605] = {
["1"] = "1",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -11519.2,
["x"] = -853.5,
},
["Range"] = 65.63,
["TT"] = {
["y"] = -11519.2,
["x"] = -853.5,
},
}, -- [34]
{
["Qpart"] = {
[569] = {
["1"] = "1",
["2"] = "2",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -12482.5,
["x"] = -153.5,
},
["Range"] = 41.68,
["TT"] = {
["y"] = -12482.5,
["x"] = -153.5,
},
}, -- [35]
{
["Done"] = {
192, -- [1]
},
["TT"] = {
["y"] = -11617.9,
["x"] = -48.3,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [36]
{
["PickUp"] = {
193, -- [1]
},
["TT"] = {
["y"] = -11617.9,
["x"] = -48.3,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [37]
{
["TT"] = {
["y"] = -11617.9,
["x"] = -48.3,
},
["UseHS"] = 605,
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [38]
{
["Done"] = {
605, -- [1]
},
["TT"] = {
["y"] = -14453.8,
["x"] = 490.3,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [39]
{
["ExtraLine"] = "Upstairs",
["Done"] = {
201, -- [1]
213, -- [2]
189, -- [3]
},
["TT"] = {
["y"] = -14452.3,
["x"] = 498.7,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [40]
{
["Done"] = {
1182, -- [1]
},
["TT"] = {
["y"] = -14439.1,
["x"] = 483.6,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [41]
{
["PickUp"] = {
1183, -- [1]
},
["TT"] = {
["y"] = -14439.1,
["x"] = 483.6,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [42]
{
["Done"] = {
575, -- [1]
},
["TT"] = {
["y"] = -14468.6,
["x"] = 416.6,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [43]
{
["PickUp"] = {
577, -- [1]
},
["TT"] = {
["y"] = -14468.6,
["x"] = 416.6,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [44]
{
["TT"] = {
["y"] = -14448.4,
["x"] = 506.2,
},
["UseFlightPath"] = 569,
["Name"] = "Grom'gol, Stranglethorn",
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [45]
{
["Done"] = {
569, -- [1]
},
["TT"] = {
["y"] = -12399,
["x"] = 168.6,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [46]
{
["Done"] = {
570, -- [1]
},
["TT"] = {
["y"] = -12412.4,
["x"] = 170.9,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [47]
{
["Done"] = {
582, -- [1]
},
["TT"] = {
["y"] = -12347.8,
["x"] = 165,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [48]
{
["Done"] = {
596, -- [1]
},
["TT"] = {
["y"] = -12347.5,
["x"] = 161.4,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [49]
{
["PickUp"] = {
638, -- [1]
},
["TT"] = {
["y"] = -12347.8,
["x"] = 165,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [50]
{
["Grind"] = 11951,
["Range"] = 442.15,
["Trigger"] = {
["y"] = -12347.8,
["x"] = 165,
},
["level"] = 36,
["xp"] = 1,
["TT"] = {
["y"] = -12347.8,
["x"] = 165,
},
}, -- [51]
{
["ExtraLine"] = "go to Undercity via Zepelin",
["CRange"] = 638,
["Zone"] = "85 (Tirisfal Glades)",
["Trigger"] = {
["y"] = 2299.5,
["x"] = -769.5,
},
["Range"] = 855.62,
["TT"] = {
["y"] = -12407.4,
["x"] = 207.3,
},
}, -- [52]
{
["ExtraLine"] = "Go to undercity",
["CRange"] = 638,
["Zone"] = "85 (Tirisfal Glades)",
["Trigger"] = {
["y"] = 1876.6,
["x"] = 237.8,
},
["LeaveQuests"] = {
629, -- [1]
2932, -- [2]
584, -- [3]
600, -- [4]
621, -- [5]
572, -- [6]
},
["Range"] = 9.99,
["TT"] = {
["y"] = 1876.6,
["x"] = 237.8,
},
}, -- [53]
{
["CRange"] = 638,
["Zone"] = "1497 (Undercity)",
["Trigger"] = {
["y"] = 1657.2,
["x"] = 239.2,
},
["Range"] = 11,
["TT"] = {
["y"] = 1657.2,
["x"] = 239.2,
},
}, -- [54]
{
["CRange"] = 638,
["Zone"] = "85 (Tirisfal Glades)",
["Trigger"] = {
["y"] = 1594.5,
["x"] = 238.4,
},
["Range"] = 7.74,
["TT"] = {
["y"] = 1594.5,
["x"] = 238.4,
},
}, -- [55]
{
["ExtraLine"] = "Down elevator",
["CRange"] = 638,
["Zone"] = "1497 (Undercity)",
["Trigger"] = {
["y"] = 1519.5,
["x"] = 239.8,
},
["Range"] = 12.84,
["TT"] = {
["y"] = 1519.5,
["x"] = 239.8,
},
}, -- [56]
{
["PickUp"] = {
1164, -- [1]
},
["TT"] = {
["y"] = 1561.6,
["x"] = 260.2,
},
["Zone"] = "1497 (Undercity)",
}, -- [57]
{
["TT"] = {
["y"] = 1566.7,
["x"] = 265.6,
},
["UseFlightPath"] = 638,
["Name"] = "Tarren Mill, Hillsbrad",
["Zone"] = "1497 (Undercity)",
}, -- [58]
{
["PickUp"] = {
676, -- [1]
},
["TT"] = {
["y"] = -18.6,
["x"] = -913.3,
},
["Zone"] = "267 (Hillsbrad Foothills)",
}, -- [59]
{
["TT"] = {
["y"] = 2.4,
["x"] = -858,
},
["UseFlightPath"] = 638,
["Name"] = "Hammerfall, Arathi",
["Zone"] = "267 (Hillsbrad Foothills)",
}, -- [60]
{
["SetHS"] = 676,
["TT"] = {
["y"] = -912.8,
["x"] = -3524.9,
},
["Zone"] = "45 (Arathi Highlands)",
}, -- [61]
{
["Done"] = {
638, -- [1]
},
["TT"] = {
["y"] = -948.6,
["x"] = -3523.4,
},
["Zone"] = "45 (Arathi Highlands)",
}, -- [62]
{
["PickUp"] = {
639, -- [1]
},
["TT"] = {
["y"] = -948.6,
["x"] = -3523.4,
},
["Zone"] = "45 (Arathi Highlands)",
}, -- [63]
{
["PickUp"] = {
701, -- [1]
671, -- [2]
},
["TT"] = {
["y"] = -1004.4,
["x"] = -3556.9,
},
["Zone"] = "45 (Arathi Highlands)",
}, -- [64]
{
["PickUp"] = {
642, -- [1]
},
["TT"] = {
["y"] = -942.6,
["x"] = -3118.2,
},
["ExtraLine"] = "Click Crystal",
["Zone"] = "45 (Arathi Highlands)",
}, -- [65]
{
["CRange"] = 642,
["Zone"] = "45 (Arathi Highlands)",
["Fillers"] = {
[642] = {
["1"] = "1",
},
},
["Trigger"] = {
["y"] = -1093.1,
["x"] = -3778.6,
},
["Range"] = 14.62,
["TT"] = {
["y"] = -1093.1,
["x"] = -3778.6,
},
}, -- [66]
{
["Qpart"] = {
[642] = {
["1"] = "1",
},
},
["Zone"] = "45 (Arathi Highlands)",
["Trigger"] = {
["y"] = -995.3,
["x"] = -3845.9,
},
["Range"] = 53.09,
["TT"] = {
["y"] = -995.3,
["x"] = -3845.9,
},
}, -- [67]
{
["ExtraLine"] = "Click crystal in cave",
["Done"] = {
642, -- [1]
},
["TT"] = {
["y"] = -874.6,
["x"] = -3901.8,
},
["Zone"] = "45 (Arathi Highlands)",
}, -- [68]
{
["PickUp"] = {
651, -- [1]
},
["TT"] = {
["y"] = -874.6,
["x"] = -3901.8,
},
["Zone"] = "45 (Arathi Highlands)",
}, -- [69]
{
["ExtraLine"] = "If you have 225 FirstAid do quest Triage",
["CRange"] = 651,
["Zone"] = "45 (Arathi Highlands)",
["Trigger"] = {
["y"] = -992.7,
["x"] = -3526.2,
},
["Range"] = 57.79,
["TT"] = {
["y"] = -992.7,
["x"] = -3526.2,
},
}, -- [70]
{
["ExtraLine"] = "click stone",
["Qpart"] = {
[651] = {
["2"] = "2",
},
},
["Zone"] = "45 (Arathi Highlands)",
["Trigger"] = {
["y"] = -846.1,
["x"] = -3266.9,
},
["Range"] = 0.15,
["TT"] = {
["y"] = -846.1,
["x"] = -3266.9,
},
}, -- [71]
{
["ExtraLine"] = "In house",
["Qpart"] = {
[1164] = {
["1"] = "1",
},
},
["Zone"] = "45 (Arathi Highlands)",
["Trigger"] = {
["y"] = -999.5,
["x"] = -2896.2,
},
["Range"] = 0.09,
["TT"] = {
["y"] = -999.5,
["x"] = -2896.2,
},
}, -- [72]
{
["SpecialButton"] = "Fardel Dabyrie",
["Qpart"] = {
[1164] = {
["3"] = "3",
},
},
["Button"] = 1,
["Zone"] = "45 (Arathi Highlands)",
["Trigger"] = {
["y"] = -1062.4,
["x"] = -2901.3,
},
["RaidIcon"] = 4479,
["Range"] = 24.13,
["TT"] = {
["y"] = -1062.4,
["x"] = -2901.3,
},
}, -- [73]
{
["ExtraLine"] = "In stables",
["Qpart"] = {
[1164] = {
["2"] = "2",
},
},
["Zone"] = "45 (Arathi Highlands)",
["Trigger"] = {
["y"] = -1049.3,
["x"] = -2814.8,
},
["RaidIcon"] = 4481,
["Range"] = 0.12,
["TT"] = {
["y"] = -1049.3,
["x"] = -2814.8,
},
}, -- [74]
{
["ExtraLine"] = "Click stone",
["Qpart"] = {
[651] = {
["3"] = "3",
},
},
["Zone"] = "45 (Arathi Highlands)",
["Trigger"] = {
["y"] = -1350.2,
["x"] = -2738.9,
},
["Range"] = 0.15,
["TT"] = {
["y"] = -1350.2,
["x"] = -2738.9,
},
}, -- [75]
{
["Qpart"] = {
[701] = {
["1"] = "1",
},
},
["Zone"] = "45 (Arathi Highlands)",
["Trigger"] = {
["y"] = -1777.5,
["x"] = -2718.7,
},
["Range"] = 75.72,
["TT"] = {
["y"] = -1777.5,
["x"] = -2718.7,
},
}, -- [76]
{
["Qpart"] = {
[676] = {
["1"] = "1",
["2"] = "2",
},
},
["Zone"] = "45 (Arathi Highlands)",
["Trigger"] = {
["y"] = -1196.8,
["x"] = -2136.6,
},
["Range"] = 18.44,
["TT"] = {
["y"] = -1196.8,
["x"] = -2136.6,
},
}, -- [77]
{
["Qpart"] = {
[671] = {
["1"] = "1",
},
},
["Zone"] = "45 (Arathi Highlands)",
["Trigger"] = {
["y"] = -826,
["x"] = -2031.1,
},
["Range"] = 133.07,
["TT"] = {
["y"] = -826,
["x"] = -2031.1,
},
}, -- [78]
{
["ExtraLine"] = "Click Stone",
["Qpart"] = {
[651] = {
["1"] = "1",
},
},
["Zone"] = "45 (Arathi Highlands)",
["Trigger"] = {
["y"] = -856.9,
["x"] = -1784.4,
},
["Range"] = 0.14,
["TT"] = {
["y"] = -856.9,
["x"] = -1784.4,
},
}, -- [79]
{
["Group"] = 3,
["TT"] = {
["y"] = -1353.3,
["x"] = -1832.5,
},
["GroupTask"] = 639,
["QaskPopup"] = 639,
}, -- [80]
{
["CRange"] = 639,
["Zone"] = "45 (Arathi Highlands)",
["Trigger"] = {
["y"] = -1353.3,
["x"] = -1832.5,
},
["GroupTask"] = 639,
["Range"] = 29.32,
["TT"] = {
["y"] = -1353.3,
["x"] = -1832.5,
},
}, -- [81]
{
["Qpart"] = {
[639] = {
["1"] = "1",
},
},
["Zone"] = "45 (Arathi Highlands)",
["Trigger"] = {
["y"] = -1572.5,
["x"] = -1808.8,
},
["GroupTask"] = 639,
["Range"] = 131.31,
["TT"] = {
["y"] = -1572.5,
["x"] = -1808.8,
},
}, -- [82]
{
["ExtraLine"] = "Click stone",
["Done"] = {
651, -- [1]
},
["TT"] = {
["y"] = -1509.2,
["x"] = -2171.2,
},
["Zone"] = "45 (Arathi Highlands)",
}, -- [83]
{
["PickUp"] = {
652, -- [1]
},
["TT"] = {
["y"] = -1509.2,
["x"] = -2171.2,
},
["Zone"] = "45 (Arathi Highlands)",
}, -- [84]
{
["TT"] = {
["y"] = -1509.2,
["x"] = -2171.2,
},
["UseHS"] = 676,
["Zone"] = "45 (Arathi Highlands)",
}, -- [85]
{
["GroupTask"] = 639,
["Done"] = {
639, -- [1]
},
["TT"] = {
["y"] = -948,
["x"] = -3522.6,
},
["Zone"] = "45 (Arathi Highlands)",
}, -- [86]
{
["Done"] = {
676, -- [1]
},
["TT"] = {
["y"] = -947.2,
["x"] = -3539,
},
["Zone"] = "45 (Arathi Highlands)",
}, -- [87]
{
["PickUp"] = {
677, -- [1]
},
["TT"] = {
["y"] = -947.2,
["x"] = -3539,
},
["Zone"] = "45 (Arathi Highlands)",
}, -- [88]
{
["Done"] = {
701, -- [1]
671, -- [2]
},
["TT"] = {
["y"] = -1004.8,
["x"] = -3556.3,
},
["Zone"] = "45 (Arathi Highlands)",
}, -- [89]
{
["PickUp"] = {
702, -- [1]
},
["TT"] = {
["y"] = -1004.8,
["x"] = -3556.3,
},
["Zone"] = "45 (Arathi Highlands)",
}, -- [90]
{
["Done"] = {
702, -- [1]
},
["TT"] = {
["y"] = -952.8,
["x"] = -3487.7,
},
["Zone"] = "45 (Arathi Highlands)",
}, -- [91]
{
["ExtraLine"] = "Wait a sec",
["TT"] = {
["y"] = -945.9,
["x"] = -3485.8,
},
["PickUp"] = {
847, -- [1]
},
["Zone"] = "45 (Arathi Highlands)",
}, -- [92]
{
["Done"] = {
847, -- [1]
},
["TT"] = {
["y"] = -1004.9,
["x"] = -3556.4,
},
["Zone"] = "45 (Arathi Highlands)",
}, -- [93]
{
["Qpart"] = {
[677] = {
["1"] = "1",
["3"] = "3",
["2"] = "2",
},
},
["Zone"] = "45 (Arathi Highlands)",
["Trigger"] = {
["y"] = -1720.8,
["x"] = -3312.8,
},
["Range"] = 186.96,
["TT"] = {
["y"] = -1720.8,
["x"] = -3312.8,
},
}, -- [94]
{
["Done"] = {
677, -- [1]
},
["TT"] = {
["y"] = -947.6,
["x"] = -3539.4,
},
["Zone"] = "45 (Arathi Highlands)",
}, -- [95]
{
["PickUp"] = {
678, -- [1]
},
["TT"] = {
["y"] = -947.6,
["x"] = -3539.4,
},
["Zone"] = "45 (Arathi Highlands)",
}, -- [96]
{
["Qpart"] = {
[678] = {
["1"] = "1",
["2"] = "2",
},
},
["Zone"] = "45 (Arathi Highlands)",
["Trigger"] = {
["y"] = -1956.1,
["x"] = -2763.5,
},
["Range"] = 60.55,
["TT"] = {
["y"] = -1956.1,
["x"] = -2763.5,
},
}, -- [97]
{
["Grind"] = 11951,
["Range"] = 442.15,
["Trigger"] = {
["y"] = -1956.1,
["x"] = -2763.5,
},
["level"] = 37,
["xp"] = 1,
["TT"] = {
["y"] = -1956.1,
["x"] = -2763.5,
},
}, -- [98]
{
["ExtraLine"] = "Use HS or run",
["Done"] = {
678, -- [1]
},
["TT"] = {
["y"] = -947.6,
["x"] = -3539.9,
},
["Zone"] = "45 (Arathi Highlands)",
}, -- [99]
{
["Group"] = 3,
["TT"] = {
["y"] = -936.3,
["x"] = -3535.2,
},
["GroupTask"] = 680,
["QaskPopup"] = 680,
}, -- [100]
{
["PickUp"] = {
680, -- [1]
},
["TT"] = {
["y"] = -927.8,
["x"] = -3532.7,
},
["GroupTask"] = 680,
["Zone"] = "45 (Arathi Highlands)",
}, -- [101]
{
["Qpart"] = {
[680] = {
["1"] = "1",
},
[640] = {
["1"] = "1",
},
[673] = {
["1"] = "1",
},
[679] = {
["1"] = "1",
["2"] = "2",
},
},
["Zone"] = "45 (Arathi Highlands)",
["Trigger"] = {
["y"] = -1670.9,
["x"] = -1805.5,
},
["GroupTask"] = 680,
["Range"] = 194.07,
["TT"] = {
["y"] = -1670.9,
["x"] = -1805.5,
},
}, -- [102]
{
["GroupTask"] = 680,
["Done"] = {
680, -- [1]
640, -- [2]
679, -- [3]
673, -- [4]
},
["TT"] = {
["y"] = -983.8,
["x"] = -3524.9,
},
["Zone"] = "45 (Arathi Highlands)",
}, -- [103]
{
["TT"] = {
["y"] = -918,
["x"] = -3497.7,
},
["UseFlightPath"] = 544,
["Name"] = "Tarren Mill, Hillsbrad",
["Zone"] = "45 (Arathi Highlands)",
}, -- [104]
{
["PickUp"] = {
544, -- [1]
},
["TT"] = {
["y"] = -44.1,
["x"] = -904.4,
},
["Zone"] = "267 (Hillsbrad Foothills)",
}, -- [105]
{
["PickUp"] = {
556, -- [1]
},
["RaidIcon"] = 2437,
["TT"] = {
["y"] = -46.6,
["x"] = -901.3,
},
["Zone"] = "267 (Hillsbrad Foothills)",
}, -- [106]
{
["CRange"] = 544,
["Zone"] = "267 (Hillsbrad Foothills)",
["Trigger"] = {
["y"] = 183,
["x"] = -660,
},
["LeaveQuests"] = {
680, -- [1]
640, -- [2]
679, -- [3]
673, -- [4]
643, -- [5]
},
["Range"] = 47.8,
["TT"] = {
["y"] = 183,
["x"] = -660,
},
}, -- [107]
{
["CRange"] = 544,
["Zone"] = "36 (Alterac Mountains)",
["Trigger"] = {
["y"] = 177,
["x"] = -587.3,
},
["Range"] = 17.34,
["TT"] = {
["y"] = 177,
["x"] = -587.3,
},
}, -- [108]
{
["CRange"] = 544,
["Zone"] = "36 (Alterac Mountains)",
["Trigger"] = {
["y"] = 71.9,
["x"] = -535.3,
},
["Range"] = 17.09,
["TT"] = {
["y"] = 71.9,
["x"] = -535.3,
},
}, -- [109]
{
["ExtraLine"] = "Kill a Cat or Lion",
["TT"] = {
["y"] = 37.6,
["x"] = -476.1,
},
["ItemID"] = 5810,
["Qid"] = 553,
["Trigger"] = {
["y"] = 37.6,
["x"] = -476.1,
},
["Ammount"] = 1,
["Range"] = 0.91,
["ExtraQpart"] = "Fresh Carcass",
}, -- [110]
{
["CRange"] = 544,
["Zone"] = "36 (Alterac Mountains)",
["Trigger"] = {
["y"] = 92.3,
["x"] = -365.8,
},
["Range"] = 21.13,
["TT"] = {
["y"] = 92.3,
["x"] = -365.8,
},
}, -- [111]
{
["CRange"] = 553,
["Zone"] = "36 (Alterac Mountains)",
["Trigger"] = {
["y"] = 226.6,
["x"] = -269.2,
},
["Range"] = 17.12,
["TT"] = {
["y"] = 226.6,
["x"] = -269.2,
},
}, -- [112]
{
["Qpart"] = {
[553] = {
["3"] = "3",
},
},
["Zone"] = "36 (Alterac Mountains)",
["Trigger"] = {
["y"] = 263.5,
["x"] = -267.7,
},
["Range"] = 0.11,
["TT"] = {
["y"] = 263.5,
["x"] = -267.7,
},
}, -- [113]
{
["ExtraLine"] = "Use Carcass to summon Frostmaw",
["Qpart"] = {
[1136] = {
["1"] = "1",
},
},
["Button"] = 5810,
["Zone"] = "36 (Alterac Mountains)",
["Trigger"] = {
["y"] = 263.2,
["x"] = -266.3,
},
["RaidIcon"] = 4504,
["Range"] = 0.14,
["TT"] = {
["y"] = 263.2,
["x"] = -266.3,
},
}, -- [114]
{
["CRange"] = 556,
["Zone"] = "36 (Alterac Mountains)",
["Trigger"] = {
["y"] = 116.6,
["x"] = 12.4,
},
["Range"] = 51.16,
["TT"] = {
["y"] = 116.6,
["x"] = 12.4,
},
}, -- [115]
{
["Qpart"] = {
[556] = {
["1"] = "1",
},
[544] = {
["1"] = "1",
["4"] = "4",
["3"] = "3",
["2"] = "2",
},
},
["Zone"] = "36 (Alterac Mountains)",
["Trigger"] = {
["y"] = -87.1,
["x"] = 246,
},
["Range"] = 97.63,
["TT"] = {
["y"] = -87.1,
["x"] = 246,
},
}, -- [116]
{
["CRange"] = 553,
["Zone"] = "267 (Hillsbrad Foothills)",
["Trigger"] = {
["y"] = -581.4,
["x"] = -697.2,
},
["Range"] = 62.42,
["TT"] = {
["y"] = -581.4,
["x"] = -697.2,
},
}, -- [117]
{
["ExtraLine"] = "Click on Grave",
["Done"] = {
553, -- [1]
},
["TT"] = {
["y"] = -738.1,
["x"] = -622.6,
},
["Zone"] = "267 (Hillsbrad Foothills)",
}, -- [118]
{
["Done"] = {
556, -- [1]
544, -- [2]
},
["TT"] = {
["y"] = -46.1,
["x"] = -902.6,
},
["Zone"] = "267 (Hillsbrad Foothills)",
}, -- [119]
{
["PickUp"] = {
545, -- [1]
557, -- [2]
},
["TT"] = {
["y"] = -46.1,
["x"] = -902.6,
},
["Zone"] = "267 (Hillsbrad Foothills)",
}, -- [120]
{
["CRange"] = 557,
["Zone"] = "36 (Alterac Mountains)",
["Trigger"] = {
["y"] = 201.2,
["x"] = -647.1,
},
["Range"] = 40.76,
["TT"] = {
["y"] = 201.2,
["x"] = -647.1,
},
}, -- [121]
{
["CRange"] = 557,
["Zone"] = "36 (Alterac Mountains)",
["Trigger"] = {
["y"] = 163.7,
["x"] = -592,
},
["Range"] = 19.69,
["TT"] = {
["y"] = 163.7,
["x"] = -592,
},
}, -- [122]
{
["CRange"] = 557,
["Zone"] = "36 (Alterac Mountains)",
["Trigger"] = {
["y"] = 7.2,
["x"] = -479.2,
},
["Range"] = 31.64,
["TT"] = {
["y"] = 7.2,
["x"] = -479.2,
},
}, -- [123]
{
["CRange"] = 557,
["Zone"] = "36 (Alterac Mountains)",
["Trigger"] = {
["y"] = -76.9,
["x"] = -338.9,
},
["Range"] = 26.33,
["TT"] = {
["y"] = -76.9,
["x"] = -338.9,
},
}, -- [124]
{
["CRange"] = 557,
["Zone"] = "36 (Alterac Mountains)",
["Trigger"] = {
["y"] = 2.3,
["x"] = -83.8,
},
["Range"] = 22.31,
["TT"] = {
["y"] = 2.3,
["x"] = -83.8,
},
}, -- [125]
{
["Qpart"] = {
[557] = {
["1"] = "1",
},
[545] = {
["1"] = "1",
["2"] = "2",
},
},
["Zone"] = "36 (Alterac Mountains)",
["Trigger"] = {
["y"] = 91.8,
["x"] = 258,
},
["Range"] = 90.3,
["TT"] = {
["y"] = 91.8,
["x"] = 258,
},
}, -- [126]
{
["ExtraLine"] = "Die and spirit rez or run",
["Done"] = {
557, -- [1]
545, -- [2]
},
["TT"] = {
["y"] = -46.1,
["x"] = -902.9,
},
["Zone"] = "267 (Hillsbrad Foothills)",
}, -- [127]
{
["UpdMapID"] = 1,
},
},
["37-40"] = {
{
["TT"] = {
["y"] = 1.9,
["x"] = -858.5,
},
["UseFlightPath"] = 1164,
["Name"] = "Undercity, Tirisfal",
["Zone"] = "267 (Hillsbrad Foothills)",
}, -- [1]
{
["Done"] = {
1164, -- [1]
},
["TT"] = {
["y"] = 1561.8,
["x"] = 261.2,
},
["Zone"] = "1497 (Undercity)",
}, -- [2]
{
["ExtraLine"] = "Leave Undercity and go to Orgrimmar on Zep",
["CRange"] = 1436,
["Zone"] = "14 (Durotar)",
["Trigger"] = {
["y"] = 1336.5,
["x"] = -5215.9,
},
["Range"] = 440.37,
["TT"] = {
["y"] = 2064,
["x"] = 288.5,
},
}, -- [3]
{
["CRange"] = 1436,
["Zone"] = "14 (Durotar)",
["Trigger"] = {
["y"] = 1389.7,
["x"] = -4375.3,
},
["Range"] = 17.78,
["TT"] = {
["y"] = 1389.7,
["x"] = -4375.3,
},
}, -- [4]
{
["CRange"] = 1436,
["Zone"] = "1637 (Orgrimmar)",
["Trigger"] = {
["y"] = 1475.7,
["x"] = -4415.5,
},
["Range"] = 29,
["TT"] = {
["y"] = 1475.7,
["x"] = -4415.5,
},
}, -- [5]
{
["CRange"] = 1436,
["Zone"] = "1637 (Orgrimmar)",
["Trigger"] = {
["y"] = 1556.4,
["x"] = -4323.4,
},
["Range"] = 19.67,
["TT"] = {
["y"] = 1556.4,
["x"] = -4323.4,
},
}, -- [6]
{
["CRange"] = 1436,
["Zone"] = "1637 (Orgrimmar)",
["Trigger"] = {
["y"] = 1648.7,
["x"] = -4273.7,
},
["Range"] = 11.27,
["TT"] = {
["y"] = 1648.7,
["x"] = -4273.7,
},
}, -- [7]
{
["CRange"] = 1436,
["Zone"] = "1637 (Orgrimmar)",
["Trigger"] = {
["y"] = 1695.4,
["x"] = -4281.5,
},
["Range"] = 4.98,
["TT"] = {
["y"] = 1695.4,
["x"] = -4281.5,
},
}, -- [8]
{
["CRange"] = 1436,
["Zone"] = "1637 (Orgrimmar)",
["Trigger"] = {
["y"] = 1687.7,
["x"] = -4241.5,
},
["Range"] = 18.98,
["TT"] = {
["y"] = 1687.7,
["x"] = -4241.5,
},
}, -- [9]
{
["Done"] = {
1436, -- [1]
},
["TT"] = {
["y"] = 1780.5,
["x"] = -3997.2,
},
["Zone"] = "1637 (Orgrimmar)",
}, -- [10]
{
["TT"] = {
["y"] = 1675.9,
["x"] = -4313.9,
},
["UseFlightPath"] = 1146,
["Name"] = "Crossroads, The Barrens",
["Zone"] = "1637 (Orgrimmar)",
}, -- [11]
{
["SetHS"] = 1146,
["TT"] = {
["y"] = -408.1,
["x"] = -2645.4,
},
["Zone"] = "17 (The Barrens)",
}, -- [12]
{
["TT"] = {
["y"] = -438,
["x"] = -2595.9,
},
["UseFlightPath"] = 1146,
["Name"] = "Freewind Post, Thousand Needles",
["Zone"] = "17 (The Barrens)",
}, -- [13]
{
["Done"] = {
1146, -- [1]
},
["TT"] = {
["y"] = -5842.9,
["x"] = -3407.7,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [14]
{
["PickUp"] = {
1147, -- [1]
},
["TT"] = {
["y"] = -5842.9,
["x"] = -3407.7,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [15]
{
["Done"] = {
1112, -- [1]
},
["TT"] = {
["y"] = -6232.8,
["x"] = -3855.3,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [16]
{
["ExtraLine"] = "wait a sec",
["TT"] = {
["y"] = -6232.8,
["x"] = -3855.3,
},
["PickUp"] = {
1114, -- [1]
},
["Zone"] = "400 (Thousand Needles)",
}, -- [17]
{
["Done"] = {
1114, -- [1]
},
["TT"] = {
["y"] = -6228.3,
["x"] = -3868.2,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [18]
{
["PickUp"] = {
1106, -- [1]
},
["TT"] = {
["y"] = -6228.3,
["x"] = -3868.2,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [19]
{
["PickUp"] = {
1115, -- [1]
},
["TT"] = {
["y"] = -6233.2,
["x"] = -3855.9,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [20]
{
["Done"] = {
1183, -- [1]
},
["TT"] = {
["y"] = -6192.1,
["x"] = -3961.1,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [21]
{
["PickUp"] = {
1186, -- [1]
},
["TT"] = {
["y"] = -6192.1,
["x"] = -3961.1,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [22]
{
["Done"] = {
1186, -- [1]
},
["TT"] = {
["y"] = -6198.5,
["x"] = -3967.8,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [23]
{
["PickUp"] = {
1187, -- [1]
},
["TT"] = {
["y"] = -6198.5,
["x"] = -3967.8,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [24]
{
["ExtraLine"] = "Kill Silithid mobs and get quest starter",
["TT"] = {
["y"] = -6430,
["x"] = -3558.5,
},
["PickUp"] = {
1148, -- [1]
},
["Zone"] = "400 (Thousand Needles)",
}, -- [25]
{
["Qpart"] = {
[1148] = {
["1"] = "1",
["3"] = "3",
["2"] = "2",
},
[1147] = {
["1"] = "1",
["3"] = "3",
["2"] = "2",
},
},
["Zone"] = "400 (Thousand Needles)",
["Trigger"] = {
["y"] = -6454.3,
["x"] = -3408.6,
},
["Range"] = 131.05,
["TT"] = {
["y"] = -6454.3,
["x"] = -3408.6,
},
}, -- [26]
{
["Grind"] = 11951,
["Range"] = 442.15,
["Trigger"] = {
["y"] = -6454.3,
["x"] = -3408.6,
},
["level"] = 38,
["xp"] = 1,
["TT"] = {
["y"] = -6454.3,
["x"] = -3408.6,
},
}, -- [27]
{
["Done"] = {
1147, -- [1]
},
["TT"] = {
["y"] = -5842.6,
["x"] = -3407.6,
},
["Zone"] = "400 (Thousand Needles)",
}, -- [28]
{
["TT"] = {
["y"] = -5845.1,
["x"] = -3410.9,
},
["UseHS"] = 1148,
["Zone"] = "400 (Thousand Needles)",
}, -- [29]
{
["Done"] = {
1148, -- [1]
},
["TT"] = {
["y"] = -389.3,
["x"] = -2552.1,
},
["Zone"] = "17 (The Barrens)",
}, -- [30]
{
["PickUp"] = {
1184, -- [1]
},
["TT"] = {
["y"] = -389.3,
["x"] = -2552.1,
},
["Zone"] = "17 (The Barrens)",
}, -- [31]
{
["TT"] = {
["y"] = -437.5,
["x"] = -2596.9,
},
["UseFlightPath"] = 1136,
["Name"] = "Thunder Bluff, Mulgore",
["Zone"] = "17 (The Barrens)",
}, -- [32]
{
["ExtraLine"] = "Buy Soothing Spices for a quest later",
["TT"] = {
["y"] = -1214.7,
["x"] = -16.7,
},
["ItemID"] = 3713,
["Qid"] = 1201,
["Trigger"] = {
["y"] = -1214.7,
["x"] = -16.7,
},
["Ammount"] = 3,
["Range"] = 0.01,
["ExtraQpart"] = "Soothing Spices",
}, -- [33]
{
["ExtraLine"] = "Train abilities",
["Done"] = {
1136, -- [1]
},
["TT"] = {
["y"] = -1412.7,
["x"] = -125.3,
},
["Zone"] = "1638 (Thunder Bluff)",
}, -- [34]
{
["PickUp"] = {
1205, -- [1]
},
["TT"] = {
["y"] = -1412.7,
["x"] = -125.3,
},
["Zone"] = "1638 (Thunder Bluff)",
}, -- [35]
{
["TT"] = {
["y"] = -1196.9,
["x"] = 26.8,
},
["UseFlightPath"] = 1201,
["Name"] = "Brackenwall Village, Dustwallow Marsh",
["Zone"] = "1638 (Thunder Bluff)",
}, -- [36]
{
["PickUp"] = {
1201, -- [1]
},
["TT"] = {
["y"] = -3107.6,
["x"] = -2824,
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [37]
{
["PickUp"] = {
1322, -- [1]
},
["TT"] = {
["y"] = -3112,
["x"] = -2891.8,
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [38]
{
["PickUp"] = {
1177, -- [1]
},
["TT"] = {
["y"] = -3372.8,
["x"] = -2820.5,
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [39]
{
["ExtraLine"] = "Theramore Infiltrator are stealthed non-agro",
["Qpart"] = {
[1322] = {
["1"] = "1",
},
[1201] = {
["1"] = "1",
},
},
["Button"] = 1,
["Zone"] = "15 (Dustwallow Marsh)",
["Trigger"] = {
["y"] = -2954.5,
["x"] = -2972.9,
},
["SpecialButton"] = "Theramore Infiltrator",
["Range"] = 43.35,
["TT"] = {
["y"] = -2954.5,
["x"] = -2972.9,
},
}, -- [40]
{
["Qpart"] = {
[1177] = {
["1"] = "1",
},
},
["Zone"] = "15 (Dustwallow Marsh)",
["Trigger"] = {
["y"] = -2582.1,
["x"] = -4021.3,
},
["Range"] = 43.29,
["TT"] = {
["y"] = -2582.1,
["x"] = -4021.3,
},
}, -- [41]
{
["PickUp"] = {
1218, -- [1]
},
["TT"] = {
["y"] = -2953.3,
["x"] = -3885.2,
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [42]
{
["Done"] = {
1218, -- [1]
},
["TT"] = {
["y"] = -2953.3,
["x"] = -3885.2,
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [43]
{
["PickUp"] = {
1206, -- [1]
},
["TT"] = {
["y"] = -2953.3,
["x"] = -3885.2,
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [44]
{
["ExtraLine"] = "Click Dirtpile",
["TT"] = {
["y"] = -2940.1,
["x"] = -3885.1,
},
["PickUp"] = {
1238, -- [1]
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [45]
{
["ExtraLine"] = "Grind on the way",
["TT"] = {
["y"] = -2646.5,
["x"] = -3436.7,
},
["PickUp"] = {
1270, -- [1]
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [46]
{
["Qpart"] = {
[1270] = {
["1"] = "1",
},
},
["Zone"] = "15 (Dustwallow Marsh)",
["Trigger"] = {
["y"] = -2714.1,
["x"] = -3458.9,
},
["RaidIcon"] = 4880,
["Range"] = 110.67,
["TT"] = {
["y"] = -2714.1,
["x"] = -3458.9,
},
}, -- [47]
{
["Qpart"] = {
[1206] = {
["1"] = "1",
},
},
["Zone"] = "15 (Dustwallow Marsh)",
["Trigger"] = {
["y"] = -2806,
["x"] = -2779.3,
},
["Range"] = 109.31,
["TT"] = {
["y"] = -2806,
["x"] = -2779.3,
},
}, -- [48]
{
["Done"] = {
1238, -- [1]
1201, -- [2]
},
["TT"] = {
["y"] = -3105.8,
["x"] = -2823.9,
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [49]
{
["PickUp"] = {
1202, -- [1]
},
["TT"] = {
["y"] = -3105.8,
["x"] = -2823.9,
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [50]
{
["Done"] = {
1322, -- [1]
},
["TT"] = {
["y"] = -3111.2,
["x"] = -2891.9,
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [51]
{
["PickUp"] = {
1323, -- [1]
},
["TT"] = {
["y"] = -3111.2,
["x"] = -2891.9,
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [52]
{
["Done"] = {
1323, -- [1]
},
["TT"] = {
["y"] = -3149.4,
["x"] = -2887.2,
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [53]
{
["Done"] = {
1177, -- [1]
},
["TT"] = {
["y"] = -3372.4,
["x"] = -2820.6,
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [54]
{
["Done"] = {
1206, -- [1]
},
["TT"] = {
["y"] = -2953.5,
["x"] = -3885.3,
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [55]
{
["ExtraLine"] = "Click Dirtpile",
["TT"] = {
["y"] = -2940.6,
["x"] = -3885.4,
},
["PickUp"] = {
1239, -- [1]
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [56]
{
["CRange"] = 1202,
["Zone"] = "15 (Dustwallow Marsh)",
["Trigger"] = {
["y"] = -3340.3,
["x"] = -4095,
},
["Range"] = 31.46,
["TT"] = {
["y"] = -3340.3,
["x"] = -4095,
},
}, -- [57]
{
["CRange"] = 1202,
["Zone"] = "15 (Dustwallow Marsh)",
["Trigger"] = {
["y"] = -3564.1,
["x"] = -4456.2,
},
["Range"] = 22.22,
["TT"] = {
["y"] = -3564.1,
["x"] = -4456.2,
},
}, -- [58]
{
["CRange"] = 1202,
["Zone"] = "15 (Dustwallow Marsh)",
["Trigger"] = {
["y"] = -3574.2,
["x"] = -4504.6,
},
["Range"] = 21.08,
["TT"] = {
["y"] = -3574.2,
["x"] = -4504.6,
},
}, -- [59]
{
["CRange"] = 1202,
["Zone"] = "15 (Dustwallow Marsh)",
["Trigger"] = {
["y"] = -3685.8,
["x"] = -4668.8,
},
["Range"] = 23.12,
["TT"] = {
["y"] = -3685.8,
["x"] = -4668.8,
},
}, -- [60]
{
["CRange"] = 1202,
["Zone"] = "15 (Dustwallow Marsh)",
["Trigger"] = {
["y"] = -3808.9,
["x"] = -4701.4,
},
["Range"] = 17.85,
["TT"] = {
["y"] = -3808.9,
["x"] = -4701.4,
},
}, -- [61]
{
["ExtraLine"] = "Loot Footlocker in the water",
["Qpart"] = {
[1202] = {
["1"] = "1",
},
},
["Zone"] = "15 (Dustwallow Marsh)",
["Trigger"] = {
["y"] = -3824.2,
["x"] = -4732.2,
},
["Range"] = 0.07,
["TT"] = {
["y"] = -3824.2,
["x"] = -4732.2,
},
}, -- [62]
{
["ExtraLine"] = "Die and spirit rez",
["Done"] = {
1202, -- [1]
1239, -- [2]
},
["TT"] = {
["y"] = -3106.7,
["x"] = -2823.9,
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [63]
{
["PickUp"] = {
1240, -- [1]
},
["TT"] = {
["y"] = -3106.7,
["x"] = -2823.9,
},
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [64]
{
["TT"] = {
["y"] = -3106.7,
["x"] = -2823.9,
},
["UseHS"] = 1270,
["Zone"] = "15 (Dustwallow Marsh)",
}, -- [65]
{
["UseFlightPath"] = 1270,
["Name"] = "Ratchet, The Barrens",
["Zone"] = "17 (The Barrens)",
["LeaveQuests"] = {
1169, -- [1]
1166, -- [2]
1107, -- [3]
1168, -- [4]
1203, -- [5]
},
["TT"] = {
["y"] = -437.4,
["x"] = -2596,
},
}, -- [66]
{
["Done"] = {
1270, -- [1]
},
["TT"] = {
["y"] = -929.3,
["x"] = -3697.2,
},
["Zone"] = "17 (The Barrens)",
}, -- [67]
{
["ExtraLine"] = "Use boat to Booty Bay",
["CRange"] = 1115,
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -14340.6,
["x"] = 1151.5,
},
["Range"] = 534.89,
["TT"] = {
["y"] = -999.6,
["x"] = -3827.4,
},
}, -- [68]
{
["PickUp"] = {
595, -- [1]
},
["LeaveQuests"] = {
1491, -- [1]
1069, -- [2]
1221, -- [3]
},
["TT"] = {
["y"] = -14411,
["x"] = 427.4,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [69]
{
["PickUp"] = {
606, -- [1]
},
["TT"] = {
["y"] = -14449.6,
["x"] = 450.8,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [70]
{
["SetHS"] = 606,
["TT"] = {
["y"] = -14458.5,
["x"] = 494.8,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [71]
{
["Done"] = {
1115, -- [1]
},
["TT"] = {
["y"] = -14453.6,
["x"] = 500.8,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [72]
{
["PickUp"] = {
1116, -- [1]
},
["TT"] = {
["y"] = -14453.6,
["x"] = 500.8,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [73]
{
["TT"] = {
["y"] = -14448.9,
["x"] = 506.5,
},
["UseFlightPath"] = 606,
["Name"] = "Grom'gol, Stranglethorn",
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [74]
{
["PickUp"] = {
572, -- [1]
},
["LeaveQuests"] = {
209, -- [1]
621, -- [2]
600, -- [3]
},
["TT"] = {
["y"] = -12412.6,
["x"] = 171.3,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [75]
{
["PickUp"] = {
629, -- [1]
},
["TT"] = {
["y"] = -12347.4,
["x"] = 161.9,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [76]
{
["Done"] = {
1240, -- [1]
},
["TT"] = {
["y"] = -12347.4,
["x"] = 161.9,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [77]
{
["Qpart"] = {
[196] = {
["1"] = "1",
},
[572] = {
["1"] = "1",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -12874.1,
["x"] = 23.2,
},
["Range"] = 110.89,
["TT"] = {
["y"] = -12874.1,
["x"] = 23.2,
},
}, -- [78]
{
["TT"] = {
["y"] = -12871.9,
["x"] = -120.3,
},
["xp"] = 1,
["Trigger"] = {
["y"] = -12871.9,
["x"] = -120.3,
},
["level"] = 39,
["Range"] = 83.79,
["Grind"] = 11951,
}, -- [79]
{
["Done"] = {
572, -- [1]
},
["TT"] = {
["y"] = -12412.6,
["x"] = 171.3,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [80]
{
["PickUp"] = {
571, -- [1]
},
["TT"] = {
["y"] = -12412.6,
["x"] = 171.3,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [81]
{
["ExtraLine"] = "Loot tablet standing against pelar",
["Qpart"] = {
[629] = {
["1"] = "1",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -12148.5,
["x"] = 636.2,
},
["Range"] = 0.15,
["TT"] = {
["y"] = -12148.5,
["x"] = 636.2,
},
}, -- [82]
{
["Done"] = {
629, -- [1]
},
["TT"] = {
["y"] = -12347.2,
["x"] = 160.9,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [83]
{
["Qpart"] = {
[577] = {
["1"] = "1",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -12034.4,
["x"] = -404.9,
},
["Range"] = 85.85,
["TT"] = {
["y"] = -12034.4,
["x"] = -404.9,
},
}, -- [84]
{
["GroupTask"] = 193,
["TT"] = {
["y"] = -12034.4,
["x"] = -404.9,
},
["Group"] = 2,
["QaskPopup"] = 193,
}, -- [85]
{
["Zone"] = "33 (Stranglethorn Vale)",
["GroupTask"] = 193,
["Range"] = 233.29,
["Qpart"] = {
[193] = {
["1"] = "1",
},
},
["Button"] = 1,
["SpecialButton"] = "Bhag'thera",
["RaidIcon"] = 728,
["Trigger"] = {
["y"] = -12379,
["x"] = -854.7,
},
["TT"] = {
["y"] = -12379,
["x"] = -854.7,
},
}, -- [86]
{
["Done"] = {
196, -- [1]
},
["TT"] = {
["y"] = -11628.3,
["x"] = -54.4,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [87]
{
["GroupTask"] = 193,
["Done"] = {
193, -- [1]
},
["TT"] = {
["y"] = -11617.4,
["x"] = -48.4,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [88]
{
["PickUp"] = {
197, -- [1]
},
["TT"] = {
["y"] = -11629.2,
["x"] = -54.5,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [89]
{
["TT"] = {
["y"] = -11629.2,
["x"] = -54.5,
},
["UseHS"] = 595,
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [90]
{
["Done"] = {
577, -- [1]
},
["TT"] = {
["y"] = -14469.1,
["x"] = 416.5,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [91]
{
["PickUp"] = {
628, -- [1]
},
["TT"] = {
["y"] = -14469.1,
["x"] = 416.5,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [92]
{
["ExtraLine"] = "Exit BB",
["CRange"] = 595,
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -14301.2,
["x"] = 437,
},
["Range"] = 7.15,
["TT"] = {
["y"] = -14301.2,
["x"] = 437,
},
}, -- [93]
{
["CRange"] = 595,
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -14249.4,
["x"] = 331.5,
},
["Range"] = 11.85,
["TT"] = {
["y"] = -14249.4,
["x"] = 331.5,
},
}, -- [94]
{
["ExtraLine"] = "Click Scroll on Barrel",
["Done"] = {
595, -- [1]
},
["TT"] = {
["y"] = -14125.6,
["x"] = 479.7,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [95]
{
["PickUp"] = {
597, -- [1]
},
["TT"] = {
["y"] = -14125.6,
["x"] = 479.7,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [96]
{
["CRange"] = 606,
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -14231.1,
["x"] = 265.3,
},
["Range"] = 44.11,
["TT"] = {
["y"] = -14231.1,
["x"] = 265.3,
},
}, -- [97]
{
["Qpart"] = {
[571] = {
["1"] = "1",
},
[606] = {
["1"] = "1",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -13994.9,
["x"] = 179,
},
["Range"] = 88.9,
["TT"] = {
["y"] = -13994.9,
["x"] = 179,
},
}, -- [98]
{
["ExtraLine"] = "back to BB",
["CRange"] = 606,
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -14257.2,
["x"] = 339.1,
},
["Range"] = 8.85,
["TT"] = {
["y"] = -14257.2,
["x"] = 339.1,
},
}, -- [99]
{
["Done"] = {
606, -- [1]
},
["TT"] = {
["y"] = -14299.6,
["x"] = 504.9,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [100]
{
["PickUp"] = {
607, -- [1]
},
["TT"] = {
["y"] = -14299.6,
["x"] = 504.9,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [101]
{
["Done"] = {
597, -- [1]
},
["TT"] = {
["y"] = -14410.5,
["x"] = 427.6,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [102]
{
["PickUp"] = {
599, -- [1]
},
["TT"] = {
["y"] = -14410.5,
["x"] = 427.6,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [103]
{
["Done"] = {
607, -- [1]
},
["TT"] = {
["y"] = -14448.7,
["x"] = 449.7,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [104]
{
["ExtraLine"] = "Up in the Inn",
["TT"] = {
["y"] = -14450.4,
["x"] = 497.8,
},
["PickUp"] = {
209, -- [1]
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [105]
{
["ExtraLine"] = "Ontop of the Inn",
["Done"] = {
599, -- [1]
},
["TT"] = {
["y"] = -14444.4,
["x"] = 487.1,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [106]
{
["TT"] = {
["y"] = -14448.1,
["x"] = 506,
},
["UseFlightPath"] = 571,
["Name"] = "Grom'gol, Stranglethorn",
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [107]
{
["Done"] = {
571, -- [1]
},
["TT"] = {
["y"] = -12412.6,
["x"] = 170.8,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [108]
{
["PickUp"] = {
573, -- [1]
},
["TT"] = {
["y"] = -12412.6,
["x"] = 170.8,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [109]
{
["PickUp"] = {
598, -- [1]
},
["TT"] = {
["y"] = -12346.8,
["x"] = 161.8,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [110]
{
["SetHS"] = 573,
["TT"] = {
["y"] = -12434.2,
["x"] = 211.9,
},
["Zone"] = "33 (Stranglethorn Vale)",
}, -- [111]
{
["Qpart"] = {
[209] = {
["1"] = "1",
},
},
["Zone"] = "33 (Stranglethorn Vale)",
["Trigger"] = {
["y"] = -12707.3,
["x"] = -769.1,
},
["LeaveQuests"] = {
587, -- [1]
2932, -- [2]
584, -- [3]
621, -- [4]
609, -- [5]
604, -- [6]
600, -- [7]
},
["Range"] = 333.04,
["TT"] = {
["y"] = -12707.3,
["x"] = -769.1,
},
}, -- [112]
{
["ShowMobsOnMap"] = 667,
["Trigger"] = {
["y"] = -12709.4,
["x"] = -472.5,
},
["Range"] = 442.15,
["ShowMobsOnMap2"] = 1195,
["Grind"] = 11951,
["xp"] = 1,
["level"] = 40,
["ShowMobsOnMap3"] = 1,
["TT"] = {
["y"] = -12709.4,
["x"] = -472.5,
},
}, -- [113]
{
["ExtraLine"] = "Use hs or run and go to UC with Zep",
["CRange"] = 573,
["Zone"] = "85 (Tirisfal Glades)",
["Trigger"] = {
["y"] = 2306.2,
["x"] = -469.3,
},
["Range"] = 548.46,
["TT"] = {
["y"] = -12417.8,
["x"] = 208.3,
},
}, -- [114]
{
["ExtraLine"] = "go to Undercity",
["CRange"] = 573,
["Zone"] = "85 (Tirisfal Glades)",
["Trigger"] = {
["y"] = 1875.2,
["x"] = 238.2,
},
["Range"] = 7.65,
["TT"] = {
["y"] = 1875.2,
["x"] = 238.2,
},
}, -- [115]
{
["ExtraLine"] = "Learn your 40 abilitys then use FP",
["UseFlightPath"] = 573,
["Name"] = "Hammerfall, Arathi",
["Zone"] = "1497 (Undercity)",
["TT"] = {
["y"] = 1567.3,
["x"] = 266.2,
},
}, -- [116]
{
["ExtraLine"] = "If you got 240FirstAid Learn Heavy Magewave",
["CRange"] = 573,
["Zone"] = "45 (Arathi Highlands)",
["Trigger"] = {
["y"] = -1018.8,
["x"] = -3509.5,
},
["RaidIcon"] = 12920,
["Range"] = 4.36,
["TT"] = {
["y"] = -1018.8,
["x"] = -3509.5,
},
}, -- [117]
{
["ExtraLine"] = "Time to run alot (Badlands)",
["CRange"] = 573,
["Zone"] = "45 (Arathi Highlands)",
["Trigger"] = {
["y"] = -1808.4,
["x"] = -2425.7,
},
["Range"] = 34.25,
["TT"] = {
["y"] = -1808.4,
["x"] = -2425.7,
},
}, -- [118]
{
["CRange"] = 573,
["Zone"] = "45 (Arathi Highlands)",
["Trigger"] = {
["y"] = -2181.4,
["x"] = -2454.4,
},
["Range"] = 17.19,
["TT"] = {
["y"] = -2181.4,
["x"] = -2454.4,
},
}, -- [119]
{
["CRange"] = 573,
["Zone"] = "45 (Arathi Highlands)",
["Trigger"] = {
["y"] = -2275.5,
["x"] = -2502.8,
},
["Range"] = 23.28,
["TT"] = {
["y"] = -2275.5,
["x"] = -2502.8,
},
}, -- [120]
{
["CRange"] = 573,
["Zone"] = "11 (Wetlands)",
["Trigger"] = {
["y"] = -2476.7,
["x"] = -2498.7,
},
["Range"] = 16.89,
["TT"] = {
["y"] = -2476.7,
["x"] = -2498.7,
},
}, -- [121]
{
["CRange"] = 573,
["Zone"] = "11 (Wetlands)",
["Trigger"] = {
["y"] = -3458.5,
["x"] = -2628.6,
},
["Range"] = 56.46,
["TT"] = {
["y"] = -3458.5,
["x"] = -2628.6,
},
}, -- [122]
{
["CRange"] = 573,
["Zone"] = "11 (Wetlands)",
["Trigger"] = {
["y"] = -4087,
["x"] = -2621.7,
},
["Range"] = 12.01,
["TT"] = {
["y"] = -4087,
["x"] = -2621.7,
},
}, -- [123]
{
["CRange"] = 573,
["Zone"] = "11 (Wetlands)",
["Trigger"] = {
["y"] = -4092.7,
["x"] = -2425.5,
},
["Range"] = 8.01,
["TT"] = {
["y"] = -4092.7,
["x"] = -2425.5,
},
}, -- [124]
{
["CRange"] = 573,
["Zone"] = "11 (Wetlands)",
["Trigger"] = {
["y"] = -4008.2,
["x"] = -2381.2,
},
["Range"] = 11.8,
["TT"] = {
["y"] = -4008.2,
["x"] = -2381.2,
},
}, -- [125]
{
["CRange"] = 573,
["Zone"] = "11 (Wetlands)",
["Trigger"] = {
["y"] = -4080.7,
["x"] = -2464.7,
},
["Range"] = 13.08,
["TT"] = {
["y"] = -4080.7,
["x"] = -2464.7,
},
}, -- [126]
{
["CRange"] = 573,
["Zone"] = "11 (Wetlands)",
["Trigger"] = {
["y"] = -4307.9,
["x"] = -2464.5,
},
["Range"] = 14.47,
["TT"] = {
["y"] = -4307.9,
["x"] = -2464.5,
},
}, -- [127]
{
["CRange"] = 573,
["Zone"] = "11 (Wetlands)",
["Trigger"] = {
["y"] = -4423.1,
["x"] = -2481,
},
["Range"] = 6.03,
["TT"] = {
["y"] = -4423.1,
["x"] = -2481,
},
}, -- [128]
{
["CRange"] = 573,
["Zone"] = "11 (Wetlands)",
["Trigger"] = {
["y"] = -4450,
["x"] = -2674.5,
},
["Range"] = 7.77,
["TT"] = {
["y"] = -4450,
["x"] = -2674.5,
},
}, -- [129]
{
["CRange"] = 573,
["Zone"] = "11 (Wetlands)",
["Trigger"] = {
["y"] = -4485.2,
["x"] = -2689.5,
},
["Range"] = 8.71,
["TT"] = {
["y"] = -4485.2,
["x"] = -2689.5,
},
}, -- [130]
{
["CRange"] = 573,
["Zone"] = "38 (Loch Modan)",
["Trigger"] = {
["y"] = -4679.6,
["x"] = -2699.1,
},
["Range"] = 15.74,
["TT"] = {
["y"] = -4679.6,
["x"] = -2699.1,
},
}, -- [131]
{
["CRange"] = 573,
["Zone"] = "38 (Loch Modan)",
["Trigger"] = {
["y"] = -5230.8,
["x"] = -3048.1,
},
["Range"] = 32.77,
["TT"] = {
["y"] = -5230.8,
["x"] = -3048.1,
},
}, -- [132]
{
["CRange"] = 573,
["Zone"] = "38 (Loch Modan)",
["Trigger"] = {
["y"] = -5488.1,
["x"] = -3146.1,
},
["Range"] = 41.93,
["TT"] = {
["y"] = -5488.1,
["x"] = -3146.1,
},
}, -- [133]
{
["CRange"] = 573,
["Zone"] = "38 (Loch Modan)",
["Trigger"] = {
["y"] = -5856.7,
["x"] = -3276.2,
},
["Range"] = 23.68,
["TT"] = {
["y"] = -5856.7,
["x"] = -3276.2,
},
}, -- [134]
{
["CRange"] = 573,
["Zone"] = "3 (Badlands)",
["Trigger"] = {
["y"] = -6154.7,
["x"] = -3369.5,
},
["Range"] = 20.79,
["TT"] = {
["y"] = -6154.7,
["x"] = -3369.5,
},
}, -- [135]
{
["CRange"] = 573,
["Zone"] = "3 (Badlands)",
["Trigger"] = {
["y"] = -6699.9,
["x"] = -3226.3,
},
["Range"] = 22.42,
["TT"] = {
["y"] = -6699.9,
["x"] = -3226.3,
},
}, -- [136]
{
["Done"] = {
1106, -- [1]
},
["TT"] = {
["y"] = -6763.4,
["x"] = -3129.1,
},
["Zone"] = "3 (Badlands)",
}, -- [137]
{
["UpdMapID"] = 1,
},
},
}
if (not AAPClassic.Path) then
AAPClassic.Path = {}
end
for AAP_index,AAP_value in pairs(AAPClassic.PathH2) do
AAPClassic.Path[AAP_index] = AAP_value
end
AAPClassic.PathH2 = nil
end
|
function newBol(elin, lin, actB)
-- num name[1] as[2] value[3] --
vname, vvall = sys.midle(lin, ' as ')
-- A other variable has the same name
if actB[vname] ~= nil then sys.error(elin, 'c', "Another bol variable has the same name of this.")
-- If is a number --
elseif isBol(vvall, actB) then
-- Update value --
if actB[vvall] ~= nil then vvall = actB[vvall] end
-- Update variable --
if vvall == 'yes' then actB[vname] = true end
if vvall == 'not' then actB[vname] = false end
-- Return bol's table --
return actB
-- Wrong type --
else sys.error(elin, 'c', "This is not a boolean value.") end
end
function isBol(vall, actB)
-- Pure bool --
if vall == 'yes' or vall == 'not' then return true
-- Stored bool --
elseif actB[vall] ~= nil then return true
-- Is not a bool --
else return false end
end
|
--[[
This database of players who violate or use third-party software.
Our development team is trying to improve the quality of the game and get rid of unwanted players.
All rights reserved Awesomium Team.
--]]
AWTeam.Config = {
system = true, -- On/off system
ban = true, -- On/off system
bansystem = "fadmin", -- Ban system. Available: serverguard; ulx; fadmin
bantime = 0, -- Time ban
delayupdate = 60 -- Delay update API php
}
AWTeam.Menu = {
ColorBG = Color(62, 69, 76), -- Color menu
ColorFont = Color(255, 246, 229), -- Color font
ColoButton = Color(33, 133, 197), -- Color button
Font = "Default", -- Custom font or default https://wiki.facepunch.com/gmod/Default_Fonts
Language = "EN", -- WIP (is not work)
}
AWTeam.Translate = {
NameMenu = "All in one - Ban system",
AddBan = "See/Add ban...",
Search = "Search...",
ColumnName = "Name",
ColumnSteam = "SteamID",
ColumnReason = "Reason",
}
|
local ts = require("telescope")
ts.setup {
defaults = {
vimgrep_arguments = {
"rg",
"--no-heading",
"--smart-case"
},
prompt_prefix = " ",
selection_caret = " ",
layout_config = {
horizontal = {
prompt_position = "bottom",
preview_width = 0.55,
results_width = 0.8,
},
vertical = {
mirror = false,
},
width = 0.87,
height = 0.80,
preview_cutoff = 120,
},
borderchars = { "─", "│", "─", "│", "╭", "╮", "╯", "╰" },
file_ignore_patterns = { "node_modules", "build", "dist", "target", ".git" }
}
}
|
-- project
set_project("co")
-- set xmake minimum version
set_xmakever("2.2.5")
-- set common flags
set_languages("c++11")
set_optimize("faster") -- -O2
set_warnings("all") -- -Wall
if is_plat("macosx", "linux") then
add_cxflags("-g3")
if is_plat("macosx") then
add_cxflags("-fno-pie")
end
add_syslinks("pthread", "dl")
end
if is_plat("windows") then
add_cxflags("-Ox", "-fp:fast", "-EHsc")
end
-- include sub-projects
includes("base", "rpcgen", "test", "unitest/base")
|
-- Agent script
-- The moonagents table is preloaded in the agent's _ENV, so it need not be require()d.
-- local moonagents = require("moonagents") -- this should give an error
-- Make moonagents functions global in this _ENV:
moonagents.global_functions()
-- Just to make things a little interesting, the salute is given with a delay.
local delay = 1.2 -- seconds
local T = timer(delay,"T_EXPIRED")
local function Start()
print("Please, wait "..delay.." seconds ...")
timer_start(T)
next_state("Waiting")
end
local function TExpired()
print("... Hello World!")
stop()
end
start_transition(Start)
transition("Waiting", "T_EXPIRED", TExpired)
|
-- config: (lint (only var:set-loop))
for x = 0, 10 do
x = x + 1
end
for k in pairs(_G) do
k = 0
end
|
--[[
FiveM Scripts
Copyright C 2018 Sighmir
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
at your option any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
]]
Menu = {}
Menu.GUI = {}
Menu.buttonCount = 0
Menu.selection = 0
Menu.hidden = true
MenuTitle = "Garage"
function Menu.addButton(name, func,args)
local yoffset = 0.2
local xoffset = 0
local xmin = 0.0
local xmax = 0.3
local ymin = 0.05
local ymax = 0.05
Menu.GUI[Menu.buttonCount+1] = {}
Menu.GUI[Menu.buttonCount+1]["name"] = name
Menu.GUI[Menu.buttonCount+1]["func"] = func
Menu.GUI[Menu.buttonCount+1]["args"] = args
Menu.GUI[Menu.buttonCount+1]["active"] = false
Menu.GUI[Menu.buttonCount+1]["xmin"] = xmin + xoffset
Menu.GUI[Menu.buttonCount+1]["ymin"] = ymin * (Menu.buttonCount + 0.01) +yoffset
Menu.GUI[Menu.buttonCount+1]["xmax"] = xmax
Menu.GUI[Menu.buttonCount+1]["ymax"] = ymax
Menu.buttonCount = Menu.buttonCount+1
end
function Menu.updateSelection()
if IsControlJustPressed(3, 173) then
if(Menu.selection < Menu.buttonCount -1 ) then
Menu.selection = Menu.selection +1
else
Menu.selection = 0
end
elseif IsControlJustPressed(3, 172) then
if(Menu.selection > 0)then
Menu.selection = Menu.selection -1
else
Menu.selection = Menu.buttonCount-1
end
elseif IsControlJustPressed(3, 176) then
MenuCallFunction(Menu.GUI[Menu.selection +1]["func"], Menu.GUI[Menu.selection +1]["args"])
end
local iterator = 0
for id, settings in ipairs(Menu.GUI) do
Menu.GUI[id]["active"] = false
if(iterator == Menu.selection ) then
Menu.GUI[iterator +1]["active"] = true
end
iterator = iterator +1
end
end
function Menu.renderGUI()
if not Menu.hidden then
Menu.renderButtons()
Menu.updateSelection()
end
end
function Menu.renderBox(xMin,xMax,yMin,yMax,color1,color2,color3,color4)
DrawRect(xMin, yMin,xMax, yMax, color1, color2, color3, color4);
end
function Menu.renderButtons()
local yoffset = 0.2
local xoffset = 0
SetTextFont(1)
SetTextProportional(0)
SetTextScale(1.0, 1.0)
SetTextColour(255, 255, 255, 255)
SetTextDropShadow(0, 0, 0, 0,255)
SetTextEdge(1, 0, 0, 0, 255)
SetTextDropShadow()
SetTextOutline()
SetTextCentre(2)
SetTextEntry("STRING")
AddTextComponentString(string.upper(MenuTitle))
DrawText((xoffset + 0.07), (yoffset - 0.065 - 0.0125 ))
Menu.renderBox(xoffset,0.3,(yoffset - 0.05),0.05,20,20,255,150)
for id, settings in pairs(Menu.GUI) do
local screen_w = 0
local screen_h = 0
screen_w, screen_h = GetScreenResolution(0, 0)
if(settings["active"]) then
boxColor = {255,255,255,150}
SetTextColour(0, 0, 0, 255)
else
boxColor = {0,0,0,150}
SetTextColour(255, 255, 255, 255)
end
SetTextFont(0)
SetTextScale(0.0,0.35)
SetTextCentre(false)
-- SetTextDropShadow(0, 0, 0, 0, 0)
SetTextEdge(0, 0, 0, 0, 0)
SetTextEntry("STRING")
AddTextComponentString(settings["name"])
DrawText(settings["xmin"]+ 0.01, (settings["ymin"] - 0.0125 ))
Menu.renderBox(settings["xmin"] ,settings["xmax"], settings["ymin"], settings["ymax"],boxColor[1],boxColor[2],boxColor[3],boxColor[4])
end
end
function ClearMenu()
--Menu = {}
Menu.GUI = {}
Menu.buttonCount = 0
Menu.selection = 0
end
function MenuCallFunction(fnc, arg)
_G[fnc](arg)
end
|
--[[
TheNexusAvenger
Tests the NexusTextBox class.
--]]
local NexusUnitTesting = require("NexusUnitTesting")
local NexusPluginFramework = require(game:GetService("ReplicatedStorage"):WaitForChild("NexusPluginFramework"))
local NexusTextBox = NexusPluginFramework:GetResource("UI.Input.NexusTextBox")
--[[
Test that the constructor works without failing.
--]]
NexusUnitTesting:RegisterUnitTest("Constructor",function(UnitTest)
local CuT = NexusTextBox.new()
UnitTest:AssertEquals(CuT.ClassName,"NexusTextBox","Class name is incorrect.")
UnitTest:AssertEquals(CuT.Name,"NexusTextBox","Name is incorrect.")
UnitTest:AssertEquals(tostring(CuT),"NexusTextBox","Name is incorrect.")
end)
return true
|
--[[Author: Pizzalol
Date: 14.03.2015.
Fires several axes in a cone, damaging and slowing enemies]]
function WhirlingAxesRanged( keys )
local caster = keys.caster
local caster_location = caster:GetAbsOrigin()
local target_point = keys.target_points[1]
local ability = keys.ability
local ability_level = ability:GetLevel() - 1
-- Ability variables
local axe_width = ability:GetLevelSpecialValueFor("axe_width", ability_level)
local axe_speed = ability:GetLevelSpecialValueFor("axe_speed", ability_level)
local axe_range = ability:GetLevelSpecialValueFor("axe_range", ability_level)
local axe_spread = ability:GetLevelSpecialValueFor("axe_spread", ability_level)
local axe_count = ability:GetLevelSpecialValueFor("axe_count", ability_level)
local axe_projectile = keys.axe_projectile
caster.whirling_axes_ranged_hit_table = {}
-- Vision
local vision_radius = ability:GetLevelSpecialValueFor("vision_radius", ability_level)
-- Initial angle calculation
local angle = axe_spread / axe_count -- The angle between the axes
local direction = (target_point - caster_location):Normalized()
local axe_angle_count = math.floor(axe_count / 2) -- Number of axes for each direction
local angle_left = QAngle(0, angle, 0) -- Rotation angle to the left
local angle_right = QAngle(0, -angle, 0) -- Rotation angle to the right
-- Check if its an uneven number of axes
-- If it is then create the middle axe
if axe_count % 2 ~= 0 then
local projectileTable =
{
EffectName = axe_projectile,
Ability = ability,
vSpawnOrigin = caster_location,
vVelocity = direction * axe_speed,
fDistance = axe_range,
fStartRadius = axe_width,
fEndRadius = axe_width,
Source = caster,
bHasFrontalCone = false,
bReplaceExisting = false,
iUnitTargetTeam = ability:GetAbilityTargetTeam(),
iUnitTargetFlags = DOTA_UNIT_TARGET_FLAG_NONE,
iUnitTargetType = ability:GetAbilityTargetType(),
bProvidesVision = true,
iVisionRadius = vision_radius,
iVisionTeamNumber = caster:GetTeamNumber()
}
ProjectileManager:CreateLinearProjectile(projectileTable)
end
local new_angle = QAngle(0,0,0) -- Rotation angle
-- Create axes that spread to the right
for i = 1, axe_angle_count do
-- Angle calculation
new_angle.y = angle_right.y * i
-- Calculate the new position after applying the angle and then get the direction of it
local position = RotatePosition(caster_location, new_angle, target_point)
local position_direction = (position - caster_location):Normalized()
-- Create the axe projectile
local projectileTable =
{
EffectName = axe_projectile,
Ability = ability,
vSpawnOrigin = caster_location,
vVelocity = position_direction * axe_speed,
fDistance = axe_range,
fStartRadius = axe_width,
fEndRadius = axe_width,
Source = caster,
bHasFrontalCone = false,
bReplaceExisting = false,
iUnitTargetTeam = ability:GetAbilityTargetTeam(),
iUnitTargetFlags = DOTA_UNIT_TARGET_FLAG_NONE,
iUnitTargetType = ability:GetAbilityTargetType(),
bProvidesVision = true,
iVisionRadius = vision_radius,
iVisionTeamNumber = caster:GetTeamNumber()
}
ProjectileManager:CreateLinearProjectile(projectileTable)
end
-- Create axes that spread to the left
for i = 1, axe_angle_count do
-- Angle calculation
new_angle.y = angle_left.y * i
-- Calculate the new position after applying the angle and then get the direction of it
local position = RotatePosition(caster_location, new_angle, target_point)
local position_direction = (position - caster_location):Normalized()
-- Create the axe projectile
local projectileTable =
{
EffectName = axe_projectile,
Ability = ability,
vSpawnOrigin = caster_location,
vVelocity = position_direction * axe_speed,
fDistance = axe_range,
fStartRadius = axe_width,
fEndRadius = axe_width,
Source = caster,
bHasFrontalCone = false,
bReplaceExisting = false,
iUnitTargetTeam = ability:GetAbilityTargetTeam(),
iUnitTargetFlags = DOTA_UNIT_TARGET_FLAG_NONE,
iUnitTargetType = ability:GetAbilityTargetType(),
bProvidesVision = true,
iVisionRadius = vision_radius,
iVisionTeamNumber = caster:GetTeamNumber()
}
ProjectileManager:CreateLinearProjectile(projectileTable)
end
end
--[[
Author: Noya
Used by: Pizzalol
Date: 14.03.2015.
Levels up the ability_name to the same level of the ability that runs this
]]
function LevelUpAbility( event )
local caster = event.caster
local this_ability = event.ability
local this_abilityName = this_ability:GetAbilityName()
local this_abilityLevel = this_ability:GetLevel()
-- The ability to level up
local ability_name = event.ability_name
local ability_handle = caster:FindAbilityByName(ability_name)
local ability_level = ability_handle:GetLevel()
-- Check to not enter a level up loop
if ability_level ~= this_abilityLevel then
ability_handle:SetLevel(this_abilityLevel)
end
end
--[[Author: Pizzalol
Date: 18.03.2015.
Checks if the target has been hit before and then does logic according to that]]
function WhirlingAxesRangedHit( keys )
local caster = keys.caster
local target = keys.target
local ability = keys.ability
local ability_level = ability:GetLevel() - 1
local sound = keys.sound
local axe_damage = ability:GetLevelSpecialValueFor("axe_damage", ability_level)
-- Check if the target has been hit before
local hit_check = false
for _,unit in ipairs(caster.whirling_axes_ranged_hit_table) do
if unit == target then
hit_check = true
break
end
end
-- If the target hasnt been hit before then insert it into the hit table to keep track of it
if not hit_check then
table.insert(caster.whirling_axes_ranged_hit_table, target)
-- Play the sound
EmitSoundOn(sound, target)
-- Initialize the damage table and deal damage to the target
local damage_table = {}
damage_table.attacker = caster
damage_table.victim = target
damage_table.ability = ability
damage_table.damage_type = ability:GetAbilityDamageType()
damage_table.damage = axe_damage
ApplyDamage(damage_table)
end
end
|
abyssal_underlord_dark_rift_oaa = class(AbilityBaseClass)
LinkLuaModifier("modifier_underlord_dark_rift_oaa_stun", "abilities/oaa_dark_rift.lua", LUA_MODIFIER_MOTION_NONE)
--------------------------------------------------------------------------------
function abyssal_underlord_dark_rift_oaa:GetAOERadius()
return self:GetSpecialValueFor("radius")
end
function abyssal_underlord_dark_rift_oaa:GetCastAnimation()
return ACT_DOTA_CAST_ABILITY_4
end
function abyssal_underlord_dark_rift_oaa:GetAssociatedSecondaryAbilities()
return "abyssal_underlord_cancel_dark_rift_oaa"
end
function abyssal_underlord_dark_rift_oaa:OnUpgrade()
local abilityLevel = self:GetLevel()
local sub_ability = self:GetCaster():FindAbilityByName("abyssal_underlord_cancel_dark_rift_oaa")
-- Check to not enter a level up loop
if sub_ability and sub_ability:GetLevel() ~= abilityLevel then
sub_ability:SetLevel(abilityLevel)
end
end
function abyssal_underlord_dark_rift_oaa:OnSpellStart()
local caster = self:GetCaster()
local originCaster = caster:GetAbsOrigin()
local pos = self:GetCursorPosition()
local minRange = self:GetSpecialValueFor("minimum_range")
local vectorTarget = pos - originCaster
-- if the target point is too close, push it out to minimum range
if vectorTarget:Length2D() < minRange then
pos = originCaster + ( vectorTarget:Normalized() * minRange )
end
local radius = self:GetSpecialValueFor( "radius" )
self.originSecond = GetGroundPosition( Vector(pos.x, pos.y, 0), caster)
-- Remove particles of the previous spell instance in case of refresher
if caster.partPortal1 then
ParticleManager:DestroyParticle( caster.partPortal1, false )
ParticleManager:ReleaseParticleIndex( caster.partPortal1 )
caster.partPortal1 = nil
end
if caster.partPortal2 then
ParticleManager:DestroyParticle( caster.partPortal2, false )
ParticleManager:ReleaseParticleIndex( caster.partPortal2 )
caster.partPortal2 = nil
end
-- Remove stored location of the previous spell instance in case of refresher
caster.original_cast_location = nil
-- create portal particle on caster location
local partPortal1 = ParticleManager:CreateParticle( "particles/units/heroes/heroes_underlord/abyssal_underlord_dark_rift_portal.vpcf", PATTACH_WORLDORIGIN, caster )
ParticleManager:SetParticleControl( partPortal1, 0, originCaster )
ParticleManager:SetParticleControl( partPortal1, 2, originCaster )
ParticleManager:SetParticleControl( partPortal1, 1, Vector( radius, 1, 1 ) )
-- create portal particle on destination
local partPortal2 = ParticleManager:CreateParticle( "particles/units/heroes/heroes_underlord/abyssal_underlord_dark_rift_portal.vpcf", PATTACH_WORLDORIGIN, caster )
ParticleManager:SetParticleControl( partPortal2, 0, self.originSecond )
ParticleManager:SetParticleControl( partPortal2, 2, self.originSecond )
ParticleManager:SetParticleControl( partPortal2, 1, Vector( radius, 1, 1 ) )
-- play cast sounds
caster:EmitSound( "Hero_AbyssalUnderlord.DarkRift.Cast" )
--EmitSoundOnLocationWithCaster( self.originSecond, "Hero_AbyssalUnderlord.DarkRift.Cast", caster )
-- EmitSoundOnLocationWithCaster needs to be replaced with EmitSound on invisible thinker/dummy entity
-- and StopSound when portals close, otherwise its annoying
-- Store the location of the caster on the caster itself for the sub ability
caster.original_cast_location = originCaster
-- Store particles indexes on caster itself
caster.partPortal1 = partPortal1
caster.partPortal2 = partPortal2
end
function abyssal_underlord_dark_rift_oaa:OnChannelFinish(bInterrupted)
local caster = self:GetCaster()
-- Stop sound in all cases when channeling finishes
caster:StopSound( "Hero_AbyssalUnderlord.DarkRift.Cast" )
-- Function for removing portal particles
local function RemoveParticles()
if caster.partPortal1 then
ParticleManager:DestroyParticle( caster.partPortal1, false )
ParticleManager:ReleaseParticleIndex( caster.partPortal1 )
caster.partPortal1 = nil
end
if caster.partPortal2 then
ParticleManager:DestroyParticle( caster.partPortal2, false )
ParticleManager:ReleaseParticleIndex( caster.partPortal2 )
caster.partPortal2 = nil
end
end
-- Remove stuff if interrupted and don't continue
if bInterrupted then
RemoveParticles()
caster.original_cast_location = nil
return
end
local originParent = caster:GetAbsOrigin()
local radius = self:GetSpecialValueFor("radius")
-- destroy all trees in portals
GridNav:DestroyTreesAroundPoint( originParent, radius, true )
GridNav:DestroyTreesAroundPoint( self.originSecond, radius, true )
-- play teleportation sounds
caster:EmitSound("Hero_AbyssalUnderlord.DarkRift.Aftershock")
EmitSoundOnLocationWithCaster( self.originSecond, "Hero_AbyssalUnderlord.DarkRift.Aftershock", caster )
-- emit warp particles
local part = ParticleManager:CreateParticle( "particles/units/heroes/heroes_underlord/abbysal_underlord_darkrift_warp.vpcf", PATTACH_WORLDORIGIN, caster )
ParticleManager:SetParticleControl( part, 1, Vector( radius, 1, 1 ) )
ParticleManager:SetParticleControl( part, 2, originParent )
local part2 = ParticleManager:CreateParticle( "particles/units/heroes/heroes_underlord/abbysal_underlord_darkrift_warp.vpcf", PATTACH_WORLDORIGIN, caster )
ParticleManager:SetParticleControl( part2, 1, Vector( radius, 1, 1 ) )
ParticleManager:SetParticleControl( part2, 2, self.originSecond )
local targetTeam = self:GetAbilityTargetTeam()
local targetType = self:GetAbilityTargetType()
local targetFlags = self:GetAbilityTargetFlags()
local units_in_portal = FindUnitsInRadius(caster:GetTeamNumber(), self.originSecond, nil, radius, targetTeam, targetType, targetFlags, FIND_ANY_ORDER, false)
-- Original stun duration
local stun_duration = self:GetSpecialValueFor("stun_duration")
-- Teleport the caster
caster:SetAbsOrigin(self.originSecond)
FindClearSpaceForUnit(caster, self.originSecond, true)
-- Disjoint disjointable/dodgeable projectiles
ProjectileManager:ProjectileDodge(caster)
-- Teleportation particle
local part3 = ParticleManager:CreateParticle( "particles/units/heroes/heroes_underlord/abbysal_underlord_darkrift_ambient_end.vpcf", PATTACH_ABSORIGIN_FOLLOW, caster )
ParticleManager:SetParticleControl( part3, 2, originParent )
ParticleManager:SetParticleControl( part3, 5, originParent )
local damageTable = {}
damageTable.attacker = caster
damageTable.damage = self:GetSpecialValueFor("damage")
damageTable.damage_type = self:GetAbilityDamageType()
damageTable.ability = self
-- Find all enemies and apply effects of the spell: stun them and damage them
for _, unit in pairs(units_in_portal) do
-- Status Resistance Fix
local actual_duration = unit:GetValueChangedByStatusResistance(stun_duration)
unit:AddNewModifier(caster, self, "modifier_underlord_dark_rift_oaa_stun", {duration = actual_duration} )
-- Apply damage
damageTable.victim = unit
ApplyDamage(damageTable)
end
-- Particles releasing indexes
ParticleManager:ReleaseParticleIndex(part)
ParticleManager:ReleaseParticleIndex(part2)
ParticleManager:ReleaseParticleIndex(part3)
-- If somebody was affected by this spell, delay the portal particle removal, otherwise remove immediately
if #units_in_portal > 0 then
Timers:CreateTimer(stun_duration+0.5, function()
RemoveParticles()
end)
else
RemoveParticles()
caster.original_cast_location = nil
end
end
---------------------------------------------------------------------------------------------------
modifier_underlord_dark_rift_oaa_stun = class(ModifierBaseClass)
function modifier_underlord_dark_rift_oaa_stun:IsHidden()
return false
end
function modifier_underlord_dark_rift_oaa_stun:IsDebuff()
return true
end
function modifier_underlord_dark_rift_oaa_stun:IsPurgable()
return true
end
function modifier_underlord_dark_rift_oaa_stun:IsStunDebuff()
return true
end
function modifier_underlord_dark_rift_oaa_stun:GetEffectName()
return "particles/generic_gameplay/generic_stunned.vpcf"
end
function modifier_underlord_dark_rift_oaa_stun:GetEffectAttachType()
return PATTACH_OVERHEAD_FOLLOW
end
function modifier_underlord_dark_rift_oaa_stun:DeclareFunctions()
return {
MODIFIER_PROPERTY_OVERRIDE_ANIMATION,
}
end
function modifier_underlord_dark_rift_oaa_stun:GetOverrideAnimation()
return ACT_DOTA_DISABLED
end
function modifier_underlord_dark_rift_oaa_stun:CheckState()
return {
[MODIFIER_STATE_STUNNED] = true,
}
end
|
game.ReplicatedStorage.Remotes.GiveClicks.OnServerEvent:Connect(function(player)
player.leaderstats.Clicks.Value = player.leaderstats.Clicks.Value + player.ClickData["Click_Multiplier"].Value
player.ClickData.TotalClicks.Value = player.ClickData.TotalClicks.Value + player.ClickData["Click_Multiplier"].Value
wait(2)
end)
|
--
-- tests/base/test_table.lua
-- Automated test suite for the new table functions.
-- Copyright (c) 2008-2013 Jason Perkins and the Premake project
--
local suite = test.declare("table")
local t
--
-- table.contains() tests
--
function suite.contains_OnContained()
t = { "one", "two", "three" }
test.istrue( table.contains(t, "two") )
end
function suite.contains_OnNotContained()
t = { "one", "two", "three" }
test.isfalse( table.contains(t, "four") )
end
--
-- table.flatten() tests
--
function suite.flatten_OnMixedValues()
t = { "a", { "b", "c" }, "d" }
test.isequal({ "a", "b", "c", "d" }, table.flatten(t))
end
--
-- table.implode() tests
--
function suite.implode()
t = { "one", "two", "three", "four" }
test.isequal("[one], [two], [three], [four]", table.implode(t, "[", "]", ", "))
end
--
-- table.indexof() tests
--
function suite.indexof_returnsIndexOfValueFound()
local idx = table.indexof({ "a", "b", "c" }, "b")
test.isequal(2, idx)
end
--
-- table.isempty() tests
--
function suite.isempty_ReturnsTrueOnEmpty()
test.istrue(table.isempty({}))
end
function suite.isempty_ReturnsFalseOnNotEmpty()
test.isfalse(table.isempty({ 1 }))
end
function suite.isempty_ReturnsFalseOnNotEmptyMap()
test.isfalse(table.isempty({ name = 'premake' }))
end
function suite.isempty_ReturnsFalseOnNotEmptyMapWithFalseKey()
test.isfalse(table.isempty({ [false] = 0 }))
end
--
-- table.insertsorted() tests
--
function suite.insertsorted()
local t = {}
table.insertsorted(t, 5)
table.insertsorted(t, 2)
table.insertsorted(t, 8)
table.insertsorted(t, 4)
table.insertsorted(t, 1)
test.istrue(#t == 5)
test.istrue(t[1] == 1)
test.istrue(t[2] == 2)
test.istrue(t[3] == 4)
test.istrue(t[4] == 5)
test.istrue(t[5] == 8)
end
|
local state = 0
function get_one()
state = 1
return 1
end
function get_two()
state = 2
return 2
end
assert(get_one() == 1 or get_two() == 1 or 0 == 1)
assert(state == 1)
assert((get_one() == 1 and get_two() == 1) == false)
assert((get_one() == 2 and get_two() == 2) == false)
assert((get_one() == 1 or get_two() == 1) == true)
assert((get_one() == 2 or get_two() == 2) == true)
assert((get_one() == 1 and get_two() == 2) == true)
assert((get_one() == 2 or get_two() == 1) == false)
|
-- _NSword Prototype [masterepico] --
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Meshes : Head, Torso, Wedge, Sphere, Cylinder, Brick, Cone, Devo, Corner, Diamond, Ring, Tetrahedron, Crown, Dominus, Claws
-- HowToUse : Variable = CreatePart(parts(table), name, color, transparency, reflectance, size, vector, rotation, cancollide, meshtype, weldpart)
-- [ TEST ] Fade remove for non-canCollide part
-- [ TEST ] accelerate reflectance end
-- [ TEST / 2 ] fix conditions for horisontal slice (first bug maybe fixed, if sYPos is greater than pYPos....)
-- GRAB WITH LIGHTING
-- Spider to control
-- Dodge while gtarget
-- HOVERSWORD WITH PALE ANIMATION !!!
local _CODE = "_NSword"
--==================================================-VARIABLES-==================================================--
local player = game:GetService("Players").LocalPlayer
local char = player.Character
local huma = char:FindFirstChild("Humanoid")
local initialized, disconnectRequest = false, false
local model,suited,use,processing,animate,gtarget,gs = false,false,false,false,false,true
local w,a,s,d,z = false,false,false,false,false
local bindKeyDown,bindKeyUp = false,false
local hit,trail,lighting,shirt,bin = false, false, false, false, false
local bPos, bGyro = Instance.new("BodyPosition"), Instance.new("BodyGyro")
local delete = true
local prt,_jnt,_mdl,_prt,_kup,_kdn,_mse,ms = {}
local combo = 0
local tol = 4
local mode = 0
local cfs = false
local jumping = false
local buttonDown = false
local shirtColor = "Lime green"
local pantsColor = "Really red"
local attachColor = "Really red"
local sheathColor = "Really red"
local swordHandleColor = "Really red"
local gunColor = "Really red"
local gunTakePos = nil
local defaultWalkspeed = huma.WalkSpeed
--==================================================-MAIN-CODE-==================================================--
bPos.maxForce = Vector3.new(0,math.huge,0)
bGyro.maxTorque = Vector3.new(math.huge,math.huge,math.huge)
if player == nil or char == nil then return end
if not player.Backpack:FindFirstChild(_CODE) then
bin = Instance.new("HopperBin")
bin.Name = _CODE
bin.Parent = player:FindFirstChild("Backpack")
else bin = player.Backpack[_CODE] end
if bin ~= nil then
script.Name = "_NScript"
script.Parent = nil
end
local part = {
head = char:FindFirstChild("Head"),
tors = char:FindFirstChild("Torso"),ftor,
larm = char:FindFirstChild("Left Arm"),
rarm = char:FindFirstChild("Right Arm"),
lleg = char:FindFirstChild("Left Leg"),
rleg = char:FindFirstChild("Right Leg")}
local motor = {
neck = part.tors:FindFirstChild("Neck"),
lsho = part.tors:FindFirstChild("Left Shoulder"),
rsho = part.tors:FindFirstChild("Right Shoulder"),
lhip = part.tors:FindFirstChild("Left Hip"),
rhip = part.tors:FindFirstChild("Right Hip")}
for i,obj in pairs(char:GetChildren()) do
if obj:IsA("CharacterMesh") then
obj:Destroy()
end
end
function JoinInit()
while processing do wait() end
processing = true
if char:FindFirstChild("Shirt") then
shirt = char.Shirt
shirt.Parent = nil
end
part.ftor = part.tors:Clone()
part.ftor.Name = "_Torso2"
part.ftor.BrickColor = BrickColor.new("Really red")
local joint = {neck,tors,lsho,rsho,lhip,rhip}
joint.tors = Instance.new("Weld", part.tors)
joint.tors.Name = "Torso_WELD"
joint.tors.Part0 = part.tors
joint.tors.Part1 = part.ftor
part.ftor.Parent = char
part.tors.Transparency = 1
for i,join in pairs (motor) do
local weld
if not join.Parent:FindFirstChild(join.Name.."_WELD") then
weld = Instance.new("Weld", join.Parent)
weld.Name = join.Name.."_WELD"
else weld = join.Parent[join.Name.."_WELD"] end
if tostring(i) == "lsho" then
weld.C0 = CFrame.new(-1.5,0.5,0)
weld.C1 = CFrame.new(0,0.5,0)
elseif tostring(i) == "rsho" then
weld.C0 = CFrame.new(1.5,0.5,0)
weld.C1 = CFrame.new(0,0.5,0)
elseif tostring(i) == "neck" then
weld.C0 = CFrame.new(0,1,0)
weld.C1 = CFrame.new(0,-0.5,0)
else
weld.C0 = join.C0
weld.C1 = join.C1
end
weld.Part1 = join.Part1
if tostring(i) ~= "neck" then
join.Part0 = part.ftor
else
weld.Part0 = part.ftor
end
joint[i] = weld
end
initialized = true
processing = false
return joint
end
function Bind(join)
if join == nil then return end
if _jnt == nil then return end
if part.ftor == nil then return end
if not _jnt[join]:IsA("Weld") then return end
if not motor[join]:IsA("Motor6D") then return end
motor[join].Part0 = nil
_jnt[join].Part0 = part.ftor
end
function Release(join)
if join == nil then return end
if _jnt == nil then return end
if part.ftor == nil then return end
if not _jnt[join]:IsA("Weld") then return end
if not motor[join]:IsA("Motor6D") then return end
_jnt[join].Part0 = nil
motor[join].Part0 = part.ftor
end
function SuitInit()
while processing do wait() end
processing = true
if initialized then
local suitModel
if not char:FindFirstChild(_CODE.." Suit") then
suitModel = Instance.new("Model", char)
suitModel.Name = _CODE.." Suit"
model = true
else suitModel = char[_CODE.." Suit"] model = true end
processing = false
return suitModel
else processing = false end
end
function CF(join,cf,rot,speed,ctin,s)
if s and cfs then ctin = true animate = false return end
if join == nil then return end
local def,done = join.C0,false
local cf = cf or def
local rot = rot or (def - def.p)
local speed = speed or 1
local x1,y1,z1 = def:toEulerAnglesXYZ()
local x2,y2,z2 = rot:toEulerAnglesXYZ()
coroutine.wrap(function()
if speed ~= 1 then
for i = 0,1,speed do
if s and cfs then ctin = true animate = false return end
join.C0 = CFrame.new(
(def.p.X * (1 - i) + cf.p.X * i),
(def.p.Y * (1 - i) + cf.p.Y * i),
(def.p.Z * (1 - i) + cf.p.Z * i)) *
CFrame.fromEulerAnglesXYZ(
(x1 * (1 - i) + x2 * i),
(y1 * (1 - i) + y2 * i),
(z1 * (1 - i) + z2 * i))
wait(0.015)
end
end if s and cfs then ctin = true animate = false else join.C0 = CFrame.new(cf.p) * CFrame.fromEulerAnglesXYZ(x2,y2,z2) end done = true
end)()
if not ctin and speed ~= 1 then while not done do wait(0.015) end end
end
function CreatePart(tab, name, color, transparency, reflectance, size, cframe, rotation, cancollide, anchored, meshType, scaleSize, weldPart, parent)
if model and _mdl ~= nil and part.ftor ~= nil then
local returnTable = {part,weld}
if scaleSize == nil then scaleSize = false end
local suitPart = Instance.new("Part")
suitPart.Name = name
suitPart.BrickColor = BrickColor.new(color)
suitPart.Anchored = anchored
suitPart.Locked = true
suitPart.CanCollide = cancollide
suitPart.Transparency = transparency
suitPart.Reflectance = reflectance
suitPart.FormFactor = Enum.FormFactor.Custom
suitPart.BottomSurface = "Smooth"
suitPart.TopSurface = "Smooth"
suitPart.Size = size
if meshType ~= nil then
if meshType == "Cone" then
CreateMesh("http://www.roblox.com/asset/?id=1033714", suitPart, scaleSize)
elseif meshType == "Corner" then
CreateMesh("http://www.roblox.com/asset/?id=11294911", suitPart, scaleSize)
elseif meshType == "Devo" then
CreateMesh("http://www.roblox.com/asset/?id=15720044", suitPart, scaleSize)
elseif meshType == "Diamond" then
CreateMesh("http://www.roblox.com/asset/?id=9756362", suitPart, scaleSize)
elseif meshType == "Ring" then
CreateMesh("http://www.roblox.com/asset/?id=3270017", suitPart, scaleSize)
elseif meshType == "Tetrahedron" then
CreateMesh("http://www.roblox.com/asset/?id=11294922", suitPart, scaleSize)
elseif meshType == "Crown" then
CreateMesh("http://www.roblox.com/asset/?id=20329976", suitPart, scaleSize)
elseif meshType == "Claws" then
CreateMesh("http://www.roblox.com/asset/?id=10681506", suitPart, scaleSize)
elseif meshType == "Cylinder" then
local mesh = Instance.new("CylinderMesh", suitPart)
if scaleSize then mesh.Scale = suitPart.Size end
elseif meshType == "Brick" then
local mesh = Instance.new("BlockMesh", suitPart)
if scaleSize then mesh.Scale = suitPart.Size end
else
local mesh = Instance.new("SpecialMesh", suitPart)
if scaleSize then mesh.Scale = suitPart.Size end
mesh.MeshType = meshType
end
end
if weldPart == nil then suitPart.CFrame = cframe * rotation else
local weld = Instance.new("Weld", _mdl)
weld.Part1 = suitPart
weld.Part0 = weldPart
weld.Name = tostring(weld.Part0).."_TO_"..tostring(weld.Part1)
weld.C0 = cframe * rotation
returnTable.weld = weld
end
returnTable.part = suitPart
suitPart.Parent = parent or _mdl
if tab ~= nil then tab[name] = returnTable else return returnTable end
end
end
function CreateMesh(id, part, scaleSize)
local mesh = Instance.new("SpecialMesh", part)
if scaleSize then mesh.Scale = part.Size end
mesh.MeshType = Enum.MeshType.FileMesh
mesh.MeshId = id
return mesh
end
function LoadSuit()
while processing do wait() end
processing = true
if not suited then
CreatePart(prt, "torso_1", shirtColor, 0, 0, Vector3.new(2.015,2.11,1.015), CFrame.new(0,-0.04,0), CFrame.Angles(0,0,0),false,false, "Brick",false,part.ftor)
CreatePart(prt, "torso_2", attachColor, 0, 0, Vector3.new(2.70,0.2,1.06), CFrame.new(-0.05,0.125,0), CFrame.Angles(0,0,math.rad(45)),false,false, "Brick",false,prt.torso_1.part)
CreatePart(prt, "torso_3", attachColor, 0, 0, Vector3.new(2.15,0.2,1.06), CFrame.new(-0.025,-0.9,0), CFrame.Angles(0,0,math.rad(-2)),false,false, "Brick",false,prt.torso_1.part)
CreatePart(prt, "torso_4", "Lime green", 0, 1, Vector3.new(0.3,0.2,0.3), CFrame.new(0.6,0,-0.45), CFrame.Angles(math.rad(90),0,0),false,false, "Cylinder",false,prt.torso_3.part)
CreatePart(prt, "arm_1", shirtColor, 0, 0, Vector3.new(1.015,0.8,1.015), CFrame.new(0,0.615,0), CFrame.Angles(0,0,0),false,false, "Brick",false,part.rarm)
CreatePart(prt, "arm_2", shirtColor, 0, 0, Vector3.new(1.015,1.6,1.015), CFrame.new(0,0.215,0), CFrame.Angles(0,0,0),false,false, "Brick",false,part.larm)
CreatePart(prt, "sheath_1", sheathColor, 0, 0, Vector3.new(0.425,4.5,0.2), CFrame.new(-0.25,0,0.63), CFrame.Angles(0,0,math.rad(-90)),false, false,"Brick", false, prt.torso_2.part)
CreatePart(prt, "sheath_2", sheathColor, 0, 0,Vector3.new(0.21,0.6,0.415),CFrame.new(0,-2.55,0),CFrame.Angles(0,math.rad(90),math.rad(180)),false,false,"Wedge",false,prt.sheath_1.part)
CreatePart(prt, "sheath_3", "Really red", 0, 0,Vector3.new(0.25,0.6,0.2),CFrame.new(0,1.8,0.05),CFrame.Angles(0,0,0),false,false,"Diamond",true,prt.sheath_1.part)
CreatePart(prt, "sheath_4", "Pastel Blue", 0, 0.3,Vector3.new(0.2,0.6,0.2),CFrame.new(0,1.3,0.1),CFrame.Angles(0,0,math.rad(27)),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "sheath_5", "Medium blue", 0, 0.3,Vector3.new(0.2,0.6,0.2),CFrame.new(0,1.1,0.1),CFrame.Angles(0,0,math.rad(27)),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "sheath_6", "Bright blue", 0, 0.3,Vector3.new(0.2,0.6,0.2),CFrame.new(0,0.9,0.1),CFrame.Angles(0,0,math.rad(27)),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "sheath_7", "Lime green", 0, 0,Vector3.new(0.2,2,0.2),CFrame.new(0.2,0,0),CFrame.Angles(0,0,0),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "sheath_8", "Lime green", 0, 0,Vector3.new(0.2,2,0.2),CFrame.new(-0.2,0,0),CFrame.Angles(0,0,0),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "sheath_9", "Lime green", 0, 0,Vector3.new(0.2,0.72,0.2),CFrame.new(0.09,2.0125,0.13),CFrame.Angles(math.rad(35),0,-math.rad(20)),false,false,"Brick",true,prt.sheath_7.part)
CreatePart(prt, "sheath_10", "Lime green", 0, 0,Vector3.new(0.2,0.72,0.2),CFrame.new(-0.09,2.0125,0.13),CFrame.Angles(math.rad(35),0,math.rad(20)),false,false,"Brick",true,prt.sheath_8.part)
CreatePart(prt, "sheath_11", "Lime green", 0, 1,Vector3.new(0.25,0.425,0.25),CFrame.new(0,0.085,0),CFrame.Angles(0,0,0),false,false,"Brick",true,prt.sheath_9.part)
CreatePart(prt, "sheath_12", "Lime green", 0, 1,Vector3.new(0.25,0.425,0.25),CFrame.new(0,0.085,0),CFrame.Angles(0,0,0),false,false,"Brick",true,prt.sheath_10.part)
CreatePart(prt, "sheath_13", "Lime green", 0, 1,Vector3.new(0.2,0.7,0.2),CFrame.new(0,0,0),CFrame.Angles(math.rad(-145),0,0),false,false,"Brick",true,prt.sheath_2.part)
CreatePart(prt, "sheath_14", "Lime green", 0, 1,Vector3.new(0.2,1.11,0.2),CFrame.new(0.072,-0.025,0.1),CFrame.Angles(0,0,0),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "gunsheath_1", sheathColor, 0, 0, Vector3.new(0.5,0.9,0.7), CFrame.new(1.2,-0.2,0), CFrame.Angles(math.rad(-20),0,0),false, false,"Brick",true,prt.torso_3.part)
CreatePart(prt, "gunsheath_2", "Lime green", 0, 1, Vector3.new(0.3,0.2,0.3), CFrame.new(0.1,0.2,-0.225), CFrame.Angles(0,0,0),false,false, "Brick",true,prt.gunsheath_1.part)
CreatePart(prt, "gunsheath_3", "Lime green", 0, 1, Vector3.new(0.3,0.2,0.3), CFrame.new(0,-0.1,0), CFrame.Angles(0,0,0),false,false, "Brick",true,prt.gunsheath_2.part)
CreatePart(prt, "gunsheath_4", "Lime green", 0, 1, Vector3.new(0.3,0.2,0.3), CFrame.new(0,-0.1,0), CFrame.Angles(0,0,0),false, false,"Brick",true,prt.gunsheath_3.part)
CreatePart(prt, "gun_1", gunColor, 0, 0, Vector3.new(0.4,0.775,0.5), CFrame.new(0,0.6,0.15), CFrame.Angles(math.rad(-105),0,0),false, false,"Brick",true,prt.gunsheath_1.part)
CreatePart(prt, "gun_2", gunColor, 0, 0, Vector3.new(0.4,0.5,0.9), CFrame.new(0,0.2,-0.275), CFrame.Angles(math.rad(15),0,0),false, false,"Brick",true,prt.gun_1.part)
CreatePart(prt, "gun_3", gunColor, 0, 0, Vector3.new(0.4,0.45,0.55), CFrame.new(0,0.1,0.26), CFrame.Angles(0,0,0),false, false,"Brick",true,prt.gun_2.part)
CreatePart(prt, "gun_4", "Lime green", 0, 1, Vector3.new(0.3,0.4,0.55), CFrame.new(0,0,-0.3), CFrame.Angles(0,0,0),false, false,"Brick",true,prt.gun_3.part)
CreatePart(prt, "gun_5", gunColor, 0, 0, Vector3.new(0.4,0.45,0.6), CFrame.new(0,0,-0.55), CFrame.Angles(0,0,0),false,false, "Brick",true,prt.gun_3.part)
CreatePart(prt, "gun_6", gunColor, 0, 0, Vector3.new(0.4,0.45,0.2), CFrame.new(0,0,-0.22), CFrame.Angles(0,0,0),false, false,"Brick",true,prt.gun_3.part)
CreatePart(prt, "gun_7", gunColor, 0, 0, Vector3.new(0.4,0.45,0.2), CFrame.new(0,0,-0.3), CFrame.Angles(0,0,0),false, false,"Brick",true,prt.gun_3.part)
CreatePart(prt, "gun_8", gunColor, 0, 0, Vector3.new(0.2,0.2,0.5), CFrame.new(0,-0.25,0.18), CFrame.Angles(0,0,0),false,false, "Brick",true,prt.gun_2.part)
CreatePart(prt, "gun_9", gunColor, 0, 0, Vector3.new(0.2,0.2,0.5), CFrame.new(0,0.105,-0.105), CFrame.Angles(math.rad(90),0,0),false,false, "Brick",true,prt.gun_8.part)
CreatePart(prt, "gun_10", gunColor, 0, 0, Vector3.new(0.2,0.2,0.5), CFrame.new(0,0.1725,-0.03), CFrame.Angles(math.rad(90),0,0),false,false, "Brick",true,prt.gun_8.part)
CreatePart(prt, "gunbullet", "Lime green", 0, 0, Vector3.new(0.325,0.2,0.325), CFrame.new(0,0,-0.42), CFrame.Angles(math.rad(90),0,0),false,false, "Cylinder",true,prt.gun_7.part)
CreatePart(prt, "gunpointer", "Lime green", 0, 0, Vector3.new(0.275,0.2,0.275), CFrame.new(0,-0.065,-0.39), CFrame.Angles(math.rad(90),0,0),false,false, "Cylinder",true,prt.gun_2.part)
CreatePart(prt, "nairod7_1", "Lime green", 0, 1,Vector3.new(0.2,0.43,0.2),CFrame.new(0,-2,0.1),CFrame.Angles(0,0,math.rad(90)),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_2", "Lime green", 0, 1,Vector3.new(0.2,0.45,0.2),CFrame.new(0,-1.93,0.1),CFrame.Angles(0,0,math.rad(130)),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_3", "Lime green", 0, 1,Vector3.new(0.2,0.43,0.2),CFrame.new(0,-1.86,0.1),CFrame.Angles(0,0,math.rad(90)),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_4", "Lime green", 0, 1,Vector3.new(0.2,0.43,0.2),CFrame.new(0,-1.74,0.1),CFrame.Angles(0,0,math.rad(60)),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_5", "Lime green", 0, 1,Vector3.new(0.2,0.43,0.2),CFrame.new(0,-1.66,0.1),CFrame.Angles(0,0,math.rad(110)),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_6", "Lime green", 0, 1,Vector3.new(0.2,0.275,0.2),CFrame.new(0.025,-1.7,0.1),CFrame.Angles(0,0,0),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_7", "Lime green", 0, 1,Vector3.new(0.2,0.43,0.2),CFrame.new(0,-1.54,0.1),CFrame.Angles(0,0,math.rad(90)),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_8", "Lime green", 0, 1,Vector3.new(0.2,0.43,0.2),CFrame.new(0,-1.44,0.1),CFrame.Angles(0,0,math.rad(90)),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_9", "Lime green", 0, 1,Vector3.new(0.2,0.34,0.2),CFrame.new(-0.072,-1.37,0.1),CFrame.Angles(0,0,0),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_10", "Lime green", 0, 1,Vector3.new(0.2,0.2,0.2),CFrame.new(-0.05,-1.332,0.1),CFrame.Angles(0,0,math.rad(90)),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_11", "Lime green", 0, 1,Vector3.new(0.2,0.34,0.2),CFrame.new(-0.01,-1.37,0.1),CFrame.Angles(0,0,0),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_12", "Lime green", 0, 1,Vector3.new(0.2,0.36,0.2),CFrame.new(0.035,-1.3825,0.1),CFrame.Angles(0,0,math.rad(145)),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_13", "Lime green", 0, 1,Vector3.new(0.2,0.36,0.2),CFrame.new(-0.072,-1.19,0.1),CFrame.Angles(0,0,0),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_14", "Lime green", 0, 1,Vector3.new(0.2,0.43,0.2),CFrame.new(0,-1.24,0.1),CFrame.Angles(0,0,math.rad(90)),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_15", "Lime green", 0, 1,Vector3.new(0.2,0.43,0.2),CFrame.new(0,-1.12,0.1),CFrame.Angles(0,0,math.rad(90)),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_16", "Lime green", 0, 1,Vector3.new(0.2,0.36,0.2),CFrame.new(0.072,-1.19,0.1),CFrame.Angles(0,0,0),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_17", "Lime green", 0, 1,Vector3.new(0.2,0.43,0.2),CFrame.new(0,-1.02,0.1),CFrame.Angles(0,0,math.rad(90)),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_18", "Lime green", 0, 1,Vector3.new(0.2,0.39,0.2),CFrame.new(-0.0375,-0.96,0.1),CFrame.Angles(0,0,math.rad(145)),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_19", "Lime green", 0, 1,Vector3.new(0.2,0.39,0.2),CFrame.new(0.0375,-0.96,0.1),CFrame.Angles(0,0,math.rad(35)),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_20", "Lime green", 0, 1,Vector3.new(0.2,0.36,0.2),CFrame.new(-0.072,-0.78,0.1),CFrame.Angles(0,0,0),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_21", "Lime green", 0, 1,Vector3.new(0.2,0.43,0.2),CFrame.new(0,-0.77,0.1),CFrame.Angles(0,0,math.rad(60)),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "nairod7_22", "Lime green", 0, 1,Vector3.new(0.2,0.2,0.2),CFrame.new(0.072,-2.12,0.1),CFrame.Angles(0,0,0),false,false,"Brick",true,prt.sheath_1.part)
CreatePart(prt, "sword_1", swordHandleColor, 0, 0, Vector3.new(0.4,0.9,0.35), CFrame.new(0,2.715,0), CFrame.Angles(0,0,0),false,false, "Brick",true,prt.sheath_1.part)
CreatePart(prt, "sword_2", "Lime green", 0, 0, Vector3.new(0.5,2.135,0.25), CFrame.new(0,-2.68,0), CFrame.Angles(0,0,0),false,false, "Brick",true,prt.sword_1.part)
CreatePart(prt, "sword_3", "Lime green", 0, 0, Vector3.new(0.25,0.55,0.5), CFrame.new(0,-5.1,0), CFrame.Angles(0,math.rad(90),math.rad(180)),false,false,"Wedge",true,prt.sword_1.part)
CreatePart(prt, "sword_4", swordHandleColor, 0, 0, Vector3.new(0.9,0.3,0.55), CFrame.new(0,-0.4,0), CFrame.Angles(0,0,0),false, false,"Brick",true,prt.sword_1.part)
CreatePart(prt, "sword_5", "Lime green", 1, 0, Vector3.new(1.8,4.4,0.2), CFrame.new(0.7,0,0), CFrame.Angles(0,0,0),false, false,"Brick",false,prt.sword_2.part)
elseif prt.torso_1 ~= nil then prt.torso_1.weld.Part0 = part.ftor end
suited = true
processing = false
return prt
end -- +7
function Trail(val)
if not _prt.sword_1.part then return end
trail = val
if trail then
coroutine.wrap(function()
local last = _prt.sword_3.part.CFrame.p
while use and trail and _prt.sword_3.part ~= nil do wait(.02)
local new = _prt.sword_3.part.CFrame.p
local mag = (last - new).magnitude
local pos = CFrame.new(last, new) * CFrame.Angles(math.rad(-90), 0, 0)
local trl = Instance.new("Part")
local msh = Instance.new("CylinderMesh", trl)
trl.Name = "NSword_TRAIL"
trl.Anchored = true
trl.Locked = true
trl.CanCollide = false
trl.FormFactor = Enum.FormFactor.Custom
trl.BrickColor = BrickColor.new("Lime green")
trl.Transparency = 0.3
trl.Size = Vector3.new(0.2, mag, 0.2)
msh.Scale = Vector3.new(1.8, 1, 1.8)
trl.CFrame = pos * CFrame.new(0,mag/2,0)
trl.Parent = game.Workspace
coroutine.wrap(function() for i = trl.Transparency, 1, .05 do trl.Transparency = i msh.Scale = msh.Scale - Vector3.new(.15, 0, .15) wait(.02) end pcall(function() trl:Destroy() end) end)()
last = _prt.sword_3.part.CFrame.p
end
end)()
end
end
function LightingGen(init,target,ran,delay,size,damage)
local CL = function()
local lght = Instance.new("Part")
local msh = Instance.new("CylinderMesh", lght)
local size = size or .3
msh.Scale = Vector3.new(size,1,size)
lght.Name = "NSword_LIGHT"
lght.Anchored = true
lght.Locked = true
lght.CanCollide = false
lght.Reflectance = .4
lght.FormFactor = Enum.FormFactor.Custom
lght.BrickColor = BrickColor.new("Lime green")
lght.Transparency = 0.5
lght.Parent = char
return lght
end
local delay, cPos = delay or .03
local rand = Vector3.new(math.random(-ran,ran)/10, math.random(-ran,ran)/10, math.random(-ran,ran)/10)
local mPos = (init - target).magnitude
local dLgt = math.random(1,5)
local dLgt = dLgt/10
local rVec = init + (target - init) * dLgt
local dVec = rVec - init
local gPos = CFrame.new(init, rVec + rand) * CFrame.Angles(math.rad(-90), 0, 0)
local rMag = (init - rVec + rand).magnitude
for i = dLgt, 1 - dLgt, dLgt do
local cPrt = CL()
cPrt.Size = Vector3.new(.2,rMag,.2)
cPrt.CFrame = gPos * CFrame.new(0,rMag/2,0)
cPos = gPos * CFrame.new(0,rMag,0)
cPrt.Touched:connect(function(part)
if (part.Parent:FindFirstChild("Humanoid") or part.Parent:FindFirstChild("Zombie")) then
if game.Players:GetPlayerFromCharacter(part.Parent) ~= player.Name then
local humanoid = part.Parent:FindFirstChild("Humanoid") or part.Parent:FindFirstChild("Zombie")
local dmg = damage or 10
humanoid:TakeDamage(dmg)
end
end
end)
coroutine.wrap(function() wait(delay) pcall(function() cPrt:Destroy() end) end)()
if i <= 1 - dLgt * 2 then
rVec = init + (target - init) * (i + dLgt)
rand = Vector3.new(math.random(-ran,ran)/10, math.random(-ran,ran)/10, math.random(-ran,ran)/10)
gPos = CFrame.new(cPos.p, rVec + rand) * CFrame.Angles(math.rad(-90), 0, 0)
rMag = (cPos.p - rVec + rand).magnitude
end
end
gPos = CFrame.new(cPos.p, target) * CFrame.Angles(math.rad(-90), 0, 0)
rMag = (cPos.p - target).magnitude
local cPrt = CL()
cPrt.Size = Vector3.new(.2,rMag,.2)
cPrt.CFrame = gPos * CFrame.new(0,rMag/2,0)
cPrt.Touched:connect(function(part)
if (part.Parent:FindFirstChild("Humanoid") or part.Parent:FindFirstChild("Zombie")) then
if game.Players:GetPlayerFromCharacter(part.Parent) ~= player.Name then
local humanoid = part.Parent:FindFirstChild("Humanoid") or part.Parent:FindFirstChild("Zombie")
local dmg = damage or 10
humanoid:TakeDamage(dmg)
end
end
end)
coroutine.wrap(function() wait(delay) pcall(function() cPrt:Destroy() end) end)()
end
function SwordEquip(force)
if processing and not force then return end
processing,cfs = true,true
if suited then
Bind("rsho")
CF(_jnt.rsho, nil, CFrame.Angles(0, 0, math.rad(90)), .05, true)
CF(_prt.sword_1.weld, CFrame.new(0,4.5,0), nil, .05, true)
for i = 0, 1, .05 do
_prt.sword_1.part.Transparency = i
_prt.sword_2.part.Transparency = i
_prt.sword_3.part.Transparency = i
_prt.sword_4.part.Transparency = i
wait(.015)
end
_prt.sword_1.part.Transparency = 1
_prt.sword_2.part.Transparency = 1
_prt.sword_3.part.Transparency = 1
_prt.sword_4.part.Transparency = 1
_prt.sword_1.weld.Part0 = part.rarm
CF(_prt.sword_1.weld, CFrame.new(0, -1, -0.25), CFrame.Angles(0, math.rad(90), 0))
for i = 0, 1, .05 do
_prt.sword_1.part.Transparency = 1 - i
_prt.sword_2.part.Transparency = 1 - i
_prt.sword_3.part.Transparency = 1 - i
_prt.sword_4.part.Transparency = 1 - i
wait(.015)
end
_prt.sword_1.part.Transparency = 0
_prt.sword_2.part.Transparency = 0
_prt.sword_3.part.Transparency = 0
_prt.sword_4.part.Transparency = 0
Bind("lsho")
huma.WalkSpeed = 45
CF(_jnt.lsho, nil, CFrame.Angles(0, 0, math.rad(-5)), .07, true)
CF(_prt.sword_1.weld, nil, CFrame.Angles(math.rad(90), math.rad(90), 0), .07, true)
CF(_jnt.rsho, nil, CFrame.Angles(0, 0, math.rad(5)), .07)
end
mode,processing,cfs = 1, false, false
Walk()
end
function SwordUnequip(force)
if processing and not force then return end
processing,cfs = true,true
if suited then
CF(_jnt.neck, nil, CFrame.Angles(0, 0, 0), .2, true)
CF(_jnt.tors, nil, CFrame.Angles(0, 0, 0), .2, true)
CF(_jnt.lsho, CFrame.new(-1.5,0.5,0), CFrame.Angles(0, 0, math.rad(-5)), .2, true)
CF(_jnt.rsho, nil, CFrame.Angles(math.rad(100), math.rad(90), 0), .07)
Trail(true)
CF(_prt.sword_1.weld, nil, CFrame.Angles(0, math.rad(90), 0), .15, true)
CF(_jnt.rsho, nil, CFrame.Angles(0, 0, math.rad(90)), .15)
Trail(false)
for i = 0, 1, .05 do
_prt.sword_1.part.Transparency = i
_prt.sword_2.part.Transparency = i
_prt.sword_3.part.Transparency = i
_prt.sword_4.part.Transparency = i
wait(.015)
end
_prt.sword_1.part.Transparency = 1
_prt.sword_2.part.Transparency = 1
_prt.sword_3.part.Transparency = 1
_prt.sword_4.part.Transparency = 1
_prt.sword_1.weld.Part0 = _prt.sheath_1.part
CF(_prt.sword_1.weld, CFrame.new(0, 4.5, 0), CFrame.Angles(0, 0, 0))
CF(_prt.sword_1.weld, CFrame.new(0,2.715,0), CFrame.Angles(0, 0, 0), .05, true)
for i = 0, 1, .05 do
_prt.sword_1.part.Transparency = 1 - i
_prt.sword_2.part.Transparency = 1 - i
_prt.sword_3.part.Transparency = 1 - i
_prt.sword_4.part.Transparency = 1 - i
wait(.015)
end
_prt.sword_1.part.Transparency = 0
_prt.sword_2.part.Transparency = 0
_prt.sword_3.part.Transparency = 0
_prt.sword_4.part.Transparency = 0
huma.WalkSpeed = defaultWalkspeed
CF(_jnt.lsho, nil, CFrame.Angles(0, 0, 0), .07, true)
CF(_jnt.rsho, nil, CFrame.Angles(0, 0, 0), .07)
Release("rsho")
Release("lsho")
end
mode,processing,cfs = 0, false, false
end
function GunEquip(force)
if processing and not force then return end
processing,cfs = true,true
if suited then
Bind("rsho")
CF(_jnt.rsho, CFrame.new(1.5,0.9,0), CFrame.Angles(math.rad(-20), 0, 0), 0.15)
gunTakePos = _prt.gun_1.part.CFrame:inverse() * part.rarm.CFrame
_prt.gun_1.weld.Part0 = part.rarm
_prt.gun_1.weld.C0 = gunTakePos:inverse()
CF(_jnt.rsho, CFrame.new(1.5,1.7,0), CFrame.Angles(math.rad(-20), 0, math.rad(2)), 0.15)
Bind("lsho")
CF(_jnt.lsho, nil, CFrame.Angles(math.rad(-5), 0, math.rad(-5)), 0.08, true)
CF(_jnt.rsho, CFrame.new(1.5,0.5,0), CFrame.Angles(math.rad(-10), 0, math.rad(10)), 0.08, true)
CF(_prt.gun_1.weld, _prt.gun_1.weld.C0 * CFrame.new(0.25,-0.1,0.1), nil, 0.08)
end
mode,processing,cfs = 2, false, false
Walk()
end
function GunUnequip(force)
if processing and not force then return end
processing = true
if suited then
if not gs and gtarget then gtarget = false repeat wait(.015) until gs end
CF(_jnt.neck, nil, CFrame.Angles(0, 0, 0), .2, true)
CF(_jnt.tors, nil, CFrame.Angles(0, 0, 0), .2, true)
CF(_jnt.lsho, CFrame.new(-1.5,0.5,0), CFrame.Angles(0, 0, math.rad(-5)), .2, true)
CF(_prt.gun_1.weld, gunTakePos:inverse(), (gunTakePos - gunTakePos.p):inverse(), 0.15, true)
CF(_jnt.rsho, CFrame.new(1.5,1.7,0), CFrame.Angles(math.rad(-20), 0, math.rad(2)), 0.15)
CF(_jnt.rsho, CFrame.new(1.5,0.9,0), CFrame.Angles(math.rad(-20), 0, 0), 0.15)
_prt.gun_1.weld.Part0 = _prt.gunsheath_1.part
CF(_prt.gun_1.weld, CFrame.new(0,0.6,0.15), CFrame.Angles(math.rad(-105),0,0))
CF(_jnt.rsho, CFrame.new(1.5,0.5,0), CFrame.Angles(0, 0, 0), 0.08)
Release("rsho")
Release("lsho")
end
mode,processing,cfs = 0, false, false
end
function LightEquip(force)
if processing and not force then return end
processing,cfs = true,true
if suited then
Bind("rsho")
Bind("lsho")
huma.WalkSpeed = 45
CF(_jnt.lsho, nil, CFrame.Angles(0, 0, math.rad(-5)), .07, true)
CF(_jnt.rsho, nil, CFrame.Angles(0, 0, math.rad(5)), .07)
end
mode,processing,cfs = 3, false, false
Walk()
end
function LightUnequip(force)
if processing and not force then return end
processing,cfs = true,true
if suited then
huma.WalkSpeed = defaultWalkspeed
CF(_jnt.neck, nil, CFrame.Angles(0, 0, 0), .2, true)
CF(_jnt.tors, nil, CFrame.Angles(0, 0, 0), .2, true)
CF(_jnt.lsho, nil, CFrame.Angles(0, 0, 0), .07, true)
CF(_jnt.rsho, nil, CFrame.Angles(0, 0, 0), .07)
Release("rsho")
Release("lsho")
end
mode,processing,cfs = 0, false, false
Walk()
end
function Walk()
if use then
while processing or animate do wait(.015) end
if w or a or s or d then
animate = true
if mode == 1 then
CF(_jnt.neck, nil, CFrame.Angles(0, math.rad(65), 0), .15, true, true)
CF(_jnt.tors, nil, CFrame.Angles(0, math.rad(-65), 0), .15, true, true)
CF(_jnt.rsho, nil, CFrame.Angles(math.rad(-20), 0, math.rad(70)), .15, true, true)
CF(_jnt.lsho, nil, CFrame.Angles(math.rad(30), math.rad(20), math.rad(5)), .15, false, true)
elseif mode == 2 then
CF(_jnt.neck, nil, CFrame.Angles(0, math.rad(65), 0), .15, true, true)
CF(_jnt.tors, nil, CFrame.Angles(0, math.rad(-65), 0), .15, true, true)
CF(_jnt.rsho, CFrame.new(1,0.4,-0.2), CFrame.Angles(math.rad(35), math.rad(20), math.rad(-40)), .15, true, true)
CF(_jnt.lsho, CFrame.new(-1,0.5,0), CFrame.Angles(math.rad(60), math.rad(-20), math.rad(30)), .15, false, true)
elseif mode == 3 then
CF(_jnt.rsho, nil, CFrame.Angles(math.rad(-35), 0, math.rad(10)), .15, true, true)
CF(_jnt.lsho, nil, CFrame.Angles(math.rad(-35), 0, math.rad(-10)), .15, false, true)
end
animate = false
end
end
end
function Stand()
if use then
while processing or animate do wait(.015) end
if not w and not a and not s and not d and not jumping then
animate = true
if mode ~= 0 then
CF(_jnt.neck, CFrame.new(0,1,0), CFrame.Angles(0, 0, 0), .2, true, true)
CF(_jnt.tors, CFrame.new(0,0,0), CFrame.Angles(0, 0, 0), .2, true, true)
CF(_jnt.rsho, CFrame.new(1.5,0.5,0), CFrame.Angles(0, 0, math.rad(5)), .2, true, true)
CF(_jnt.lsho, CFrame.new(-1.5,0.5,0), CFrame.Angles(0, 0, math.rad(-5)), .2, false, true)
end
animate = false
end
end
end
function FAC(num,res)
if (math.floor(num) <= res + tol and math.floor(num) >= res - tol) or (math.ceil(num) <= res + tol and math.ceil(num) >= res - tol) then return true
else return false end
end
function SliceAndKill(p)
coroutine.wrap(function()
if p.Name ~= "__NSCUTPART" and p.Name ~= "Base" and p.Name ~= "NSword_TRAIL" and p.Name ~= "NSword_LIGHT" then
if p.Parent ~= char and p.Parent ~= _mdl and not p.Parent:IsA("Hat") then
local pX,pY,pZ = p.CFrame:toEulerAnglesXYZ()
if (FAC(pX,0) or FAC(pX,180)) and (FAC(pZ,0) or FAC(pZ,180)) and p.Size.y < 0.4 then return end
pX = math.deg(pX) if pX < 0 then pX = pX * (-1) else pX = math.floor(pX) end
pZ = math.deg(pZ) if pZ < 0 then pZ = pZ * (-1) else pZ = math.floor(pZ) end
if not FAC(pX,0) and not FAC(pX,90) and not FAC(pX,180) then return end
if not FAC(pZ,0) and not FAC(pZ,90) and not FAC(pZ,180) then return end
if (not FAC(pX,0) and not FAC(pZ,0)) or (not FAC(pX,180) and not FAC(pZ,180)) then
if FAC(pX,0) and FAC(pZ,180) then
p.CFrame = p.CFrame * CFrame.Angles(0, 0, math.pi)
elseif FAC(pX,180) and FAC(pZ,0) then
p.CFrame = p.CFrame * CFrame.Angles(math.pi, 0, 0)
elseif FAC(pX,90) and (FAC(pZ,0) or FAC(pZ,180)) then
local rPart = p:Clone()
rPart.Anchored = true
rPart.Size = Vector3.new(p.Size.z,p.Size.x,p.Size.y)
rPart.CFrame = CFrame.new(p.CFrame.x, p.CFrame.y, p.CFrame.z) * CFrame.Angles(0, pY, 0)
if not p.Anchored then rPart.Anchored = false end
rPart.Parent = p.Parent
p:Remove()
p = rPart
elseif FAC(pX,90) and FAC(pZ,90) then
local rPart = p:Clone()
rPart.Anchored = true
rPart.Size = Vector3.new(p.Size.y,p.Size.z,p.Size.x)
rPart.CFrame = CFrame.new(p.CFrame.x, p.CFrame.y, p.CFrame.z) * CFrame.Angles(0, pY, 0)
if not p.Anchored then rPart.Anchored = false end
rPart.Parent = p.Parent
p:Remove()
p = rPart
elseif (FAC(pX,0) or FAC(pX,180)) and FAC(pZ,90) then
local rPart = p:Clone()
rPart.Anchored = true
rPart.Size = Vector3.new(p.Size.y,p.Size.x,p.Size.z)
rPart.CFrame = CFrame.new(p.CFrame.x, p.CFrame.y, p.CFrame.z) * CFrame.Angles(0, pY, 0)
if not p.Anchored then rPart.Anchored = false end
rPart.Parent = p.Parent
p:Remove()
p = rPart
end
end
local s = _prt.sword_3.part
local pYPos = p.CFrame.p.y - (p.Size.y/2)
local sYPos = s.CFrame.p.y
if sYPos <= pYPos or sYPos >= (pYPos + p.Size.y) then return end
local x, y, z = p.CFrame:toEulerAnglesXYZ()
local c1 = p:Clone()
local c2 = p:Clone()
local CC,TR = p.CanCollide, p.Transparency
local mat = p.Material
c1:BreakJoints()
c2:BreakJoints()
if CC then
c1.CanCollide = true
c2.CanCollide = true
c1.Anchored = false
c2.Anchored = false
else
c1.CanCollide = false
c2.CanCollide = false
c1.Anchored = true
c2.Anchored = true
end
c1.FormFactor = Enum.FormFactor.Custom
c2.FormFactor = Enum.FormFactor.Custom
c1.Material = Enum.Material.Plastic
c2.Material = Enum.Material.Plastic
c1.Size = Vector3.new(p.Size.x,sYPos-pYPos,p.Size.z)
c2.Size = Vector3.new(p.Size.x,c2.Size.y-(sYPos-pYPos),p.Size.z)
c1.CFrame = p.CFrame * CFrame.new(0, -c2.Size.y/2,0)
c2.CFrame = p.CFrame * CFrame.new(0, c1.Size.y/2,0)
c1.Name = "__NSCUTPART"
c2.Name = "__NSCUTPART"
c1.Reflectance = 0.5
c2.Reflectance = 0.5
c1.Parent = game.Workspace
c2.Parent = game.Workspace
p:Remove()
for i = 1, 20, 1 do wait(0.015)
c1.Reflectance = c1.Reflectance - 1/20
c2.Reflectance = c2.Reflectance - 1/20
end
if not CC then
coroutine.wrap(function()
for i = TR, 1, 0.05 do wait(0.015)
c1.Transparency = i
c2.Transparency = i
end pcall(function() c1:Remove() c2:Remove() end)
end)()
end
c1.Reflectance = 0
c2.Reflectance = 0
c1.Material = mat
c2.Material = mat
if CC then
c1.Name = "_NSCUTPART"
c2.Name = "_NSCUTPART"
end
end
end
end)()
end
function Hit(val)
hit = val
if hit then
coroutine.wrap(function()
local event = _prt.sword_5.part.Touched:connect(SliceAndKill)
while use and hit and _prt.sword_2 ~= nil and _prt.sword_3 ~= nil and _prt.sword_5 ~= nil do wait() end
event:disconnect()
end)()
end
end
function GunTarget()
if not ms then return end
if processing and not gtarget then return end
processing,cfs,gs = true, true, false
if not gtarget then gtarget = true
huma.WalkSpeed = 5
CF(_jnt.neck, nil, CFrame.Angles(0, math.rad(-90), 0), .1, true)
CF(_jnt.tors, nil, CFrame.Angles(0, math.rad(90), 0), .1, true)
CF(_jnt.lsho, CFrame.new(-1.5,0.5,0), CFrame.Angles(math.rad(-5), 0, math.rad(-5)), .1, true)
CF(_jnt.rsho, CFrame.new(1.5,0.5,0), CFrame.Angles(0, 0, math.rad(90)), .1, true)
pcall(function() bGyro.Parent = part.tors end)
repeat wait(.015)
if ms and not disconnectRequest then
bGyro.cframe = CFrame.new(part.tors.CFrame.p, Vector3.new(ms.Hit.p.X, part.tors.CFrame.p.Y, ms.Hit.p.Z))
end
until not gtarget or not ms gtarget = false
huma.WalkSpeed = defaultWalkspeed
pcall(function() bGyro.Parent = nil end)
CF(_jnt.neck, nil, CFrame.Angles(0, 0, 0), .1, true)
CF(_jnt.tors, nil, CFrame.Angles(0, 0, 0), .1, true)
CF(_jnt.lsho, CFrame.new(-1.5,0.5,0), CFrame.Angles(0, 0, math.rad(-5)), .1, true)
CF(_jnt.rsho, CFrame.new(1.5,0.5,0), CFrame.Angles(0, 0, math.rad(5)), .1)
end
processing,cfs,gs = false, false, true
if not gtarget and not disconnectRequest then Walk() end
end
function OnKeyDown(key) key = key:lower()
if bindKeyDown then
if key == "w" then w = true Walk() end
if key == "a" then a = true Walk() end
if key == "s" then s = true Walk() end
if key == "d" then d = true Walk() end
if key == "c" then if mode == 0 then SwordEquip() elseif mode == 1 then SwordUnequip() elseif mode == 2 then GunUnequip() SwordEquip() elseif mode == 3 then LightUnequip() SwordEquip() end end
if key == "v" then if mode == 0 then GunEquip() elseif mode == 2 then GunUnequip() elseif mode == 1 then SwordUnequip() GunEquip() elseif mode == 3 then LightUnequip() GunEquip() end end
if key == "x" then if mode == 0 then LightEquip() elseif mode == 3 then LightUnequip() elseif mode == 1 then SwordUnequip() LightEquip() elseif mode == 2 then GunUnequip() LightEquip() end end
if key == "z" then if mode == 2 and not gtarget then GunTarget() else gtarget = false end end
end
end
function OnKeyUp(key) key = key:lower()
if bindKeyUp then
if key == "w" then w = false if not a and not s and not d then Stand() end end
if key == "a" then a = false if not w and not s and not d then Stand() end end
if key == "s" then s = false if not w and not a and not d then Stand() end end
if key == "d" then d = false if not w and not a and not s then Stand() end end
end
end
function OnButton1Down() buttonDown = true combo = combo + 1
if not ms then end
if processing and not gtarget then return end
processing,cfs = true, true
if mode == 1 then
CF(_jnt.neck, nil, CFrame.Angles(0, math.rad(40), 0), .2, true)
CF(_jnt.tors, nil, CFrame.Angles(0, math.rad(-40), 0), .2, true)
CF(_prt.sword_1.weld, nil, CFrame.Angles(0, math.rad(-90), 0), .2, true)
CF(_jnt.lsho, nil, CFrame.Angles(0, 0, math.rad(-10)), .2, true)
CF(_jnt.rsho, nil, CFrame.Angles(0, math.rad(-20), math.rad(90)), .2)
pcall(function() bPos.position = Vector3.new(0,part.tors.CFrame.p.Y,0) bPos.Parent = part.tors end)
Trail(true)
Hit(true)
CF(_jnt.neck, nil, CFrame.Angles(0, math.rad(-50), 0), .15, true)
CF(_jnt.tors, nil, CFrame.Angles(0, math.rad(50), 0), .15, true)
CF(_prt.sword_1.weld, nil, CFrame.Angles(math.rad(55), math.rad(-90), 0), .15, true)
CF(_jnt.rsho, nil, CFrame.Angles(math.rad(90), math.rad(90), 0), .15)
Trail(false)
Hit(false)
if combo > 1 then combo = 2
if buttonDown then pcall(function() bPos.Parent = nil end) repeat wait(0.015) LightingGen(_prt.sword_4.part.CFrame.p,_prt.sword_3.part.CFrame.p,3,.05) until not buttonDown end
CF(_prt.sword_1.weld, nil, CFrame.Angles(math.rad(55), math.rad(90),0), .3)
Trail(true)
Hit(true)
CF(_prt.sword_1.weld, nil, CFrame.Angles(0, math.rad(90), 0), .15, true)
CF(_jnt.neck, nil, CFrame.Angles(0, math.rad(40), 0), .12, true)
CF(_jnt.tors, nil, CFrame.Angles(0, math.rad(-40), 0), .15, true)
CF(_jnt.rsho, nil, CFrame.Angles(0, math.rad(-20), math.rad(90)), .15)
pcall(function() bPos.Parent = nil end)
Trail(false)
Hit(false)
CF(_prt.sword_1.weld, nil, CFrame.Angles(math.rad(90), math.rad(90), 0), .15, true)
CF(_jnt.neck, nil, CFrame.Angles(0, 0, 0), .15, true)
CF(_jnt.tors, nil, CFrame.Angles(0, 0, 0), .15, true)
CF(_jnt.rsho, nil, CFrame.Angles(math.rad(-10), 0, 0), .15)
else
pcall(function() bPos.Parent = nil end)
CF(_jnt.neck, nil, CFrame.Angles(0, 0, 0), .15, true)
CF(_jnt.tors, nil, CFrame.Angles(0, 0, 0), .15, true)
CF(_jnt.rsho, nil, CFrame.Angles(0, 0, math.rad(5)), .15)
end
elseif mode == 2 then
--> GUN <--
elseif mode == 3 then
CF(_jnt.neck, nil, CFrame.Angles(0, math.rad(90), 0), .1, true)
CF(_jnt.tors, nil, CFrame.Angles(0, math.rad(-90), 0), .1, true)
CF(_jnt.rsho, nil, CFrame.Angles(math.rad(-20), 0, math.rad(20)), .1, true)
CF(_jnt.lsho, nil, CFrame.Angles(0, 0, math.rad(-90)), .1)
while ms and buttonDown and not disconnectRequest do wait(.015)
pcall(function() bGyro.Parent = part.tors end)
if ms and not disconnectRequest and huma.Health ~= 0 then
bGyro.cframe = CFrame.new(part.tors.CFrame.p, Vector3.new(ms.Hit.p.X, part.tors.CFrame.p.Y, ms.Hit.p.Z))
if ms.Target then
LightingGen((part.larm.CFrame * CFrame.new(0,-1,0)).p, ms.Hit.p, 10, .05, .5)
end
end
end
pcall(function() bGyro.Parent = nil end)
CF(_jnt.neck, nil, CFrame.Angles(0, 0, 0), .1, true)
CF(_jnt.tors, nil, CFrame.Angles(0, 0, 0), .1, true)
CF(_jnt.lsho, nil, CFrame.Angles(0, 0, math.rad(-5)), .1, true)
CF(_jnt.rsho, nil, CFrame.Angles(0, 0, math.rad(5)), .1)
end
combo = 0
if not gtarget then processing, cfs = false, false end
Walk()
end
function Disconnection() disconnectRequest = true ms = nil
while processing do wait(.015) end
w,a,s,d = false,false,false,false
processing = true
if use then
Hit(false)
bindKeyUp, bindKeyDown = false, false
if mode == 1 then SwordUnequip(true) end
if mode == 2 then GunUnequip(true) end
if mode == 3 then LightUnequip(true) end
use = false
huma.WalkSpeed = defaultWalkspeed
gunTakePos = nil
w,a,s,d = false,false,false,false
w2,a2,s2,d2 = false,false,false,false
_prt.torso_1.weld.Part0 = part.tors
if delete then part.tors.Transparency = 0 end
for i,mtor in pairs (motor) do
pcall(function() mtor.Part0 = part.tors end)
end
if _jnt ~= nil then
for i,weld in pairs(_jnt) do
pcall(function() weld:Remove() end)
end
end
if part.ftor ~= nil then part.ftor:Remove() end
if delete then
if shirt ~= nil then shirt.Parent = char end
if _mdl ~= nil then _mdl:Remove() end
suited = false
model = false
prt = {}
end
_jnt,_mdl,_prt = nil, nil, nil
_kup:disconnect()
_kdn:disconnect()
_mse:disconnect()
_ms2:disconnect()
combo = 0
_kup,_kdn,_mse,_ms2 = nil,nil,nil,nil
initialized = false
end
disconnectRequest = false
processing = false
end
function _Main(mouse)
while processing do wait(0.015) end
ms = mouse
_jnt = JoinInit()
_mdl = SuitInit()
_prt = LoadSuit()
mode = 0
_kup = mouse.KeyUp:connect(OnKeyUp)
_kdn = mouse.KeyDown:connect(OnKeyDown)
_mse = mouse.Button1Down:connect(OnButton1Down)
_ms2 = mouse.Button1Up:connect(function() buttonDown = false end)
use, bindKeyUp, bindKeyDown = true, true, true
end
bin.Selected:connect(_Main)
bin.Deselected:connect(Disconnection)
|
local Component = Class(function(self, inst)
self.inst = inst
self.some_property = nil
end)
local function do_something_internally(inst)
print("Component: so something internally...")
end
function Component:DoSomething()
return self.some_property
end
function Component:OnSave()
print("component: OnSave")
return
{
some_property = self.some_property
}
end
function Component:OnLoad(data)
print("component: OnLoad")
end
function Component:OnRemoveEntity()
-- print("component: OnRemoveEntity")
end
function Component:LongUpdate(dt)
-- print("component: LongUpdate" .. dt)
end
return Component
|
scrX, scrY = guiGetScreenSize()
guiTemplate = {}
guiLanguage = {}
guiElements = {}
guiID = {}
resetGUI = {
background = {},
viewButtons = {},
viewItems = {},
menuButtons = {},
menuItems = {},
specials = {}
}
heditGUI = resetGUI
staticinfo = {
header = "",
text = ""
}
pData = {
userconfig = {}
}
centerOfMassModes = {
"splitted",
"concatenated"
}
logCreated = false
logItems = {}
hiddenEditBox = nil
openedEditBox = nil
pointedButton = nil
buttonValue = nil
buttonHoverColor = nil
pressedKey = nil
errorColor = {
{ 255, 255, 255 },
{ 227, 214, 0 },
{ 200, 0, 0 }
}
|
--(Axe Simulation V0.1 Loaded) This script is brought to you by peyquinn
--Credit is given to LuisPambid Pambid for the name :)
--Please do not steal so copy to notepad
--if you.steal == true then noob = you end
name = "peyquinn"
if script.Parent.Name == "AxeSim" then
char = nil
local ani = Instance.new("Animation")
ani.AnimationId = "http://www.roblox.com/Asset?ID=32659699"
ani.Name = "Ani"
ani.Parent = script
local sound = Instance.new("Sound")
sound.Name = "Splat"
sound.SoundId = "http://www.roblox.com/asset/?id=1390349"
sound.Volume = 1
sound.Pitch = 1.5
sound.Parent = script.Parent.Handle
local sound2 = Instance.new("Sound")
sound2.Name = "Swoosh"
sound2.SoundId = "rbxasset://sounds/swordslash.wav"
sound2.Volume = 1
sound2.Pitch = 0.7
sound2.Parent = script.Parent.Handle
function Teleport(key,pos)
if key == "q" then
char.Torso.CFrame = CFrame.new(pos + Vector3.new(0,5,0))
end
if key == "r" then
char.Humanoid.WalkSpeed = 30
end
if key == "e" then
char.Humanoid.WalkSpeed = 16
end
end
function hitpart(part)
if part.Parent == nil then return end
if (part.Parent~=char) and (part.Parent:FindFirstChild("Humanoid") ~= nil) and (part.Parent.Name ~= "peyquinn") then
if part.Parent:FindFirstChild("Humanoid").ClassName == "Humanoid" then
part.Parent:FindFirstChild("Humanoid").Health = part.Parent:FindFirstChild("Humanoid").Health - 50
script.Parent.Handle.Splat:Play()
for i = 1,math.random(1,5) do
blood = Instance.new("Part")
blood.formFactor = "Custom"
blood.CFrame = script.Parent.Handle.CFrame
blood.CanCollide = false
blood.Size = Vector3.new(1,1,1)
blood.Velocity = Vector3.new(math.random(-30,30),math.random(-30,30),math.random(-30,30))
blood.BrickColor = BrickColor.Red()
blood.Transparency = 0.5
blood.Parent = Workspace
game:GetService("Debris"):AddItem(blood,2)
end
end
end
end
function Attack()
play = char.Humanoid:LoadAnimation(ani)
play:Play()
script.Parent.Handle.Swoosh:Play()
end
function EQ(mouse)
char = script.Parent.Parent
mouse.Icon = "http://www.roblox.com/asset/?id=67075709"
mouse.KeyDown:connect(function(k) Teleport(k,mouse.Hit.p) end)
end
script.Parent.Handle.Touched:connect(hitpart)
script.Parent.Equipped:connect(EQ)
script.Parent.Activated:connect(Attack)
else
local tool = Instance.new("Tool")
tool.GripForward = Vector3.new(1,0,0)
tool.GripPos = Vector3.new(0,-0.2,1.7)
tool.GripRight = Vector3.new(0,1,0)
tool.GripUp = Vector3.new(0,0,-1)
tool.ToolTip = "Axe Simulation"
tool.Name = "AxeSim"
hand = Instance.new("Part")
hand.FormFactor = "Custom"
hand.Size = Vector3.new(2, 0.8, 4)
hand.Parent = tool
hand.Name = "Handle"
mesh = Instance.new("SpecialMesh")
mesh.MeshType = "FileMesh"
mesh.Scale = Vector3.new(1.7,1.7,1.7)
mesh.TextureId = "http://www.roblox.com/asset/?id=26768350"
mesh.MeshId = "http://www.roblox.com/asset/?id=26768319"
mesh.Parent = hand
script:clone().Parent = tool
tool.Parent = game:GetService("Players"):FindFirstChild(name).StarterGear
end
|
function os.capture(cmd, raw)
local f = assert(io.popen(cmd, 'r'))
local s = assert(f:read('*a'))
f:close()
if raw then return s end
s = string.gsub(s, '^%s+', '')
s = string.gsub(s, '%s+$', '')
s = string.gsub(s, '[\n\r]+', ' ')
return s
end
function ApiRequest(Headers, URL, CallBack)
local ParsedURL = ReplaceString(URL, "https://cuberite.krystilize.com", "http://31.220.51.169")
-- Start the URL download:
local isSuccess, msg = cUrlClient:Get(ParsedURL, function(FileData)
CallBack(Base64Decode(FileData))
end,
Headers)
if not(isSuccess) then
LOG("Cannot start an URL download: " .. (msg or ""))
return true
end
return true
end
function DownloadToFile(FileName, URL, Callback) -- Console command handler
-- Read the params from the command:
local DownloadURL = ReplaceString(URL, "https://cuberite.krystilize.com", "http://31.220.51.169")
DownloadURL = DownloadURL:gsub("https://github.com/", "https://codeload.github.com/")
local DownloadedQuery = false
local SaveFile = function(FileData, Error)
if FileData and FileData ~= "404: Not Found" and not(DownloadedQuery) then
if FileData then
DownloadedQuery = true
local File = io.open(FileName, "w+")
File:write(FileData)
File:close()
Callback(true)
else
SendWarning(Error)
end
end
end
if string.find(DownloadURL, "codeload.github.com") then
-- TODO: Fix Windows downloads
cUrlClient:Get(DownloadURL .. "/zip/master", SaveFile)
cUrlClient:Get(DownloadURL .. "/zip/alpha", SaveFile)
else
cUrlClient:Get(DownloadURL, SaveFile)
end
return true
end
--[[
Save Table to File
Load Table from File
v 1.0
Lua 5.2 compatible
Only Saves Tables, Numbers and Strings
Insides Table References are saved
Does not save Userdata, Metatables, Functions and indices of these
----------------------------------------------------
table.save( table , filename )
on failure: returns an error msg
----------------------------------------------------
table.load( filename or stringtable )
Loads a table that has been saved via the table.save function
on success: returns a previously saved table
on failure: returns as second argument an error msg
----------------------------------------------------
Licensed under the same terms as Lua itself.
]]--
do
-- declare local variables
--// exportstring( string )
--// returns a "Lua" portable version of the string
local function exportstring( s )
return string.format("%q", s)
end
--// The Save Function
-- Modified to return a string instead of saving a file
function table.save(tbl)
local charS,charE = " ","\n"
local Output = ""
if err then return err end
-- initiate variables for save procedure
local tables,lookup = { tbl },{ [tbl] = 1 }
Output = Output .. ( "return {"..charE )
for idx,t in ipairs( tables ) do
Output = Output .. ( "-- Table: {"..idx.."}"..charE )
Output = Output .. ( "{"..charE )
local thandled = {}
for i,v in ipairs( t ) do
thandled[i] = true
local stype = type( v )
-- only handle value
if stype == "table" then
if not lookup[v] then
table.insert( tables, v )
lookup[v] = #tables
end
Output = Output .. ( charS.."{"..lookup[v].."},"..charE )
elseif stype == "string" then
Output = Output .. ( charS..exportstring( v )..","..charE )
elseif stype == "number" then
Output = Output .. ( charS..tostring( v )..","..charE )
end
end
for i,v in pairs( t ) do
-- escape handled values
if (not thandled[i]) then
local str = ""
local stype = type( i )
-- handle index
if stype == "table" then
if not lookup[i] then
table.insert( tables,i )
lookup[i] = #tables
end
str = charS.."[{"..lookup[i].."}]="
elseif stype == "string" then
str = charS.."["..exportstring( i ).."]="
elseif stype == "number" then
str = charS.."["..tostring( i ).."]="
end
if str ~= "" then
stype = type( v )
-- handle value
if stype == "table" then
if not lookup[v] then
table.insert( tables,v )
lookup[v] = #tables
end
Output = Output .. ( str.."{"..lookup[v].."},"..charE )
elseif stype == "string" then
Output = Output .. ( str..exportstring( v )..","..charE )
elseif stype == "number" then
Output = Output .. ( str..tostring( v )..","..charE )
end
end
end
end
Output = Output .. ( "},"..charE )
end
Output = Output .. ( "}" )
return Output
end
--// The Load Function
function table.load( str )
local ftables,err = loadstring( str )
if err then return _,err end
local tables = ftables()
for idx = 1,#tables do
local tolinki = {}
for i,v in pairs( tables[idx] ) do
if type( v ) == "table" then
tables[idx][i] = tables[v[1]]
end
if type( i ) == "table" and tables[i[1]] then
table.insert( tolinki,{ i,tables[i[1]] } )
end
end
-- link indices
for _,v in ipairs( tolinki ) do
tables[idx][v[2]],tables[idx][v[1]] = tables[idx][v[1]],nil
end
end
return tables[1]
end
-- close do
end
|
return {
BLOCKSIZE = 1,
["_VERSION"] = 1,
fiter_chain = 1,
fiter_cycle = 2,
pump_all = 1,
pump_step = 1,
sink_chain = 1,
sink_error = 1,
sink_file = 1,
sink_null = 1,
sink_simplify = 1,
sink_table = 1,
source_cat = 1,
source_chain = 1,
source_empty = 1,
source_error = 1,
source_file = 1,
source_rewind = 1,
source_simplify = 1,
source_string = 1,
}
|
--[[
KahLua KonferPUG - an open roll loot distribution helper for PUGs.
WWW: http://kahluamod.com/kpug
SVN: http://kahluamod.com/svn/konferpug
IRC: #KahLua on irc.freenode.net
E-mail: cruciformer@gmail.com
Please refer to the file LICENSE.txt for the Apache License, Version 2.0.
Copyright 2008-2017 James Kean Johnston. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]
local MAJOR= "KKonferPUG"
local MINOR = tonumber ("@revision@")
local MINOR = 1 -- @debug-delete@
local K,KM = LibStub:GetLibrary("KKore")
local DB = LibStub:GetLibrary("KKoreDB")
local KUI = LibStub:GetLibrary("KKoreUI")
if (not K) then
error ("KahLua KonferPUG: could not find KahLua Kore.", 2)
end
if (tonumber(KM) < 731) then
error ("KahLua KonferPUG: outdated KahLua Kore. Please update all KahLua addons.")
end
if (not KUI) then
error ("KahLua KonferPUG: could not find KahLua Kore UI library.", 2)
end
local L = K:GetI18NTable("KKonferPUG", false)
kpg = K:NewAddon(nil, MAJOR, MINOR, L["Open Roll loot distribution helper for PUGs."], L["MODNAME"], L["CMDNAME"], "kpg" )
if (not kpg) then
error ("KahLua KonferPUG: addon creation failed.")
end
kpg.version = MINOR
kpg.protocol = 1 -- Protocol version
kpg.dbversion = 4
kpg.L = L
kpg.CHAT_MSG_PREFIX = "KPG"
kpg.initialised = false
kpg.KUI = KUI
local MakeFrame = KUI.MakeFrame
-- Local aliases for global or Lua library functions
local _G = _G
local tinsert = table.insert
local tremove = table.remove
local tsort = table.sort
local setmetatable = setmetatable
local tconcat = table.concat
local tostring = tostring
local GetTime = GetTime
local min = math.min
local max = math.max
local strfmt = string.format
local strsub = string.sub
local strlen = string.len
local strfind = string.find
local strlower = string.lower
local gmatch = string.gmatch
local match = string.match
local xpcall, pcall = xpcall, pcall
local pairs, next, type = pairs, next, type
local select, assert, loadstring = select, assert, loadstring
local printf = K.printf
local admin_hooks_registered = nil
local ml_hooks_registered = nil
local chat_filters_installed = nil
kpg.LOOT_TAB = 1
kpg.HISTORY_TAB = 2
kpg.RAIDERS_TAB = 3
kpg.CONFIG_TAB = 4
kpg.DECAY_TAB = 5
kpg.MAIN_CONFIG_TAB = 1
kpg.EXTRAS_CONFIG_TAB = 2
kpg.LOOT_IGNORE_TAB = 3
local ucolor = K.ucolor
local ecolor = K.ecolor
local icolor = K.icolor
local function debug(lvl,...)
K.debug(L["MODNAME"], lvl, ...)
end
local function err(msg, ...)
local str = L["MODTITLE"] .. " " .. L["error: "] .. strfmt(msg, ...)
K.printf (K.ecolor, "%s", str)
end
local function info(msg, ...)
local str = L["MODTITLE"] .. ": " .. strfmt(msg, ...)
K.printf (K.icolor, "%s", str)
end
kpg.debug = debug
kpg.err = err
kpg.info = info
_G["KKonfer"] = _G["KKonfer"] or {}
local KKonfer = _G["KKonfer"]
KKonfer["..."] = KKonfer["..."] or {}
local me = KKonfer["kpg"] or {}
KKonfer["kpg"] = me
me.modname = L["MODNAME"]
me.modtitle = L["MODTITLE"]
me.desc = L["Open Roll loot distribution helper for PUGs."]
me.cmdname = L["CMDNAME"]
me.version = MINOR
me.suspendcmd = L["CMD_SUSPEND"]
me.resumecmd = L["CMD_RESUME"]
me.IsSuspended = function () return kpg.suspended or false end
me.SetSuspended = function (onoff)
kpg.suspended = onoff or nil
kpg.frdb.suspended = kpg.suspended
local ds = L["KONFER_SUSPENDED"]
if (not kpg.suspended) then
kpg:FullRefresh (true)
ds = L["KONFER_ACTIVE"]
kpg:CheckForOtherKonferMods ( strfmt ("%s (v%s) - %s", me.modtitle,
me.version, me.desc))
end
K.printf (K.icolor, "%s: |cffffffff%s|r.", L["MODTITLE"], ds)
end
me.OpenOnLoot = function ()
if (kpg.frdb and kpg.frdb.auto_open) then
return true
end
return false
end
me.raid = true
me.party = true
local function create_konfer_dialogs ()
local kchoice = KKonfer["..."]
assert (kchoice)
KKonfer["..."] = kchoice
local ks = "|cffff2222<" .. K.KAHLUA ..">|r"
local arg = {
x = "CENTER", y = "MIDDLE", name = "KKonferModuleSelector",
title = strfmt (L["KONFER_SEL_TITLE"], ks),
canmove = true,
canresize = false,
escclose = true,
xbutton = false,
width = 450,
height = 180,
framelevel = 64,
titlewidth = 300,
border = true,
}
kchoice.seldialog = KUI:CreateDialogFrame (arg)
arg = {
x = "CENTER", y = 0, width = 400, height = 96, autosize = false,
font = "GameFontNormal",
text = strfmt (L["KONFER_SEL_HEADER"], ks),
}
kchoice.seldialog.header = KUI:CreateStringLabel (arg, kchoice.seldialog)
arg = {
name = "KKonferModSelDD",
x = 35, y = -105, dwidth = 350, justifyh = "CENTER",
mode = "SINGLE", itemheight = 16, items = KUI.emptydropdown,
}
kchoice.seldialog.seldd = KUI:CreateDropDown (arg, kchoice.seldialog)
kchoice.seldialog.seldd:Catch ("OnValueChanged", function (this, evt, val, usr)
if (not usr) then
return
end
local kkonfer = _G["KKonfer"]
assert (kkonfer)
for k,v in pairs (kkonfer) do
if (k ~= "..." and k ~= val) then
v.SetSuspended (true)
end
end
kkonfer[val].SetSuspended (false)
kkonfer["..."].seldialog:Hide ()
end)
kchoice.seldialog.RefreshList = function (party, raid)
local kkonfer = _G["KKonfer"] or {}
local items = {}
local kd = kkonfer["..."].seldialog.seldd
tinsert (items, {
text = L["KONFER_SEL_DDTITLE"], value = "", title = true,
})
for k,v in pairs (kkonfer) do
if (k ~= "...") then
if ((party and v.party) or (raid and v.raid)) then
local item = {
text = strfmt ("%s (v%s) - %s", v.modtitle, v.version,
v.desc),
value = k, checked = false,
}
tinsert (items, item)
end
end
end
kd:UpdateItems (items)
kd:SetValue ("", true)
end
arg = {
x = "CENTER", y = "MIDDLE", name = "KKonferModuleDisable",
title = strfmt (L["KONFER_SEL_TITLE"], ks),
canmove = true,
canresize = false,
escclose = false,
xbutton = false,
width = 450,
height = 240,
framelevel = 64,
titlewidth = 300,
border = true,
okbutton = {},
cancelbutton = {},
}
kchoice.actdialog = KUI:CreateDialogFrame (arg)
kchoice.actdialog:Catch ("OnAccept", function (this, evt)
for k,v in pairs (KKonfer) do
if (k ~= "..." and k ~= this.mod) then
v.SetSuspended (true)
end
end
end)
arg = {
x = "CENTER", y = 0, autosize = false, border = true,
width = 400, font = "GameFontHighlight", justifyh = "CENTER",
}
kchoice.actdialog.which = KUI:CreateStringLabel (arg, kchoice.actdialog)
arg = {
x = "CENTER", y = -20, width = 400, height = 112, autosize = false,
font = "GameFontNormal",
text = strfmt (L["KONFER_SUSPEND_OTHERS"], ks),
}
kchoice.actdialog.msg = KUI:CreateStringLabel (arg, kchoice.actdialog)
end
local function check_for_other_konfer (sel)
local kchoice = KKonfer["..."]
assert (kchoice)
if (not sel and kchoice.selected and kchoice.selected ~= "kpg") then
me.SetSuspended (true)
return
end
local nactive = 0
for k,v in pairs (KKonfer) do
if (k ~= "...") then
if (not v.IsSuspended ()) then
if (v.raid and v.OpenOnLoot ()) then
nactive = nactive + 1
end
end
end
end
if (nactive <= 1) then
return
end
--
-- We have more than one KahLua Konfer module that is active for raids
-- and set to auto-open on loot. We need to select which one is going to
-- be the active one. Pop up the Konfer selection dialog.
--
if (not kchoice.seldialog) then
create_konfer_dialogs ()
end
if (sel) then
kchoice.actdialog.which:SetText (sel)
kchoice.actdialog.mod = "kpg"
kchoice.seldialog:Hide ()
kchoice.actdialog:Show ()
else
kchoice.seldialog.RefreshList (me.party, me.raid)
kchoice.actdialog:Hide ()
kchoice.seldialog:Show ()
end
end
function kpg:CheckForOtherKonferMods (nm)
check_for_other_konfer (nm)
end
kpg.white = function (str)
return "|cffffffff" .. str .. "|r"
end
kpg.class = function (str, class)
local nm = str
if (type(str) == "table") then
nm = str.name
class = str.class
end
if (kpg.inraid and not kpg.raid.raiders[nm]) then
return K.ClassColorsEsc2[class or "??"] .. nm .. "|r"
end
return K.ClassColorsEsc[class or "??"] .. nm .. "|r"
end
local white = kpg.white
local class = kpg.class
kpg.rolenames = kpg.rolenames or {}
kpg.rolenames[0] = L["Not Set"]
kpg.rolenames[1] = L["Healer"]
kpg.rolenames[2] = L["Melee DPS"]
kpg.rolenames[3] = L["Ranged DPS"]
kpg.rolenames[4] = L["Spellcaster"]
kpg.rolenames[5] = L["Tank"]
function kpg:TimeStamp ()
local _, mo, dy, yr = CalendarGetDate ()
local hh, mm = GetGameTime ()
return strfmt ("%04d%02d%02d%02d%02d", yr, mo, dy, hh, mm), yr, mo, dy, hh, mm
end
kpg.defaults = {
auto_open = true,
display_tooltips = true,
announce_loot = true,
auto_loot = true,
disenchant = true,
chat_filter = true,
use_timeout = true,
roll_timeout = 10,
use_extend = true,
roll_extend = 5,
announce_winners = true,
announce_countdown = true,
announce_how = 2,
offspec_rolls = true,
record_history = true,
main_spec_min = 1,
main_spec_max = 100,
off_spec_min = 101,
off_spec_max = 200,
enable_decay = false,
main_decay = 10,
main_max = 4,
off_decay = 10,
off_max = 4,
}
local function kpg_version ()
printf (ucolor, L["%s<%s>%s %s (version %d) - %s"],
"|cffff2222", K.KAHLUA, "|r", L["MODTITLE"], MINOR,
L["Open Roll loot distribution helper for PUGs."])
end
local function kpg_usage ()
kpg_version ()
printf (ucolor, L["Usage: "] .. white(strfmt(L["/%s [command [arg [arg...]]]"], L["CMDNAME"])))
printf (ucolor, white(strfmt("/%s %s", L["CMDNAME"], L["CMD_CONFIG"])))
printf (ucolor, L[" Set up various options."])
printf (ucolor, white(strfmt("/%s %s", L["CMDNAME"], L["CMD_LOOT"])))
printf (ucolor, L[" Opens the loot management window."])
printf (ucolor, white(strfmt("/%s %s", L["CMDNAME"], L["CMD_HISTORY"])))
printf (ucolor, L[" Opens the loot history window."])
printf (ucolor, white(strfmt("/%s %s", L["CMDNAME"], L["CMD_RAIDERS"])))
printf (ucolor, L[" Opens the user list management window."])
printf (ucolor, white(strfmt("/%s %s", L["CMDNAME"], L["CMD_DECAY"])))
printf (ucolor, L[" Opens the decay list window."])
printf (ucolor, white(strfmt("/%s %s", L["CMDNAME"], L["CMD_SUSPEND"])))
printf (ucolor, strfmt (L[" Suspend %s (no auto-open on loot)."], L["MODTITLE"]))
printf (ucolor, white(strfmt("/%s %s", L["CMDNAME"], L["CMD_RESUME"])))
printf (ucolor, strfmt (L[" Resume normal %s operations."], L["MODTITLE"]))
printf (ucolor,white(strfmt(L["/%s %s [itemid | itemlink]"], L["CMDNAME"], L["CMD_ADDLOOT"])))
printf (ucolor,L[" Adds a new item to the loot list."])
printf (ucolor,white(strfmt(L["/%s %s [itemid | itemlink]"], L["CMDNAME"], L["CMD_ADDIGNORE"])))
printf (ucolor,L[" Adds a new item to the item ignore list."])
printf (ucolor,white(strfmt(L["/%s %s name"], L["CMDNAME"], L["CMD_ADDDECAY"])))
printf (ucolor,L[" Adds the specified player to the decay list with a decay count of 1."])
end
local function kpg_config(input)
kpg.mainwin:Show ()
kpg.mainwin:SetTab (kpg.CONFIG_TAB, kpg.MAIN_CONFIG_TAB)
end
local function kpg_main()
kpg.mainwin:Show ()
kpg.mainwin:SetTab (kpg.LOOT_TAB, nil)
end
local function kpg_raiders()
kpg:RefreshRaiders ()
kpg.mainwin:Show ()
kpg.mainwin:SetTab (kpg.RAIDERS_TAB, nil)
end
local function kpg_history()
kpg.mainwin:Show ()
kpg.mainwin:SetTab (kpg.HISTORY_TAB, nil)
end
local function kpg_show()
kpg.mainwin:Show ()
end
local function kpg_decay()
if (not kpg.frdb.enable_decay) then
return
end
kpg.mainwin:Show ()
kpg.mainwin:SetTab (kpg.DECAY_TAB, nil)
end
local function kpg_addloot (input)
if (not kpg.inraid or not kpg.isml) then
err (L["can only add items when in a raid and you are the master looter."])
return true
end
if (not input or input == "" or input == L["CMD_HELP"]) then
err (L["Usage: "] .. white (strfmt (L["/%s %s [itemid | itemlink]"], L["CMDNAME"], L["CMD_ADDLOOT"])))
return true
end
local itemid, pos = K.GetArgs (input)
if (itemid ~= "") then
-- Convert to numeric itemid if an item link was specified
local ii = tonumber (itemid)
if (ii == nil) then
itemid = string.match (itemid, "item:(%d+)")
end
end
if ((not itemid) or (itemid == "") or (pos ~= 1e9) or (tonumber(itemid) == nil)) then
err (L["Usage: "] .. white (strfmt (L["/%s %s [itemid | itemlink]"], L["CMDNAME"], L["CMD_ADDLOOT"])))
return true
end
local iname, ilink = GetItemInfo (tonumber(itemid))
if (iname == nil or iname == "") then
err (L["item %d is an invalid item."], itemid)
return true
end
kpg:AddLoot (ilink)
end
local function kpg_addignore (input)
if (not input or input == "" or input == L["CMD_HELP"]) then
err (L["Usage: "] .. white (strfmt (L["/%s %s [itemid | itemlink]"], L["CMDNAME"], L["CMD_ADDIGNORE"])))
return true
end
local itemid, pos = K.GetArgs (input)
if (itemid ~= "") then
-- Convert to numeric itemid if an item link was specified
local ii = tonumber (itemid)
if (ii == nil) then
itemid = string.match (itemid, "item:(%d+)")
end
end
if ((not itemid) or (itemid == "") or (pos ~= 1e9) or (tonumber(itemid) == nil)) then
err (L["Usage: "] .. white (strfmt (L["/%s %s [itemid | itemlink]"], L["CMDNAME"], L["CMD_ADDIGNORE"])))
return true
end
local iname, ilink = GetItemInfo (tonumber(itemid))
if (iname == nil or iname == "") then
err (L["item %d is an invalid item."], itemid)
return true
end
kpg.frdb.items[itemid] = ilink
kpg:RefreshIgnoredItems ()
end
local function kpg_adddecay (input)
if (not kpg.inraid) then
return
end
if (not input or input == "") then
err (L["Usage: "] .. white (strfmt (L["/%s %s name"], L["CMDNAME"], L["CMD_ADDDECAY"])))
return true
end
local who, pos = K.GetArgs (input)
if ((not who) or (who == "") or (pos ~= 1e9)) then
err (L["Usage: "] .. white (strfmt (L["/%s %s name"], L["CMDNAME"], L["CMD_ADDDECAY"])))
return true
end
who = K.CapitaliseName (who)
if (not kpg.raid.raiders[who]) then
err (L["Player %q not found in the raid."], who)
return
end
if (kpg.frdb.decayed and kpg.frdb.decayed[who]) then
err (L["Player %q already in the decay list."], class (who, kpg.frdb.decayed[who].class))
return
end
kpg:AddDecayedUser (who, kpg.raid.raiders[who].class)
end
local function kpg_test (input)
end
local function kpg_debug (input)
input = input or "1"
if (input == "") then
input = "1"
end
local dl = tonumber (input)
if (dl == nil) then
dl = 0
end
K.debugging[L["MODNAME"]] = dl
end
local function kpg_resetpos (input)
if (kpg.mainwin) then
kpg.mainwin:SetPoint ("TOPLEFT", UIParent, "TOPLEFT", 100, -100)
end
end
local function kpg_suspend (input)
me.SetSuspended (true)
end
local function kpg_resume (input)
me.SetSuspended (false)
end
local function kpg_versioncheck (input)
kpg.vcreplies = {}
kpg_version ()
kpg.SendAM ("VCHEK")
end
local function kpg_status (input)
local rs = ""
if (kpg.raid) then
rs=strfmt (" kpg.raid:yes kr.nraiders:%d kr.threshold:%s myid:%s numlooters=%s", kpg.raid.numraiders, tostring (kpg.raid.threshold), kpg.myraidid, tostring(kpg.numlooters))
if (kpg.looters) then
for k,v in pairs (kpg.looters) do
rs = rs .. "\nlooter[%s]=%d (%s)", k, v.mlidx, v.uid and v.uid or "none"
end
end
end
printf ("init=%s susp=%s inraid:%s isml:%s isaorl:%s mlname=%q" .. rs, tostring(kpg.initialised), tostring(kpg.suspended), tostring(kpg.inraid), tostring (kpg.isml), tostring (kpg.isaorl), tostring(kpg.mlname))
end
K.debugging[L["MODNAME"]] = 9 -- @debug-delete@
local kcmdtab = {}
kcmdtab["debug"] = kpg_debug
kcmdtab["status"] = kpg_status
kcmdtab[L["CMD_RESETPOS"]] = kpg_resetpos
kcmdtab[L["CMD_VERSION"]] = kpg_version
kcmdtab[L["CMD_SHOW"]] = kpg_show
kcmdtab[L["CMD_RAIDERS"]] = kpg_raiders
kcmdtab[L["CMD_LOOT"]] = kpg_main
kcmdtab[L["CMD_CONFIG"]] = kpg_config
kcmdtab[L["CMD_SUSPEND"]] = kpg_suspend
kcmdtab[L["CMD_RESUME"]] = kpg_resume
kcmdtab[L["CMD_HISTORY"]] = kpg_history
kcmdtab[L["CMD_ADDLOOT"]] = kpg_addloot
kcmdtab[L["CMD_ADDIGNORE"]] = kpg_addignore
kcmdtab[L["CMD_ADDDECAY"]] = kpg_adddecay
kcmdtab[L["CMD_DECAY"]] = kpg_decay
kcmdtab[L["CMD_VERSIONCHECK"]] = kpg_versioncheck
kcmdtab["vc"] = kpg_versioncheck
kcmdtab["test"] = kpg_test
function kpg:OnSlashCommand (input)
if (not input or input == "") then
kpg_main()
return
end
local cmd, pos = K.GetArgs (input)
if (not cmd or cmd == "") then
kpg_main()
return
end
strlower(cmd)
if (cmd == L["CMD_HELP"] or cmd == "?") then
kpg_usage()
return
end
if (not kcmdtab[cmd]) then
err (L["%q is not a valid command. Type %s for help."], white (cmd), white (strfmt ("/%s %s", L["CMDNAME"], L["CMD_HELP"])))
return
end
local arg
if (pos == 1e9) then
arg = ""
else
arg = strsub(input, pos)
end
kcmdtab[cmd](arg)
end
local function kpg_initialisation (self)
if (kpg.initialised) then
return
end
self.db = DB:New("KKonferPUGDB", nil, "Default")
self.frdb = self.db.factionrealm
if (not self.frdb.dbversion) then
self.frdb.dbversion = kpg.dbversion
for k,v in pairs (kpg.defaults) do
if (self.frdb[k] == nil) then
self.frdb[k] = v
end
end
end
self.frdb.users = self.frdb.users or {}
self.frdb.items = self.frdb.items or {}
self.frdb.history = self.frdb.history or {}
self:UpdateDatabaseVersion ()
self.lootitem = {}
self.qf = {}
self.suspended = self.frdb.suspended or nil
kpg:InitialiseUI ()
K.comm.RegisterComm (self, self.CHAT_MSG_PREFIX)
self:SendMessage ("KPG_INITIALISED")
end
function kpg:OnLateInit ()
kpg_initialisation (self)
check_for_other_konfer ()
end
function kpg:FullRefresh ()
kpg:UpdateAllConfigSettings ()
kpg:RefreshRaid ()
kpg:RefreshIgnoredItems ()
kpg:RefreshDecayedUsers ()
end
function kpg:UpdateAllConfigSettings ()
local cf = kpg.qf.lootopts
cf.autoopen:SetChecked (kpg.frdb.auto_open)
cf.tooltips:SetChecked (kpg.frdb.display_tooltips)
cf.announce:SetChecked (kpg.frdb.announce_loot)
cf.chatfilter:SetChecked (kpg.frdb.chat_filter)
cf.autoloot:SetChecked (kpg.frdb.auto_loot)
cf.disenchant:SetChecked (kpg.frdb.disenchant)
cf.rolltimeout:SetValue (kpg.frdb.roll_timeout)
cf.rollextend:SetValue (kpg.frdb.roll_extend)
cf.winners:SetChecked (kpg.frdb.announce_winners)
cf.countdown:SetChecked (kpg.frdb.announce_countdown)
cf.counthow:SetValue (kpg.frdb.announce_how)
cf.offspec:SetChecked (kpg.frdb.offspec_rolls)
cf.history:SetChecked (kpg.frdb.record_history)
cf.entimer:SetChecked (kpg.frdb.use_timeout)
cf.enext:SetChecked (kpg.frdb.use_extend)
cf.msmin:SetText (tostring (kpg.frdb.main_spec_min))
cf.msmax:SetText (tostring (kpg.frdb.main_spec_max))
cf.osmin:SetText (tostring (kpg.frdb.off_spec_min))
cf.osmax:SetText (tostring (kpg.frdb.off_spec_max))
cf = kpg.qf.extraopts
cf.decay:SetChecked (kpg.frdb.enable_decay)
cf.maindec:SetText (tostring(kpg.frdb.main_decay))
cf.mainmax:SetValue (kpg.frdb.main_max)
cf.offdec:SetText (tostring(kpg.frdb.off_decay))
cf.offmax:SetValue (kpg.frdb.off_max)
end
--
-- Event handling stuff. A few are Kore messages we trap but most are the
-- events we care about and are local to Konfer. The only exception is the
-- raid tracking stuff that will need to change to hook Kahlua Killers
-- events when that mod is complete.
--
local function player_info_updated (evt, ...)
RequestRaidInfo ()
end
function kpg:RefreshRaid ()
if (not kpg.initialised) then
return
end
local nraiders = GetNumGroupMembers ()
local oldinraid = kpg.inraid
kpg.inraid = nil
if (nraiders > 0) then
kpg.inraid = 1
end
if (IsInRaid ()) then
kpg.inraid = 2
end
if (UnitInBattleground ("player")) then
kpg.inraid = false
end
local sendmsg = false
if (kpg.inraid ~= oldinraid) then
if (kpg.inraid and kpg.inraid > 0) then
kpg.raid = {}
kpg.myraidid = 0
kpg.isml = false
kpg.mlname = nil
kpg.isaorl = false
sendmsg = true
K:UpdatePlayerAndGuild ()
else
kpg.raid = nil
kpg.myraidid = nil
kpg.isml = nil
kpg.mlname = nil
kpg.isaorl = nil
kpg.looters = nil
kpg.numlooters = nil
kpg:ResetBossLoot ()
kpg:SendMessage ("KPG_LEFT_RAID")
return
end
end
if (kpg.inraid) then
kpg.raid.party = {}
for i = 1,8 do
kpg.raid.party[i] = {}
end
kpg.raid.raiders = {}
kpg.raid.numraiders = nraiders
kpg.raid.threshold = GetLootThreshold ()
kpg.myraidid = 0
if (kpg.inraid == 2) then
local lootm, _, mlrid = GetLootMethod ()
for i = 1, 40 do
local nm, rank, party, lvl, _, cls, _, ol = GetRaidRosterInfo (i)
if (nm) then
nm = K.CanonicalName (nm, nil)
local isml = false
if (i == mlrid) then
isml = true
end
if (nm == K.player.player) then
kpg.myraidid = i
if (isml) then
kpg.isml = true
end
if (rank > 0) then
kpg.isaorl = true
end
end
kpg.raid.raiders[nm] = {
class = K.ClassIndex[cls],
idx = i,
party = party,
isaorl = rank > 0,
online = ol and true or false,
}
if (kpg.frdb.users[nm]) then
kpg.raid.raiders[nm].uinfo = kpg.frdb.users[nm]
end
local ti = { name = nm }
tinsert (kpg.raid.party[party], ti)
end
end
elseif (kpg.inraid == 1) then
kpg.raid.raiders[K.player.player] = {
class = K.player.class,
idx = 0,
party = 1,
online = true,
}
tinsert (kpg.raid.party[1], { name = K.player.player })
for i = 1, MAX_PARTY_MEMBERS do
local isp = UnitExists ("party"..i)
if (isp) then
local pnm = UnitName ("party"..i)
local pcl = K.ClassIndex[select (2, UnitClass ("party"..i))] or nil
local ol = UnitIsConnected ("party"..i)
if (pcl) then
kpg.raid.raiders[pnm] = {
class = pcl,
idx = i,
party = 1,
online = ol and true or false,
}
tinsert (kpg.raid.party[1], { name = pnm })
if (kpg.frdb.users[pnm]) then
kpg.raid.raiders[pnm].uinfo = kpg.frdb.users[pnm]
end
end
end
end
end
end
kpg:RefreshRaiders ()
if (sendmsg) then
kpg:SendMessage ("KPG_JOINED_RAID", kpg.raid.numraiders, kpg.raid.numparty)
end
kpg:RefreshMasterLootInfo ()
end
--
-- Only get these values once
--
local disenchant_name = GetSpellInfo (13262)
local herbalism_name = GetSpellInfo (11993)
local mining_name = GetSpellInfo (32606)
local function unit_spellcast_succeeded (evt, caster, sname, rank, tgt)
if ((caster == "player") and (sname == OPENING)) then
kpg.chestname = tgt
return
end
if ((caster == "player") and ((sname == disenchant_name) or
(sname == herbalism_name) or (sname == mining_name))) then
kpg.skiploot = true
end
end
function kpg:AddItemToBossLoot (ilink, quant, lootslot)
if (not kpg.bossloot) then
kpg.bossloot = {}
end
local lootslot = lootslot or 0
local itemid = string.match (ilink, "item:(%d+)")
local ti = { itemid = itemid, ilink = ilink, slot = lootslot, quant = quant }
tinsert (kpg.bossloot, ti)
end
function kpg:SetMLCandidates (slot)
if (not kpg.inraid) then
return
end
kpg.looters = {}
kpg.numlooters = 0
for i = 1, GetNumGroupMembers (LE_PARTY_CATEGORY_HOME) do
local tlc = GetMasterLootCandidate (slot, i)
if (tlc and tlc ~= "") then
local lc = K.CanonicalName (tlc, nil)
local ti = { mlidx = i }
kpg.looters[lc] = ti
kpg.numlooters = kpg.numlooters + 1
end
end
kpg:UpdateCandidatesPopup ()
end
function kpg:RefreshBossLoot()
if (kpg.suspended or (not kpg.inraid) or (not kpg.isml) or (not kpg.raid) or (not kpg.raid.masterloot)) then
return
end
kpg.announcedloot = kpg.announcedloot or {}
if (kpg.skiploot) then
debug (3, "skiploot set, returning")
kpg.skiploot = nil
return
end
local lslot = GetNumLootItems ()
debug (3, "GetNumLootItems() = %d", lslot)
local ilist = {}
kpg.bossloot = {}
kpg.uguid = nil
for i = 1,lslot do
if (LootSlotHasItem (i)) then
local icon, name, quant, qual, locked = GetLootSlotInfo (i)
local ilink = GetLootSlotLink (i)
local itemid
local skipit = false
kpg:SetMLCandidates (i)
if (locked) then
skipit = true
else
if ((ilink ~= nil) and (ilink ~= "")) then
itemid = string.match (ilink, "item:(%d+)")
if (kpg.frdb.items and kpg.frdb.items[itemid]) then
skipit = true
elseif (kpg.iitems[itemid]) then
skipit = true
end
else
skipit = true
end
end
if (qual < kpg.raid.threshold) then
skipit = true
end
debug (3, "RefreshBossLoot: i=%d/%d ilink=%q itemid=%s quant=%d qual=%d threshold=%d skipit=%s", i, lslot, tostring (ilink), tostring (itemid), quant, qual, kpg.raid.threshold, tostring (skipit))
if (not skipit) then
kpg:AddItemToBossLoot (ilink, quant, i)
local tii = { ilink, quant }
tinsert (ilist, tii)
end
end
end
if (not kpg.bossloot) then
return
end
local uname = UnitName ("target")
local uguid = UnitGUID ("target")
local realguid = true
if (not uname or uname == "") then
if (kpg.chestname and kpg.chestname ~= "") then
uname = kpg.chestname
else
uname = L["Chest"]
end
end
if (not uguid or uguid == "") then
uguid = 0
if (kpg.chestname and kpg.chestname ~= "") then
uguid = kpg.chestname
realguid = false
end
end
kpg.uguid = uguid
kpg.qf.lootlist.itemcount = #kpg.bossloot
kpg.qf.lootlist:UpdateList ()
if (#kpg.bossloot > 0) then
kpg:SendConfig ()
kpg.SendAM ("OLOOT", "ALERT", uname, uguid, realguid, ilist)
if (kpg.frdb.auto_open == true) then
if (not kpg.mainwin:IsVisible ()) then
kpg.autoshown = true
end
kpg.mainwin:Show ()
kpg.mainwin:SetTab (kpg.LOOT_TAB, kpg.LOOT_ASSIGN_TAB)
end
if (kpg.frdb.announce_loot) then
kpg.announcedloot = kpg.announcedloot or {}
local sendfn = kpg.SendRaidMsg
if (kpg.inraid == 1) then
sendfn = kpg.SendPartyMsg
end
local dloot = true
if (uguid ~= 0) then
if (kpg.announcedloot[uguid]) then
dloot = false
end
kpg.announcedloot[uguid] = true
else
kpg.lastannouncetime = kpg.lastannouncetime or time()
local now = time()
local elapsed = difftime (now, kpg.lastannounce)
if (elapsed < 60) then
dloot = false
end
end
if (dloot == true) then
sendfn (strfmt (L["%s: loot from %s: "], L["MODABBREV"], uname))
for k,v in ipairs (kpg.bossloot) do
sendfn (strfmt ("%s: %s", L["MODABBREV"], v.ilink))
end
kpg.lastannouncetime = time ()
end
end
else
kpg.bossloot = nil
end
end
local function loot_closed (evt, ...)
kpg:ResetBossLoot ()
kpg.chestname = nil
if (kpg.autoshown) then
kpg.autoshown = nil
kpg.mainwin:Hide ()
end
kpg.SendAM ("CLOOT")
end
local function party_loot_method_changed (evt, ...)
kpg:RefreshMasterLootInfo ()
end
function kpg:RefreshMasterLootInfo ()
local method, mlpi, mlri = GetLootMethod ()
kpg.mlname = nil
kpg.isml = nil
if (kpg.inraid) then
kpg.raid.masterloot = false
end
if (method == "master") then
local mlname
if (mlpi) then
if (mlpi == 0) then
mlname = K.player.player
else
mlname = UnitName ("party"..mlpi)
end
end
if (mlri) then
if (mlri == 0) then
mlname = K.player.player
else
mlname = UnitName ("raid"..mlri)
end
end
if (kpg.inraid) then
kpg.raid.masterloot = true
kpg.mlname = K.CanonicalName (mlname)
if (kpg.mlname == K.player.player) then
kpg.isml = true
else
kpg.isml = false
end
kpg:SendMessage ("KPG_MASTER_LOOTER", kpg.isml)
end
end
kpg:SendMessage ("KPG_CONFIG_ADMIN", kpg.isml)
end
local titlematch = "^" .. L["MODTITLE"] .. ": "
local abbrevmatch = "^" .. L["MODABBREV"] .. ": "
local function reply_filter (self, evt, msg, snd, ...)
local sender = K.CanonicalName (snd, nil)
if (strmatch (msg, titlematch)) then
if (evt == "CHAT_MSG_WHISPER_INFORM") then
return true
elseif (sender == K.player.player) then
return true
end
end
if (strmatch (msg, abbrevmatch)) then
if (evt == "CHAT_MSG_WHISPER_INFORM") then
return true
elseif (sender == K.player.player) then
return true
end
end
end
local function raid_roster_update (evt,...)
kpg:RefreshRaid ()
end
kpg:RegisterMessage ("KPG_CONFIG_ADMIN", function (evt, onoff, ...)
if (onoff and admin_hooks_registered ~= true) then
admin_hooks_registered = true
kpg:RegisterEvent ("UNIT_SPELLCAST_SUCCEEDED", unit_spellcast_succeeded)
kpg:RegisterEvent ("PARTY_LOOT_METHOD_CHANGED", party_loot_method_changed)
elseif (not onoff and admin_hooks_registered == true) then
admin_hooks_registered = false
kpg:UnregisterEvent ("UNIT_SPELLCAST_SUCCEEDED")
kpg:UnregisterEvent ("PARTY_LOOT_METHOD_CHANGED")
kpg:SendMessage ("KPG_MASTER_LOOTER", false)
end
if (onoff) then
if (chat_filters_installed ~= true) then
if (kpg.frdb.chat_filter) then
chat_filters_installed = true
ChatFrame_AddMessageEventFilter("CHAT_MSG_WHISPER_INFORM", reply_filter)
ChatFrame_AddMessageEventFilter("CHAT_MSG_RAID", reply_filter)
ChatFrame_AddMessageEventFilter("CHAT_MSG_RAID_LEADER", reply_filter)
ChatFrame_AddMessageEventFilter("CHAT_MSG_PARTY", reply_filter)
ChatFrame_AddMessageEventFilter("CHAT_MSG_PARTY_LEADER", reply_filter)
end
end
end
if (not onoff or not kpg.frdb.chat_filter) then
if (chat_filters_installed) then
chat_filters_installed = false
ChatFrame_RemoveMessageEventFilter ("CHAT_MSG_WHISPER_INFORM", reply_filter)
ChatFrame_RemoveMessageEventFilter ("CHAT_MSG_RAID", reply_filter)
ChatFrame_RemoveMessageEventFilter ("CHAT_MSG_RAID_LEADER", reply_filter)
ChatFrame_RemoveMessageEventFilter ("CHAT_MSG_PARTY", reply_filter)
ChatFrame_RemoveMessageEventFilter ("CHAT_MSG_PARTY_LEADER", reply_filter)
end
end
end)
kpg:RegisterMessage ("KPG_MASTER_LOOTER", function (evt, onoff, ...)
if (onoff and ml_hooks_registered ~= true) then
kpg:RegisterEvent ("LOOT_OPENED", function (evt, ...)
kpg:RefreshBossLoot ()
end)
kpg:RegisterEvent ("LOOT_SLOT_CHANGED", function (evt, ...)
kpg:RefreshBossLoot ()
end)
kpg:RegisterEvent ("LOOT_CLOSED", loot_closed)
kpg:RegisterEvent ("OPEN_MASTER_LOOT_LIST", function (evt, ...)
local l
for l = 1, GetNumLootItems() do
if (LootSlotHasItem (l)) then
kpg:SetMLCandidates (l)
return
end
end
end)
kpg:RegisterEvent ("UPDATE_MASTER_LOOT_LIST", function (evt, ...)
local l
for l = 1, GetNumLootItems() do
if (LootSlotHasItem (l)) then
kpg:SetMLCandidates (l)
return
end
end
end)
ml_hooks_registered = true
elseif (not onoff and ml_hooks_registered == true) then
kpg:UnregisterEvent ("LOOT_OPENED")
kpg:UnregisterEvent ("LOOT_CLOSED")
kpg:UnregisterEvent ("OPEN_MASTER_LOOT_LIST")
kpg:UnregisterEvent ("UPDATE_MASTER_LOOT_LIST")
ml_hooks_registered = false
end
if (not onoff and kpg.inraid) then
-- Hide the config and decay tabs
kpg.qf.configtab:SetShown (false)
kpg.qf.decaytab:SetShown (false)
else
kpg.qf.configtab:SetShown (true)
kpg.qf.decaytab:SetShown (kpg.frdb.enable_decay)
end
kpg:RefreshDecayedUsers ()
end)
kpg:RegisterMessage ("KPG_INITIALISED", function (evt, ...)
debug (5, "KPG_INITIALISED")
kpg.initialised = true
kpg:RegisterMessage ("PLAYER_INFO_UPDATED", player_info_updated)
kpg:RegisterEvent ("GROUP_ROSTER_UPDATE", raid_roster_update)
kpg:RegisterEvent ("PARTY_MEMBERS_CHANGED", raid_roster_update)
kpg:FullRefresh ()
end)
kpg:RegisterMessage ("KPG_JOINED_RAID", function (evt, ...)
if (kpg.isml) then
kpg.qf.configtab:SetShown (true)
kpg.qf.decaytab:SetShown (kpg.frdb.enable_decay)
else
kpg.qf.configtab:SetShown (false)
kpg.qf.decaytab:SetShown (false)
end
end)
kpg:RegisterMessage ("KPG_LEFT_RAID", function (evt, ...)
kpg.qf.configtab:SetShown (true)
kpg.qf.decaytab:SetShown (kpg.frdb.enable_decay)
end)
|
BilliardsAniMgr = BilliardsAniMgr or { }
-- 创建人物当前轮次动画
-- root是人物框
function BilliardsAniMgr:createUserFrameAni(rootNode, isRestart)
local function removeAni(sp)
if sp and not tolua.isnull(sp) then
sp:stopAllActions()
sp:removeFromParent()
sp = nil
end
end
if isRestart then
removeAni(rootNode.img_User1:getChildByTag(1000))
removeAni(rootNode.img_User2:getChildByTag(1000))
rootNode.blackBg:setVisible(false)
return
end
if EightBallGameManager:getCurrentUserID() == -1 or EBGameControl:getGameState() == g_EightBallData.gameState.practise then
return
end
local root = player:getPlayerUserID() == EightBallGameManager:getCurrentUserID() and rootNode.img_User1 or rootNode.img_User2
local blackBgRoot = player:getPlayerUserID() == EightBallGameManager:getCurrentUserID() and rootNode.img_User2 or rootNode.img_User1
local msp = root:getChildByTag(1000)
if msp then
--removeAni(msp)
return
end
rootNode.blackBg:setPositionX(blackBgRoot:getPositionX())
rootNode.blackBg:setVisible(true)
msp = cc.Sprite:create()
local frames = display.newFrames("userFrame%02d.png", 1, 90)
local animation = display.newAnimation(frames, 0.03)
msp:runAction(cc.RepeatForever:create(cc.Animate:create(animation)))
msp:setPosition(cc.p(root:getContentSize().width / 2, root:getContentSize().height / 2))
msp:setTag(1000)
root:addChild(msp)
end
-- 创建连杆动画
-- @ rootNode 游戏layer
-- @ nLinkCount 连杆次数
function BilliardsAniMgr:createLinkEffect(rootNode, nLinkCount)
print(" ========== link count is ", nLinkCount)
local sprite = cc.Sprite:create()
sprite:setCascadeOpacityEnabled(true)
sprite:setGlobalZOrder(150000)
-- local emitter = cc.ParticleFlower:create()
-- if emitter then
-- sprite:addChild(emitter, 10)
-- emitter:setOpacity(0.5)
-- emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage("gameBilliards/effect/stars.png"))
-- emitter:setPosition(cc.p(20, 0))
-- emitter:setLocalZOrder(-1)
-- emitter:setScale(1.5)
-- end
local spine = sp.SkeletonAnimation:create("spine/skeleton.json", "spine/skeleton.atlas", 1)
if spine then
spine:setAnchorPoint(cc.p(0.5, 0.5))
spine:setScale(1.5)
spine:setAnimation(0, "animation", false)
sprite:setTag(g_EightBallData.g_Border_Tag.linkSpine)
sprite:addChild(spine)
spine:setCascadeOpacityEnabled(false)
spine:setLocalZOrder(5)
end
if nLinkCount > 9 then
local ten = math.modf(nLinkCount / 10)
local one = nLinkCount % 10
local link1 = ccui.ImageView:create("img_num_" .. ten .. ".png", UI_TEX_TYPE_PLIST)
local link2 = ccui.ImageView:create("img_num_" .. one .. ".png", UI_TEX_TYPE_PLIST)
link1:setAnchorPoint(cc.p(0.5, 0.5))
link1:setScale(1)
link1:setPositionX(-100)
sprite:addChild(link1)
link2:setCascadeOpacityEnabled(true)
link2:setAnchorPoint(cc.p(0.5, 0.5))
link2:setScale(1)
link2:setPositionX(-50)
sprite:addChild(link2)
link2:setCascadeOpacityEnabled(true)
else
local link = ccui.ImageView:create("img_num_" .. nLinkCount .. ".png", UI_TEX_TYPE_PLIST)
if link then
link:setAnchorPoint(cc.p(0.5, 0.5))
link:setScale(1)
link:setPositionX(-50)
sprite:addChild(link)
link:setCascadeOpacityEnabled(true)
end
end
local word = ccui.ImageView:create("img_Effect_Link.png", UI_TEX_TYPE_PLIST)
if word then
word:setAnchorPoint(cc.p(0.5, 0.5))
word:setScale(1)
word:setPositionX(50)
sprite:addChild(word)
word:setCascadeOpacityEnabled(true)
end
rootNode:addChild(sprite)
sprite:setOpacity(0)
sprite:setPosition(cc.p(display.cx + 200, display.cy + 50))
sprite:setCameraMask(cc.CameraFlag.USER2)
sprite:runAction(cc.Sequence:create(
cc.FadeIn:create(0.5),
cc.DelayTime:create(1.5),
cc.FadeOut:create(0.5)
))
sprite:runAction(cc.Sequence:create(
cc.MoveTo:create(0.5, cc.p(sprite:getPositionX() + 50, sprite:getPositionY())),
cc.DelayTime:create(1.5),
cc.MoveTo:create(0.5, cc.p(sprite:getPositionX() + 100, sprite:getPositionY()))
))
sprite:runAction(cc.Sequence:create(cc.DelayTime:create(2.5),
cc.CallFunc:create( function()
if sprite and not tolua.isnull(sprite) then
sprite:stopAllActions()
sprite:removeAllChildren()
sprite:removeFromParent()
sprite = nil
end
end )))
end
-- 力量条数值显示
-- param@ root 三个数字的父节点
-- param@ num 力量大小
function BilliardsAniMgr:createPowerNumEffet(root, num)
local hundred = math.modf(num / 100)
local ten = math.modf(num / 10)%10
local one = num % 10
if hundred == 0 then
root:getChildByName("num1"):setVisible(false)
if ten == 0 or ten == 10 then
root:getChildByName("num2"):setVisible(false)
else
root:getChildByName("num2"):loadTexture("img_num_" .. ten .. ".png", UI_TEX_TYPE_PLIST)
root:getChildByName("num2"):setVisible(true)
end
else
root:getChildByName("num1"):loadTexture("img_num_" .. hundred .. ".png", UI_TEX_TYPE_PLIST)
root:getChildByName("num1"):setVisible(true)
root:getChildByName("num2"):loadTexture("img_num_" .. ten .. ".png", UI_TEX_TYPE_PLIST)
root:getChildByName("num2"):setVisible(true)
end
root:getChildByName("num3"):loadTexture("img_num_" .. one .. ".png", UI_TEX_TYPE_PLIST)
root:getChildByName("num3"):setVisible(true)
end
-- 创建屏幕中间提示信息(该你击球,你将击打花色求等)
-- @ rootNode 游戏图层
-- @ nType 枚举 = g_EightBallData.word
function BilliardsAniMgr:createWordEffect(rootNode, nType)
local spineWord
if nType == g_EightBallData.word.your then
spineWord = cc.Sprite:createWithSpriteFrameName("eightBall_Word_YourRound.png")
elseif nType == g_EightBallData.word.full then
spineWord = cc.Sprite:createWithSpriteFrameName("eightBall_Word_HitHalfBall.png")
elseif nType == g_EightBallData.word.half then
spineWord = cc.Sprite:createWithSpriteFrameName("eightBall_Word_HitFullBall.png")
end
spineWord:setCascadeOpacityEnabled(true)
spineWord:setGlobalZOrder(150000)
local spine = sp.SkeletonAnimation:create("spine/skeleton.json", "spine/skeleton.atlas", 1)
if spine then
spine:setAnchorPoint(cc.p(0.5, 0.5))
spine:setScale(1.5)
spine:setAnimation(0, "animation", false)
spine:setPosition(cc.p(spineWord:getContentSize().width / 2, spineWord:getContentSize().height / 2))
spineWord:addChild(spine)
spine:setCascadeOpacityEnabled(false)
spine:setLocalZOrder(5)
end
spineWord:setOpacity(0)
spineWord:setPosition(cc.p(display.cx - 100, display.cy))
spineWord:setCameraMask(cc.CameraFlag.USER2)
rootNode:addChild(spineWord)
spineWord:runAction(cc.Sequence:create(
cc.FadeIn:create(0.3),
cc.DelayTime:create(1),
cc.FadeOut:create(0.3)
))
spineWord:runAction(cc.Sequence:create(
cc.MoveTo:create(0.3, cc.p(spineWord:getPositionX() + 100, spineWord:getPositionY())),
cc.DelayTime:create(1),
cc.MoveTo:create(0.3, cc.p(spineWord:getPositionX() + 200, spineWord:getPositionY()))
))
spineWord:runAction(cc.Sequence:create(cc.DelayTime:create(1.65),
cc.CallFunc:create( function()
if spineWord and not tolua.isnull(spineWord) then
spineWord:stopAllActions()
spineWord:removeAllChildren()
spineWord:removeFromParent()
spineWord = nil
end
end )))
end
-- 设置力量条的进场出场动画
--@ isEnabled 是否是可以点击状态,动画状态
--@ m_MainLayer 游戏图层
function BilliardsAniMgr:setSliderBarAni(isEnabled, m_MainLayer)
print(" setSliderBarAni ",isEnabled)
BilliardsAniMgr:setFineTurningAni(isEnabled, m_MainLayer)
m_MainLayer.slider_View:setVisible(false)
m_MainLayer.img_PowerBar:stopAllActions()
local nodeWidth = m_MainLayer.node:getContentSize().width
local childWidth = m_MainLayer.img_PowerBar:getContentSize().width
if isEnabled then
local posX = 1136 +(display.width - nodeWidth) / 2
if posX ~= m_MainLayer.img_PowerBar:getPositionX() then
m_MainLayer.img_PowerBar:setPositionX(posX - childWidth)
return
end
m_MainLayer.slider_PowerBar:setTouchEnabled(true)
m_MainLayer.img_PowerBar:setPositionX(posX)
m_MainLayer.img_PowerBar:runAction(cc.MoveTo:create(0.5, cc.p(posX - childWidth, m_MainLayer.img_PowerBar:getPositionY())))
else
-- if EBGameControl:getGameState() == g_EightBallData.gameState.practise then
-- return
-- end
local posX = 1136 +(display.width - nodeWidth) / 2 - childWidth
if posX ~= m_MainLayer.img_PowerBar:getPositionX() then
m_MainLayer.img_PowerBar:setPositionX(posX + childWidth)
return
end
if EBGameControl:getGameState() ~= g_EightBallData.gameState.practise then
m_MainLayer.slider_PowerBar:setTouchEnabled(false)
end
m_MainLayer.img_PowerBar:setPositionX(posX)
m_MainLayer.img_PowerBar:runAction(cc.MoveTo:create(0.5, cc.p(posX + childWidth, m_MainLayer.img_PowerBar:getPositionY())))
end
end
-- 设置微调框的进场出场动画
-- @ isEnabled 是否可以点击状态,动画状态
-- @ m_MainLayer 游戏图层
function BilliardsAniMgr:setFineTurningAni(isEnabled, m_MainLayer)
m_MainLayer.layout_FineTurning:stopAllActions()
local nodeWidth = m_MainLayer.node:getContentSize().width
local childWidth = m_MainLayer.layout_FineTurning:getContentSize().width
if isEnabled then
local posX = 0 -(display.width - nodeWidth) / 2
-- if posX ~= m_MainLayer.layout_FineTurning:getPositionX() then
-- m_MainLayer.layout_FineTurning:setPositionX(posX + childWidth)
-- return
-- end
m_MainLayer.layout_FineTurning:setPositionX(posX)
m_MainLayer.layout_FineTurning:runAction(cc.MoveTo:create(0.5, cc.p(posX + childWidth, m_MainLayer.layout_FineTurning:getPositionY())))
else
local posX = 0 -(display.width - nodeWidth) / 2
-- if posX ~= m_MainLayer.layout_FineTurning:getPositionX() then
-- m_MainLayer.layout_FineTurning:setPositionX(posX - childWidth)
-- return
-- end
m_MainLayer.layout_FineTurning:setPositionX(posX+childWidth)
m_MainLayer.layout_FineTurning:runAction(cc.MoveTo:create(0.5, cc.p(posX - childWidth, m_MainLayer.layout_FineTurning:getPositionY())))
end
end
--比赛开始动画
function BilliardsAniMgr:setGameStartAni(rootBg)
local spine = sp.SkeletonAnimation:create("gameBilliards/effect/bisaikaishi_tx.json", "gameBilliards/effect/bisaikaishi_tx.atlas", 1)
if spine then
spine:setAnchorPoint(cc.p(0.5, 0.5))
spine:setScale(1)
spine:setAnimation(0, "bisaikaishi", false)
spine:setPosition(cc.p(rootBg:getContentSize().width / 2, rootBg:getContentSize().height / 2+50))
spine:setCameraMask(cc.CameraFlag.USER2)
spine:setGlobalZOrder(100000)
rootBg:addChild(spine)
end
end
function BilliardsAniMgr:setGameOverAni(isWin, rootBg)
local spine
if isWin then
ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("res/flash/yuan010.png", "res/flash/yuan010.plist", "res/flash/yuan01.ExportJson")
local spine = ccs.Armature:create("yuan01")
spine:setPosition(cc.p(display.cx, display.cy+50))
spine:setScale(3.0)
spine:setLocalZOrder(-1)
--spine:setCameraMask(cc.CameraFlag.USER2)
spine:getAnimation():play("Animation1")
rootBg:addChild(spine)
else
spine = sp.SkeletonAnimation:create("gameBilliards/effect/jiesuan_shibai.json", "gameBilliards/effect/jiesuan_shibai.atlas", 1)
spine:setAnimation(0, "jiesuan_shibai", true)
spine:setScale(0.5)
spine:setPosition(cc.p(rootBg:getContentSize().width / 2, rootBg:getContentSize().height / 2 + 180))
rootBg:addChild(spine)
end
end
-- 提示框信息
function BilliardsAniMgr:setGameTips(m_MainLayer,result)
--倒计时
local timer = m_MainLayer.tip:getChildByTag(g_EightBallData.g_Border_Tag.tipsTimer)
if not timer then
timer = ccui.ImageView:create()
timer:setTag(g_EightBallData.g_Border_Tag.tipsTimer)
local size = m_MainLayer.tip:getContentSize()
timer:setPositionX(timer:getPositionX() + 50)
--timer:setPosition(cc.p(size.width/2,size.height/2))
m_MainLayer.tip:addChild(timer)
local word = cc.Sprite:create("gameBilliards/eightBall/eightBall_Word_Timer.png")
word:setPosition(cc.p(-75,40))
timer:addChild(word)
end
timer:stopAllActions()
timer:setVisible(false)
local currentUserID = EightBallGameManager:getCurrentUserID()
local panel_Tip = m_MainLayer.panel_Tip
if result == g_EightBallData.gameRound.foul then
if currentUserID ~= -1 and currentUserID == player:getPlayerUserID() then
m_MainLayer.tip:setString("击球犯规,请放置自由球")
elseif currentUserID ~= -1 and currentUserID ~= player:getPlayerUserID() then
m_MainLayer.tip:setString("击球犯规,对手放置自由球")
else
return
end
elseif result == g_EightBallData.gameRound.keep then
if (currentUserID ~= -1 and currentUserID ~= player:getPlayerUserID()) --[[or EightBallGameManager:getColorUserID() <= 0]] then
m_MainLayer.tip:setString("继续击球")
else
return
end
elseif result == g_EightBallData.gameRound.change then
m_MainLayer.tip:setString("正常击球,交换击球权")
elseif result == g_EightBallData.gameRound.restart then
m_MainLayer.tip:setString("首杆进黑八,重新开始本局")
elseif result == g_EightBallData.gameRound.countdown then
if EightBallGameManager:getCurrentUserID() ~= player:getPlayerUserID() then
return
end
timer:setVisible(true)
m_MainLayer.tip:setString("")
timer:setScale(0.9)
timer:loadTexture("img_num_3.png",UI_TEX_TYPE_PLIST)
timer:runAction(cc.Sequence:create(
cc.DelayTime:create(1),
cc.CallFunc:create(function ()
timer:loadTexture("img_num_2.png",UI_TEX_TYPE_PLIST)
end),
cc.DelayTime:create(1),
cc.CallFunc:create(function ()
timer:loadTexture("img_num_1.png",UI_TEX_TYPE_PLIST)
end),
cc.DelayTime:create(1),
cc.CallFunc:create(function ()
timer:loadTexture("img_num_0.png",UI_TEX_TYPE_PLIST)
end),
cc.DelayTime:create(1),
cc.CallFunc:create(function ()
if timer and not tolua.isnull(timer) then
timer:stopAllActions()
timer:setVisible(false)
panel_Tip:runAction(cc.MoveTo:create(0.3, cc.p(display.cx, 0 -(display.height - m_MainLayer.node:getContentSize().height) / 2)))
end
end)
))
panel_Tip:runAction(cc.MoveTo:create(0.3, cc.p(display.cx, 0 -(display.height - m_MainLayer.node:getContentSize().height) / 2 + panel_Tip:getContentSize().height)))
return
else
m_MainLayer.tip:setString("")
panel_Tip:setPosition(cc.p(display.cx, 0 -(display.height - m_MainLayer.node:getContentSize().height) / 2))
return
end
local nodeHeight = m_MainLayer.node:getContentSize().height
local childHeight = panel_Tip:getContentSize().height
if panel_Tip then
panel_Tip:stopAllActions()
panel_Tip:setPosition(cc.p(display.cx, 0 -(display.height - nodeHeight) / 2))
panel_Tip:runAction(cc.Sequence:create(
cc.MoveTo:create(0.3, cc.p(display.cx, 0 -(display.height - nodeHeight) / 2 + childHeight)),
cc.DelayTime:create(1),
cc.CallFunc:create( function()
panel_Tip:runAction(cc.MoveTo:create(0.3, cc.p(display.cx, 0 -(display.height - nodeHeight) / 2)))
end )
))
end
end
--桌子白色摆放球的指示框
--@param isEnabled 是否需要亮出来
function BilliardsAniMgr:setDeskTempAni(m_MainLayer, isEnabled)
m_MainLayer.deskTemp:stopAllActions()
m_MainLayer.deskTemp:setOpacity(0)
if isEnabled then
if EBGameControl:getGameState() == g_EightBallData.gameState.practise or EightBallGameManager:getCurrentUserID() == player:getPlayerUserID() then
m_MainLayer.deskTemp:setVisible(true)
m_MainLayer.deskTemp:runAction(cc.RepeatForever:create(cc.Sequence:create(cc.FadeIn:create(1), cc.FadeOut:create(1))))
else
m_MainLayer.deskTemp:setVisible(false)
end
else
m_MainLayer.deskTemp:setVisible(false)
end
end
-- 设置头像框的倒计时
function BilliardsAniMgr:setHeadTimerAni(Bg, leftTime, callback)
--if EBGameControl:getGameState() ~= g_EightBallData.gameState.practise then
local size = Bg:getContentSize()
local ProgressTimerAction = Bg:getChildByTag(g_EightBallData.g_Border_Tag.timer)
if not ProgressTimerAction then
local sprite = cc.Sprite:create("gameBilliards/eightBall/eightBall_ProgressTimer_Bg.png")
ProgressTimerAction = cc.ProgressTimer:create(sprite)
ProgressTimerAction:setType(cc.PROGRESS_TIMER_TYPE_RADIAL)
ProgressTimerAction:setPosition(cc.p(Bg:getContentSize().width / 2, Bg:getContentSize().height / 2))
ProgressTimerAction:setAnchorPoint(cc.p(0.5, 0.5))
ProgressTimerAction:setReverseDirection(true)
ProgressTimerAction:setTag(g_EightBallData.g_Border_Tag.timer)
Bg:addChild(ProgressTimerAction)
end
local particle = Bg:getChildByTag(g_EightBallData.g_Border_Tag.clockParticle)
if not particle then
particle = cc.ParticleSystemQuad:create("gameBilliards/effect/ClockMove.plist")
particle:setLifeVar(2)
particle:setDuration(-1)
particle:setTag(g_EightBallData.g_Border_Tag.clockParticle)
Bg:addChild(particle)
end
particle:setPosition(cc.p(size.width /2 ,size.height-2))
particle:setVisible(true)
particle:stopAllActions()
local seq = cc.Sequence:create(
cc.MoveBy:create(leftTime / 8 , cc.p(size.width /2, 0)),
cc.MoveBy:create(leftTime / 4 , cc.p(0, -size.height+2)),
cc.MoveBy:create(leftTime / 4 , cc.p(-size.width+2, 0)),
cc.MoveBy:create(leftTime / 4 , cc.p(0, size.height-2)),
cc.CallFunc:create(function ( ... )
--最后3秒调用
print("last 3 seconds !")
--amgr.playViberate(0.3)
if callback then
callback()
end
end),
cc.MoveBy:create(leftTime / 8 , cc.p(size.width /2-1, 0)),
cc.CallFunc:create(function ( ... )
particle:setVisible(false)
end)
)
particle:runAction(seq)
if leftTime <= 0 then
ProgressTimerAction:setPercentage(0)
ProgressTimerAction:stopAllActions()
particle:setVisible(false)
return
end
local wholeTime = leftTime * 5
if leftTime > 20 then
wholeTime = 100
end
local progressTo = cc.ProgressFromTo:create(leftTime, wholeTime, 0)
local clear = cc.CallFunc:create( function()
end )
ProgressTimerAction:runAction(cc.Sequence:create(progressTo, clear))
--end
end
--指示球设置
function BilliardsAniMgr:setTipBallsAni(root,tipBalls,index,pos)
if root then
local tip = tipBalls[index]
if tip then
root:addChild(tip)
tip:setPositionX()
end
end
end
function BilliardsAniMgr:init()
end
return BilliardsAniMgr
|
-- Skeleton Entity
--
local Base = require 'src.entities.entities.active.units.base'
local Skeleton = Base:extend()
function Skeleton:new(data)
Base.new(self, _:merge({
name = 'skeleton',
systems = {
'gravity',
'proximity',
--
animation = Animation['skeleton'],
health = { hp = 25 },
move = { spd = 50 },
death = { },
hit = { delay = 0.25 },
regen = { rate = 1, amt = 1 },
revive = { delay = 5 }
},
behaviors = {
{ 'damage' }, -- reacts to damage
-- { 'attack' }, -- can attack
{ 'patrol' } -- default: patrol
}
}, data))
end
-- Update (req'd to run systems)
--
function Skeleton:update(dt)
Base.update(self, dt)
end
return Skeleton
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.