content
stringlengths 5
1.05M
|
---|
local utils = require 'spec.utils'
local OpCode = require 'lustre.frame.opcode'
describe('OpCode', function ()
describe('encode/decode', function ()
it('data-continue', function ()
local code = 0
local oc = OpCode.decode(code)
utils.assert_eq(oc.type, 'data')
utils.assert_eq(oc.sub, 'continue')
utils.assert_eq(oc.value, nil)
utils.assert_eq(oc:encode(), code)
end)
it('data-text', function ()
local code = 1
local oc = OpCode.decode(code)
utils.assert_eq(oc.type, 'data')
utils.assert_eq(oc.sub, 'text')
utils.assert_eq(oc.value, nil)
utils.assert_eq(oc:encode(), code)
end)
it('data-binary', function ()
local code = 2
local oc = OpCode.decode(code)
utils.assert_eq(oc.type, 'data')
utils.assert_eq(oc.sub, 'binary')
utils.assert_eq(oc.value, nil)
utils.assert_eq(oc:encode(), code)
end)
it('data-reserved', function ()
for code = 3, 7 do
local oc = OpCode.decode(code)
utils.assert_eq(oc.type, 'data')
utils.assert_eq(oc.sub, 'reserved')
utils.assert_eq(oc.value, code)
utils.assert_eq(oc:encode(), code)
end
end)
it('data-control', function ()
local code = 8
local oc = OpCode.decode(code)
utils.assert_eq(oc.type, 'control')
utils.assert_eq(oc.sub, 'close')
utils.assert_eq(oc.value, nil)
utils.assert_eq(oc:encode(), code)
end)
it('data-control', function ()
local code = 9
local oc = OpCode.decode(code)
utils.assert_eq(oc.type, 'control')
utils.assert_eq(oc.sub, 'ping')
utils.assert_eq(oc.value, nil)
utils.assert_eq(oc:encode(), code)
end)
it('data-control', function ()
local code = 10
local oc = OpCode.decode(code)
utils.assert_eq(oc.type, 'control')
utils.assert_eq(oc.sub, 'pong')
utils.assert_eq(oc.value, nil)
utils.assert_eq(oc:encode(), code)
end)
it('data-control', function ()
for code = 11, 15 do
local oc = OpCode.decode(code)
utils.assert_eq(oc.type, 'control')
utils.assert_eq(oc.sub, 'reserved')
utils.assert_eq(oc.value, code)
utils.assert_eq(oc:encode(), code)
end
end)
it('out of range', function ()
local oc = OpCode.decode(16)
utils.assert_eq(oc, nil)
end)
it('bad values', function ()
local oc = OpCode.from('junk')
local b, err = oc:encode()
assert(not b, 'expected no bytes')
utils.assert_eq(err, 'Invalid opcode')
end)
describe('type constructors', function ()
it('ping', function ()
local oc = OpCode.ping()
utils.assert_eq(oc.type, 'control')
utils.assert_eq(oc.sub, 'ping')
utils.assert_eq(oc:encode(), 9)
end)
it('pong', function ()
local oc = OpCode.pong()
utils.assert_eq(oc.type, 'control')
utils.assert_eq(oc.sub, 'pong')
utils.assert_eq(oc:encode(), 10)
end)
it('close', function ()
local oc = OpCode.close()
utils.assert_eq(oc.type, 'control')
utils.assert_eq(oc.sub, 'close')
utils.assert_eq(oc:encode(), 8)
end)
it('continue', function ()
local oc = OpCode.continue()
utils.assert_eq(oc.type, 'data')
utils.assert_eq(oc.sub, 'continue')
utils.assert_eq(oc:encode(), 0)
end)
it('text', function ()
local oc = OpCode.text()
utils.assert_eq(oc.type, 'data')
utils.assert_eq(oc.sub, 'text')
utils.assert_eq(oc:encode(), 1)
end)
it('binary', function ()
local oc = OpCode.binary()
utils.assert_eq(oc.type, 'data')
utils.assert_eq(oc.sub, 'binary')
utils.assert_eq(oc:encode(),2)
end)
end)
end)
end)
|
-- see elepower_papi >> external_nodes_items.lua for explanation
-- shorten table ref
local epi = ele.external.ing
--*****************--
-- MACHINE RECIPES --
--*****************--
--------------
-- Alloying --
--------------
local alloy_recipes = {
{
recipe = { "elepower_dynamics:iron_ingot", "elepower_dynamics:coal_dust 4" },
output = epi.steel_ingot,
},
{
recipe = { epi.copper_ingot.." 2", epi.tin_ingot },
output = epi.bronze_ingot.." 3",
},
{
recipe = { "elepower_dynamics:iron_ingot 3", "elepower_dynamics:nickel_ingot" },
output = "elepower_dynamics:invar_ingot 4",
},
{
recipe = { epi.gold_ingot.." 2", "elepower_dynamics:invar_ingot" },
output = "elepower_dynamics:electrum_ingot 3",
},
{
recipe = { "basic_materials:silicon", "elepower_dynamics:coal_dust 2" },
output = "elepower_dynamics:silicon_wafer",
},
{
recipe = { epi.coal_lump, "elepower_dynamics:coal_dust 4" },
output = "elepower_dynamics:graphite_ingot",
},
{
recipe = { "elepower_dynamics:silicon_wafer", "elepower_dynamics:gold_dust 4" },
output = "elepower_dynamics:silicon_wafer_doped",
time = 8,
},
{
recipe = { epi.obsidian_glass, "elepower_dynamics:lead_ingot 4" },
output = "elepower_dynamics:hardened_glass 4",
time = 8,
},
{
recipe = { epi.copper_ingot.." 2", epi.silver_ingot },
output = "basic_materials:brass_ingot 3",
time = 8,
},
{
recipe = { epi.bronze_ingot, epi.steel_ingot.." 4" },
output = "elepower_machines:heat_casing 4",
},
}
-- Register alloy furnace recipes
for _,i in pairs(alloy_recipes) do
elepm.register_craft({
type = "alloy",
recipe = i.recipe,
output = i.output,
time = i.time or 4
})
end
--------------
-- Grinding --
--------------
local keywords = { _ingot = 1, _lump = 2, _block = 9, block = 9 }
local ingot_map = {}
local block_map = {}
for mat, data in pairs(elepd.registered_dusts) do
local kwfound = nil
for keyword,count in pairs(keywords) do
local found = ele.helpers.scan_item_list(mat .. keyword)
if found then
if keyword == "_ingot" and not kwfound then
kwfound = found
elseif keyword == "_block" or keyword == "block" and not block_map[mat] then
block_map[mat] = found
end
-- Grind recipe for material
elepm.register_craft({
type = "grind",
recipe = { found },
output = data.item .. " " .. count,
time = count + 4,
})
end
end
-- Add dust -> ingot smelting
if kwfound then
ingot_map[mat] = kwfound
minetest.register_craft({
type = "cooking",
recipe = data.item,
output = kwfound
})
end
end
-- Other recipes
local grinding_recipes = {
{
recipe = { epi.wheat },
output = epi.flour.." 2",
time = 4,
},
{
recipe = { epi.desert_sand.." 4" },
output = "basic_materials:silicon",
},
{
recipe = { epi.sand.." 4" },
output = "basic_materials:silicon",
},
{
recipe = { epi.cobble },
output = epi.gravel.." 4",
},
{
recipe = { epi.gravel },
output = epi.sand.." 4",
},
{
recipe = { epi.mese },
output = epi.mese_crystal.." 9",
},
{
recipe = { epi.mese_crystal },
output = epi.mese_crystal_fragment.." 9",
},
{
recipe = { epi.mese_crystal_fragment },
output = "elepower_dynamics:mese_dust",
},
{
recipe = { "elepower_dynamics:graphite_ingot" },
output = "elepower_dynamics:graphite_rod 3",
}
}
-- Register grind recipes
for _,i in pairs(grinding_recipes) do
elepm.register_craft({
type = "grind",
recipe = i.recipe,
output = i.output,
time = i.time or 8,
})
end
-----------------
-- Compressing --
-----------------
for mat, ingot in pairs(ingot_map) do
local plate = elepd.registered_plates[mat]
local dust = elepd.registered_dusts[mat]
if plate then
elepm.register_craft({
type = "compress",
recipe = {ingot,ingot},
output = plate.item.." 2",
time = 4,
})
if dust then
elepm.register_craft({
type = "grind",
recipe = { plate.item },
output = dust.item.." 2",
time = 6,
})
end
end
end
-- Detect sands
for name in pairs(minetest.registered_nodes) do
if name:match("sand") and not name:match("sandstone") then
local sand = name
local sandstone = name .. "stone"
if minetest.registered_nodes[sandstone] then
elepm.register_craft({
type = "compress",
recipe = { sand .. " 2",sand .. " 2"},
output = sandstone,
time = 1,
})
-- Also give a grinding recipe to get the sand back
elepm.register_craft({
type = "grind",
recipe = { sandstone },
output = sand .. " 4",
time = 5,
})
-- Find block as well
local ssblock = sandstone .. "_block"
if minetest.registered_nodes[ssblock] then
elepm.register_craft({
type = "compress",
recipe = { sandstone .. " 2",sandstone .. " 2" },
output = ssblock,
time = 1,
})
end
end
end
end
local compressor_recipes = {
{
recipe = { "elepower_dynamics:viridisium_block 4", "elepower_dynamics:viridisium_block 4" },
output = "elepower_dynamics:xycrone_lump",
time = 20,
},
{
recipe = { epi.mese_crystal_fragment.." 4", epi.mese_crystal_fragment.." 4" },
output = epi.mese_crystal,
time = 2,
},
{
recipe = { epi.mese_crystal.." 4",epi.mese_crystal.." 4" },
output = epi.mese,
time = 2,
},
{
recipe = { "elepower_dynamics:coal_dust 2","elepower_dynamics:coal_dust 2" },
output = "elepower_dynamics:carbon_fiber",
time = 2,
},
{
recipe = { "elepower_dynamics:carbon_fiber 2","elepower_dynamics:carbon_fiber 2" },
output = "elepower_dynamics:carbon_sheet",
time = 2,
}
}
-- Register compressor recipes
for _,i in pairs(compressor_recipes) do
elepm.register_craft({
type = "compress",
recipe = i.recipe,
output = i.output,
time = i.time or 1
})
end
-------------
-- Sawmill --
-------------
-- Register all logs as sawable, if we can find a planks version
minetest.after(0.2, function ()
local wood_nodes = {}
for name in pairs(minetest.registered_nodes) do
if ele.helpers.get_item_group(name, "wood") then
wood_nodes[#wood_nodes + 1] = name
end
end
-- Begin making associations
-- Get crafting recipe for all woods
local assoc = {}
for _,wood in ipairs(wood_nodes) do
local recipes = minetest.get_all_craft_recipes(wood)
if recipes then
for _, recipe in ipairs(recipes) do
if recipe.items and #recipe.items == 1 then
assoc[recipe.items[1]] = wood
end
end
end
end
-- Register sawmill craft
for tree, wood in pairs(assoc) do
elepm.register_craft({
type = "saw",
recipe = { tree },
output = {wood .. " 6", "elepower_dynamics:wood_dust"},
time = 8,
})
end
end)
---------------
-- Soldering --
---------------
local soldering_recipes = {
{
recipe = { "elepower_dynamics:silicon_wafer_doped", "elepower_dynamics:chip 4", "elepower_dynamics:lead_ingot 2" },
output = "elepower_dynamics:microcontroller",
time = 8,
},
{
recipe = { epi.copper_ingot.." 4", "elepower_dynamics:microcontroller 4", "elepower_dynamics:electrum_ingot 2" },
output = "elepower_dynamics:soc",
time = 28,
},
{
recipe = { "elepower_dynamics:microcontroller", "elepower_dynamics:control_circuit", "elepower_dynamics:capacitor 5" },
output = "elepower_dynamics:micro_circuit",
time = 18,
},
{
recipe = { "elepower_dynamics:chip 8", "elepower_dynamics:integrated_circuit 2", "elepower_dynamics:capacitor 4" },
output = "elepower_dynamics:control_circuit",
time = 20,
},
{
recipe = { "elepower_dynamics:wound_copper_coil 4", "elepower_dynamics:wound_silver_coil 2", "basic_materials:copper_wire" },
output = "elepower_dynamics:induction_coil",
time = 16,
},
{
recipe = { "elepower_dynamics:induction_coil 4", "basic_materials:copper_wire", "elepower_dynamics:zinc_dust 2" },
output = "elepower_dynamics:induction_coil_advanced",
time = 18,
},
{
recipe = { "elepower_machines:power_cell_0", "elepower_machines:hardened_capacitor 2", "elepower_dynamics:invar_plate 8" },
output = "elepower_machines:hardened_power_cell_0",
time = 18,
},
{
recipe = { "elepower_machines:hardened_power_cell_0", "elepower_machines:reinforced_capacitor 2", "elepower_dynamics:electrum_plate 8" },
output = "elepower_machines:reinforced_power_cell_0",
time = 20,
},
{
recipe = { "elepower_machines:reinforced_power_cell_0", "elepower_machines:resonant_capacitor 2", "elepower_dynamics:viridisium_plate 8" },
output = "elepower_machines:resonant_power_cell_0",
time = 22,
},
{
recipe = { "elepower_machines:resonant_power_cell_0", "elepower_machines:super_capacitor 2", "elepower_dynamics:xycrone_lump" },
output = "elepower_machines:super_power_cell_0",
time = 24,
},
{
recipe = { "elepower_dynamics:integrated_circuit", "elepower_dynamics:induction_coil 2", "elepower_dynamics:soc" },
output = "elepower_machines:upgrade_speed",
time = 16,
},
{
recipe = { "elepower_dynamics:integrated_circuit", "elepower_machines:hardened_capacitor 2", "elepower_dynamics:soc" },
output = "elepower_machines:upgrade_efficiency",
time = 16,
},
{
recipe = { "elepower_machines:upgrade_efficiency", "elepower_machines:resonant_capacitor 2", "elepower_dynamics:soc" },
output = "elepower_machines:upgrade_efficiency_2",
time = 16,
}
}
-- Register solderer recipes
for _,i in pairs(soldering_recipes) do
elepm.register_craft({
type = "solder",
recipe = i.recipe,
output = i.output,
time = i.time or 4
})
end
-------------
-- Canning --
-------------
--******************--
-- CRAFTING RECIPES --
--******************--
-- Capacitors
minetest.register_craft({
output = "elepower_machines:hardened_capacitor",
recipe = {
{"basic_materials:plastic_sheet", "basic_materials:plastic_sheet", "basic_materials:plastic_sheet"},
{"elepower_dynamics:invar_plate", epi.mese_crystal , "elepower_dynamics:invar_plate"},
{"elepower_dynamics:invar_plate", "elepower_dynamics:capacitor" , "elepower_dynamics:invar_plate"},
}
})
minetest.register_craft({
output = "elepower_machines:reinforced_capacitor",
recipe = {
{"elepower_dynamics:invar_plate", "elepower_dynamics:invar_plate", "elepower_dynamics:invar_plate"},
{"elepower_dynamics:electrum_plate", epi.mese_crystal , "elepower_dynamics:electrum_plate"},
{"elepower_dynamics:electrum_plate", "elepower_machines:hardened_capacitor", "elepower_dynamics:electrum_plate"},
}
})
minetest.register_craft({
output = "elepower_machines:resonant_capacitor",
recipe = {
{"elepower_dynamics:electrum_plate", "elepower_dynamics:electrum_plate", "elepower_dynamics:electrum_plate"},
{"elepower_dynamics:viridisium_plate", epi.mese_crystal , "elepower_dynamics:viridisium_plate"},
{"elepower_dynamics:viridisium_plate", "elepower_machines:reinforced_capacitor", "elepower_dynamics:viridisium_plate"},
}
})
minetest.register_craft({
output = "elepower_machines:super_capacitor",
recipe = {
{"elepower_dynamics:viridisium_plate", "elepower_dynamics:viridisium_plate", "elepower_dynamics:viridisium_plate"},
{"elepower_dynamics:viridisium_plate", "elepower_dynamics:xycrone_lump", "elepower_dynamics:viridisium_plate"},
{"elepower_dynamics:xycrone_lump", "elepower_machines:resonant_capacitor", "elepower_dynamics:xycrone_lump"},
}
})
minetest.register_craft({
output = "elepower_machines:heavy_filter",
recipe = {
{"elepower_dynamics:steel_plate", "fluid_transfer:fluid_duct", "elepower_dynamics:steel_plate"},
{"basic_materials:silicon", "elepower_dynamics:servo_valve", "basic_materials:silicon"},
{"elepower_dynamics:carbon_sheet", "fluid_transfer:fluid_duct", "elepower_dynamics:carbon_sheet"}
}
})
minetest.register_craft({
output = "elepower_machines:opaque_duct_roll",
recipe = {
{"elepower_dynamics:opaque_duct", "elepower_dynamics:opaque_duct", "elepower_dynamics:opaque_duct"},
{"elepower_dynamics:opaque_duct", "basic_materials:motor", "elepower_dynamics:opaque_duct"},
{"elepower_dynamics:opaque_duct", "elepower_dynamics:opaque_duct", "elepower_dynamics:opaque_duct"},
}
})
minetest.register_craft({
output = "elepower_machines:wind_turbine_blade",
recipe = {
{"" , epi.group_wood , epi.group_wood},
{epi.group_stick, epi.group_wood , epi.group_wood},
{epi.group_stick, epi.group_stick, ""},
}
})
minetest.register_craft({
output = "elepower_machines:wind_turbine_blades",
recipe = {
{"elepower_machines:wind_turbine_blade", "elepower_machines:wind_turbine_blade", "elepower_machines:wind_turbine_blade"},
{"elepower_machines:wind_turbine_blade", epi.group_wood , "elepower_machines:wind_turbine_blade"},
{"elepower_machines:wind_turbine_blade", "elepower_machines:wind_turbine_blade", "elepower_machines:wind_turbine_blade"},
}
})
-- Nodes
-- Coal-fired Alloy Furnace
minetest.register_craft({
output = "elepower_machines:coal_alloy_furnace",
recipe = {
{epi.brick, epi.brick , epi.brick},
{epi.brick, epi.coal_lump, epi.brick},
{epi.brick, epi.brick , epi.brick},
}
})
-- Grindstone
minetest.register_craft({
output = "elepower_machines:grindstone",
recipe = {
{epi.group_stone, epi.group_stone, epi.group_stone},
{epi.flint , epi.flint , epi.flint },
{epi.cobble , epi.cobble , epi.cobble }
}
})
minetest.register_craft({
output = "elepower_machines:crank",
recipe = {
{epi.group_stick, epi.group_stick, epi.group_stick},
{"" , "" , epi.group_stick},
{"" , "" , epi.group_stick}
}
})
-- Machine block
minetest.register_craft({
output = "elepower_machines:machine_block",
recipe = {
{epi.steel_ingot, epi.glass , epi.steel_ingot},
{epi.glass , "elepower_dynamics:brass_gear", epi.glass },
{epi.steel_ingot, "basic_materials:motor" , epi.steel_ingot}
}
})
-- Generator
minetest.register_craft({
output = "elepower_machines:generator",
recipe = {
{"" , epi.steel_ingot , "" },
{epi.steel_ingot , "elepower_machines:machine_block", epi.steel_ingot },
{"elepower_dynamics:wound_copper_coil", epi.coal_lump , "elepower_dynamics:wound_copper_coil"}
}
})
-- Liquid Fuel Combustion Generator
minetest.register_craft({
output = "elepower_machines:fuel_burner",
recipe = {
{"elepower_dynamics:wound_copper_coil", "elepower_dynamics:integrated_circuit", "elepower_dynamics:wound_copper_coil"},
{epi.brick , "elepower_dynamics:portable_tank" , epi.brick},
{"elepower_dynamics:servo_valve" , "elepower_machines:generator" , "elepower_dynamics:servo_valve"},
}
})
-- Alloy Furnace
minetest.register_craft({
output = "elepower_machines:alloy_furnace",
recipe = {
{ "" , "elepower_dynamics:integrated_circuit", "" },
{"elepower_dynamics:wound_copper_coil","basic_materials:heating_element", "elepower_dynamics:wound_copper_coil"},
{epi.brick , "elepower_machines:machine_block" , epi.brick },
}
})
-- Solderer
minetest.register_craft({
output = "elepower_machines:solderer",
recipe = {
{"" , "elepower_dynamics:integrated_circuit", "" },
{"elepower_dynamics:chip" , "elepower_machines:machine_block" , "elepower_dynamics:chip" },
{"elepower_dynamics:invar_gear","elepower_dynamics:wound_copper_coil","elepower_dynamics:invar_gear"}
}
})
-- Furnace
minetest.register_craft({
output = "elepower_machines:furnace",
recipe = {
{"", "elepower_dynamics:integrated_circuit", ""},
{"elepower_dynamics:wound_copper_coil","basic_materials:heating_element", "elepower_dynamics:wound_copper_coil"},
{epi.clay_brick, "elepower_machines:machine_block", epi.clay_brick},
}
})
-- Pulverizer
minetest.register_craft({
output = "elepower_machines:pulverizer",
recipe = {
{"", "elepower_dynamics:integrated_circuit", ""},
{epi.flint, "elepower_machines:machine_block", epi.flint},
{"elepower_dynamics:wound_copper_coil", "elepower_dynamics:lead_gear", "elepower_dynamics:wound_copper_coil"},
}
})
-- Sawmill
minetest.register_craft({
output = "elepower_machines:sawmill",
recipe = {
{"", "elepower_dynamics:integrated_circuit", ""},
{"elepower_dynamics:steel_gear", "elepower_machines:machine_block", "elepower_dynamics:steel_gear"},
{"elepower_dynamics:lead_ingot", "elepower_dynamics:diamond_gear", "elepower_dynamics:lead_ingot"},
}
})
-- Power Cell
minetest.register_craft({
output = "elepower_machines:power_cell_0",
recipe = {
{"elepower_dynamics:lead_ingot", "elepower_dynamics:control_circuit", "elepower_dynamics:lead_ingot"},
{"elepower_dynamics:wound_copper_coil", "elepower_machines:machine_block", "elepower_dynamics:wound_copper_coil"},
{"elepower_dynamics:lead_ingot", "elepower_dynamics:battery", "elepower_dynamics:lead_ingot"},
}
})
-- Water Accumulator
minetest.register_craft({
output = "elepower_machines:accumulator",
recipe = {
{"", "fluid_transfer:fluid_duct", ""},
{epi.glass, "elepower_machines:machine_block", epi.glass},
{"elepower_dynamics:steel_gear", "elepower_dynamics:servo_valve", "elepower_dynamics:steel_gear"},
}
})
-- Lava Cooler
minetest.register_craft({
output = "elepower_machines:lava_cooler",
recipe = {
{"bucket:bucket_water", "elepower_dynamics:control_circuit", "bucket:bucket_lava"},
{"fluid_transfer:fluid_duct", "elepower_machines:machine_block", "fluid_transfer:fluid_duct"},
{"elepower_dynamics:servo_valve", "elepower_dynamics:tin_gear", "elepower_dynamics:servo_valve"},
},
replacements = {
{"bucket:bucket_water", "bucket:bucket_empty"},
{"bucket:bucket_lava", "bucket:bucket_empty"},
}
})
-- Lava Generator
minetest.register_craft({
output = "elepower_machines:lava_generator",
recipe = {
{"elepower_dynamics:wound_silver_coil", "elepower_dynamics:control_circuit", "elepower_dynamics:wound_silver_coil"},
{epi.brick, "elepower_machines:machine_block", epi.brick},
{"elepower_dynamics:invar_gear", "elepower_dynamics:servo_valve", "elepower_dynamics:invar_gear"},
},
})
-- Compressor Piston
minetest.register_craft({
output = "elepower_machines:compressor_piston",
recipe = {
{"", epi.steel_ingot, ""},
{"", epi.steel_ingot, ""},
{epi.bronze_ingot, epi.bronze_ingot, epi.bronze_ingot},
}
})
minetest.register_craft({
output = "elepower_machines:compressor_piston",
recipe = {
{"", epi.steel_ingot, ""},
{"", epi.steel_ingot, ""},
{"", "elepower_dynamics:bronze_plate", ""},
}
})
-- Compressor
minetest.register_craft({
output = "elepower_machines:compressor",
recipe = {
{"elepower_dynamics:integrated_circuit", "elepower_machines:compressor_piston", "elepower_dynamics:wound_copper_coil"},
{"elepower_dynamics:steel_gear", "elepower_machines:machine_block", "elepower_dynamics:steel_gear"},
{epi.steel_ingot , "elepower_machines:compressor_piston", epi.steel_ingot }
}
})
-- Turbine blades
minetest.register_craft({
output = "elepower_machines:turbine_blades",
recipe = {
{"elepower_dynamics:steel_plate", "elepower_dynamics:steel_plate", "elepower_dynamics:steel_plate"},
{"elepower_dynamics:steel_plate", epi.steel_ingot , "elepower_dynamics:steel_plate"},
{"elepower_dynamics:steel_plate", "elepower_dynamics:steel_plate", "elepower_dynamics:steel_plate"}
}
})
-- Steam Turbine
minetest.register_craft({
output = "elepower_machines:steam_turbine",
recipe = {
{"elepower_dynamics:induction_coil", "elepower_machines:turbine_blades", "elepower_dynamics:induction_coil"},
{"elepower_dynamics:steel_plate", "elepower_machines:machine_block", "elepower_dynamics:steel_plate"},
{"elepower_dynamics:invar_gear", "elepower_machines:turbine_blades", "elepower_dynamics:invar_gear"},
}
})
-- Canning Machine
minetest.register_craft({
output = "elepower_machines:canning_machine",
recipe = {
{"elepower_dynamics:wound_copper_coil", "elepower_machines:compressor_piston", "elepower_dynamics:wound_copper_coil"},
{"elepower_dynamics:tin_can", "elepower_machines:machine_block", "elepower_dynamics:tin_can"},
{"elepower_dynamics:steel_gear", "elepower_dynamics:tin_gear", "elepower_dynamics:steel_gear"},
}
})
-- Bucketer
minetest.register_craft({
output = "elepower_machines:bucketer",
recipe = {
{"", "elepower_dynamics:portable_tank", ""},
{"elepower_dynamics:tin_can", "elepower_machines:machine_block", "elepower_dynamics:tin_can"},
{"elepower_dynamics:servo_valve", "elepower_dynamics:tin_gear", "elepower_dynamics:servo_valve"},
}
})
-- Electrolyzer
minetest.register_craft({
output = "elepower_machines:electrolyzer",
recipe = {
{"elepower_dynamics:copper_plate", "elepower_dynamics:integrated_circuit", "elepower_dynamics:zinc_plate"},
{"bucket:bucket_empty", "elepower_machines:machine_block", "elepower_dynamics:gas_container"},
{"elepower_dynamics:servo_valve", "elepower_dynamics:wound_copper_coil", "elepower_dynamics:servo_valve"},
}
})
-- Advanced Machine Block
minetest.register_craft({
output = "elepower_machines:advanced_machine_block 4",
recipe = {
{"elepower_dynamics:electrum_plate", "elepower_dynamics:induction_coil_advanced", "elepower_dynamics:electrum_plate"},
{"elepower_dynamics:brass_plate", "elepower_machines:heat_casing", "elepower_dynamics:brass_plate"},
{"elepower_dynamics:electrum_plate", "elepower_dynamics:induction_coil_advanced", "elepower_dynamics:electrum_plate"},
}
})
-- Pump
minetest.register_craft({
output = "elepower_machines:pump",
recipe = {
{"elepower_dynamics:lead_gear", "elepower_dynamics:integrated_circuit", "elepower_dynamics:lead_gear"},
{"bucket:bucket_empty", "elepower_machines:machine_block", "bucket:bucket_empty"},
{"elepower_dynamics:electrum_plate", "elepower_machines:opaque_duct_roll", "elepower_dynamics:electrum_plate"},
}
})
-- Wind Turbine
minetest.register_craft({
output = "elepower_machines:wind_turbine",
recipe = {
{"elepower_dynamics:wound_copper_coil", "elepower_machines:turbine_blades", "elepower_dynamics:wound_copper_coil"},
{"elepower_dynamics:steel_plate", "elepower_machines:machine_block", "elepower_dynamics:steel_plate"},
{"elepower_dynamics:invar_gear", "elepower_dynamics:steel_plate", "elepower_dynamics:invar_gear"},
}
})
-- Evaporizer
minetest.register_craft({
output = "elepower_machines:evaporator",
recipe = {
{"elepower_dynamics:steel_plate", epi.steel_block, "elepower_dynamics:steel_plate"},
{"elepower_dynamics:steel_plate", "elepower_machines:machine_block", "elepower_dynamics:steel_plate"},
{"elepower_dynamics:induction_coil", "elepower_dynamics:zinc_plate", "elepower_dynamics:induction_coil"},
}
})
-- PCB Plant
minetest.register_craft({
output = "elepower_machines:pcb_plant",
recipe = {
{"", "elepower_dynamics:integrated_circuit", ""},
{"elepower_dynamics:chip", "elepower_machines:machine_block", "elepower_dynamics:chip"},
{"elepower_dynamics:servo_valve", "elepower_dynamics:uv_bulb", "elepower_dynamics:bronze_gear"},
}
})
|
--
-- tests/actions/vstudio/vc2010/test_globals.lua
-- Validate generation of the Globals property group.
-- Copyright (c) 2011-2012 Jason Perkins and the Premake project
--
T.vstudio_vs2010_globals = { }
local suite = T.vstudio_vs2010_globals
local vc2010 = premake.vstudio.vc2010
--
-- Setup
--
local sln, prj
function suite.setup()
sln = test.createsolution()
uuid "AE61726D-187C-E440-BD07-2556188A6565"
end
local function prepare()
prj = premake.solution.getproject_ng(sln, 1)
vc2010.globals(prj)
end
--
-- Check the structure with the default project values.
--
function suite.structureIsCorrect_onDefaultValues()
prepare()
test.capture [[
<PropertyGroup Label="Globals">
<ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>MyProject</RootNamespace>
</PropertyGroup>
]]
end
--
-- Ensure CLR support gets enabled for Managed C++ projects.
--
function suite.keywordIsCorrect_onManagedC()
flags { "Managed" }
prepare()
test.capture [[
<PropertyGroup Label="Globals">
<ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<Keyword>ManagedCProj</Keyword>
<RootNamespace>MyProject</RootNamespace>
</PropertyGroup>
]]
end
|
function findmodname()
-- find the current mod name
return debug.getinfo(2, "S").source:sub(2):match("(__.[^/]*__)/")
end
function prequire(f)
-- protected variant of require
local s, e = pcall(
function()
require(f)
end
)
if not s then
if type(e) == "string" then
print(f .. ":" .. e)
else
print(f .. ": can't load " .. modname .. "/" .. string.gsub(f, "%.", "/") .. ".lua")
end
end
end
function patch()
-- apply texturepack
local function foreach(d, g, t, n, p, i)
if d[n] ~= nil then
if type(d[n]) == "function" then
d[n](n, p, i)
else
p[i] = d[n]
end
end
if type(t) == "table" then
for k, v in pairs(t) do
foreach(d, g, v, n .. "." .. k, t, k)
end
elseif type(t) == "string" then
if g[t] ~= nil then
if type(g[t]) == "function" then
g[t](n, p, i)
else
p[i] = g[t]
end
end
end
end
foreach(overwrite_data, overwrite_graphics, data.raw, "data.raw")
end
overwrite_data = {}
overwrite_graphics = {}
-- modname = findmodname()
modname = "updated-graphics"
------ Methods updating texture list ------
function merge(t1, t2)
-- extend table with content based on key
for k, v in pairs(t2) do
t1[k] = v
end
end
function update(t1, t2)
-- update already defined key only
for k, v in pairs(t2) do
if t1[k] ~= nil then
t1[k] = v
end
end
end
function extend(t1, t2)
-- extend table with content based on value
for _, v in pairs(t2) do
table.insert(t1, v)
end
end
------ patching methods ------
function replace(r)
-- replace the texture with the new version and apply modifications on neighbors keys
return function(n, p, i)
p[i] = string.gsub(p[i], "(__.[^/]+__)", "__" .. modname .. "__/%1")
if r ~= nil then
for k, v in pairs(r) do
p[k] = v
end
end
end
end
function neighbors(r)
-- apply modifications on neighbors keys
return function(n, p, i)
if r ~= nil then
for k, v in pairs(r) do
p[k] = v
end
end
end
end
function combine(r)
-- apply multiple patching methods
return function(n, p, i)
if r ~= nil then
for _, v in pairs(r) do
v(n, p, i)
end
end
end
end
function fix(k, t)
-- change a value by those indicated
return function(n, p, i)
if t[p[k]] ~= nil then
p[k] = t[p[k]]
end
end
end
|
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/1.jpg')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'des_ripplsand')
engineApplyShaderToWorldTexture(shader, 'des_dirt1')
engineApplyShaderToWorldTexture(shader, 'des_dirt1grass')
engineApplyShaderToWorldTexture(shader, 'con2sand1a')
engineApplyShaderToWorldTexture(shader, 'con2sand1b')
engineApplyShaderToWorldTexture(shader, 'con2sand1c')
engineApplyShaderToWorldTexture(shader, 'concretedust2_line')
engineApplyShaderToWorldTexture(shader, 'hiway2sand1a')
engineApplyShaderToWorldTexture(shader, 'golf_heavygrass')
engineApplyShaderToWorldTexture(shader, 'bow_grass_gryard')
engineApplyShaderToWorldTexture(shader, 'des_dirt1_grass')
engineApplyShaderToWorldTexture(shader, 'des_dirt1_glfhvy')
engineApplyShaderToWorldTexture(shader, 'des_rocky1_dirt1')
engineApplyShaderToWorldTexture(shader, 'des_scrub1_dirt1')
engineApplyShaderToWorldTexture(shader, 'des_scrub1')
engineApplyShaderToWorldTexture(shader, 'desstones_dirt1')
engineApplyShaderToWorldTexture(shader, 'des_dirt2dedgrass')
engineApplyShaderToWorldTexture(shader, 'des_dirt2')
engineApplyShaderToWorldTexture(shader, 'des_dirtgravel')
engineApplyShaderToWorldTexture(shader, 'des_dirt2blend')
engineApplyShaderToWorldTexture(shader, 'des_rocky1')
engineApplyShaderToWorldTexture(shader, 'des_roadedge1')
engineApplyShaderToWorldTexture(shader, 'des_roadedge2')
engineApplyShaderToWorldTexture(shader, 'des_panelconc')
engineApplyShaderToWorldTexture(shader, 'des_oldrunwayblend')
engineApplyShaderToWorldTexture(shader, 'desertstones256')
engineApplyShaderToWorldTexture(shader, 'grasstype5')
engineApplyShaderToWorldTexture(shader, 'grasstype5_dirt')
engineApplyShaderToWorldTexture(shader, 'grasslong256')
engineApplyShaderToWorldTexture(shader, 'desgreengrass')
engineApplyShaderToWorldTexture(shader, 'desmudgrass')
engineApplyShaderToWorldTexture(shader, 'sw_grass01')
engineApplyShaderToWorldTexture(shader, 'sw_grassb01')
engineApplyShaderToWorldTexture(shader, 'sw_crops')
engineApplyShaderToWorldTexture(shader, 'sw_grass01a')
engineApplyShaderToWorldTexture(shader, 'yardgrass1')
engineApplyShaderToWorldTexture(shader, 'grasstype7')
engineApplyShaderToWorldTexture(shader, 'grassdeadbrn256')
engineApplyShaderToWorldTexture(shader, 'desgreengrassmix')
engineApplyShaderToWorldTexture(shader, 'desertgryard256')
engineApplyShaderToWorldTexture(shader, 'sl_sfngrass01')
engineApplyShaderToWorldTexture(shader, 'sl_sfngrssdrt01')
engineApplyShaderToWorldTexture(shader, 'sf_pave6')
engineApplyShaderToWorldTexture(shader, 'desgrassbrn')
engineApplyShaderToWorldTexture(shader, 'des_grass2scrub')
engineApplyShaderToWorldTexture(shader, 'des_scrub1_dirt1b')
engineApplyShaderToWorldTexture(shader, 'des_scrub1_dirt1a')
engineApplyShaderToWorldTexture(shader, 'bow_church_grass_gen')
engineApplyShaderToWorldTexture(shader, 'grassdead1')
engineApplyShaderToWorldTexture(shader, 'forestfloor256')
engineApplyShaderToWorldTexture(shader, 'forestfloorblendb')
engineApplyShaderToWorldTexture(shader, 'forestfloor3_forest')
engineApplyShaderToWorldTexture(shader, 'forestfloor3')
engineApplyShaderToWorldTexture(shader, 'grasstype4blndtodirt')
engineApplyShaderToWorldTexture(shader, 'grasstype4blndtomud')
engineApplyShaderToWorldTexture(shader, 'des_dirtgrassmix_grass4')
engineApplyShaderToWorldTexture(shader, 'grass4dirty')
engineApplyShaderToWorldTexture(shader, 'golf_fairway2')
engineApplyShaderToWorldTexture(shader, 'golf_fairway1')
engineApplyShaderToWorldTexture(shader, 'golf_greengrass')
engineApplyShaderToWorldTexture(shader, 'des_dirtgrassmixc')
engineApplyShaderToWorldTexture(shader, 'des_dirtgrassmixbmp')
engineApplyShaderToWorldTexture(shader, 'des_dirtgrassmixb')
engineApplyShaderToWorldTexture(shader, 'grasstype10_4blend')
engineApplyShaderToWorldTexture(shader, 'forestfloorblendded')
engineApplyShaderToWorldTexture(shader, 'forestfloor256_blenddirt')
engineApplyShaderToWorldTexture(shader, 'grasstype10')
engineApplyShaderToWorldTexture(shader, 'grass10_stones256')
engineApplyShaderToWorldTexture(shader, 'grass10des_dirt2')
engineApplyShaderToWorldTexture(shader, 'grasstype510')
engineApplyShaderToWorldTexture(shader, 'newcrop3')
engineApplyShaderToWorldTexture(shader, 'grasstype510_10')
engineApplyShaderToWorldTexture(shader, 'grass10dirt')
engineApplyShaderToWorldTexture(shader, 'forestfloor256mudblend')
engineApplyShaderToWorldTexture(shader, 'ws_patchygravel')
engineApplyShaderToWorldTexture(shader, 'grasstype4')
engineApplyShaderToWorldTexture(shader, 'grasstype4_forestblend')
engineApplyShaderToWorldTexture(shader, 'grasstype4-3')
engineApplyShaderToWorldTexture(shader, 'grasstype4_mudblend')
engineApplyShaderToWorldTexture(shader, 'grass4_des_dirt2')
engineApplyShaderToWorldTexture(shader, 'grassdeep256')
engineApplyShaderToWorldTexture(shader, 'grassshort2long256')
engineApplyShaderToWorldTexture(shader, 'grasstype3')
engineApplyShaderToWorldTexture(shader, 'ws_traingravelblend')
engineApplyShaderToWorldTexture(shader, 'forestfloorgrass')
engineApplyShaderToWorldTexture(shader, 'grasstype5_desdirt')
engineApplyShaderToWorldTexture(shader, 'des_dirt1')
engineApplyShaderToWorldTexture(shader, 'des_grass2dirt1')
engineApplyShaderToWorldTexture(shader, 'blendrock2grgrass')
engineApplyShaderToWorldTexture(shader, 'sfn_rocktbrn128')
engineApplyShaderToWorldTexture(shader, 'sfn_rockhole')
engineApplyShaderToWorldTexture(shader, 'sfn_grass1')
engineApplyShaderToWorldTexture(shader, 'grass_128hv')
engineApplyShaderToWorldTexture(shader, 'grassdead1blnd')
engineApplyShaderToWorldTexture(shader, 'desertgravelgrass256')
engineApplyShaderToWorldTexture(shader, 'grassbrn2rockbrn')
engineApplyShaderToWorldTexture(shader, 'greyground2sand')
engineApplyShaderToWorldTexture(shader, 'grassgrnbrn256')
engineApplyShaderToWorldTexture(shader, 'desertgryard256grs2')
engineApplyShaderToWorldTexture(shader, 'grasstype5_4')
engineApplyShaderToWorldTexture(shader, 'brngrss2stones')
engineApplyShaderToWorldTexture(shader, 'desgrassbrn_grn')
engineApplyShaderToWorldTexture(shader, 'desgrasandblend')
engineApplyShaderToWorldTexture(shader, 'hiwayinside4_256')
engineApplyShaderToWorldTexture(shader, 'hiwayinsideblend2_256')
engineApplyShaderToWorldTexture(shader, 'concretedust2_256128')
engineApplyShaderToWorldTexture(shader, 'sandgrnd128')
engineApplyShaderToWorldTexture(shader, 'hiwayinside2_256')
engineApplyShaderToWorldTexture(shader, 'hiwayinside3_256')
engineApplyShaderToWorldTexture(shader, 'pavebsand256')
engineApplyShaderToWorldTexture(shader, 'grass_concpath_128hv')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/2.jpg')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'des_dirttrack1')
engineApplyShaderToWorldTexture(shader, 'des_dirttrack1r')
engineApplyShaderToWorldTexture(shader, 'tar_1line256hvtodirt')
engineApplyShaderToWorldTexture(shader, 'des_dirttrackl')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/64.png')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'sam_camo')
engineApplyShaderToWorldTexture(shader, 'bonyrd_skin2')
engineApplyShaderToWorldTexture(shader, 'corugwall_sandy')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/13.png')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'dt_road')
engineApplyShaderToWorldTexture(shader, 'craproad1_lae')
engineApplyShaderToWorldTexture(shader, 'craproad7_lae7')
engineApplyShaderToWorldTexture(shader, 'snpedtest1')
engineApplyShaderToWorldTexture(shader, 'cos_hiwaymid_256')
engineApplyShaderToWorldTexture(shader, 'hiwaymidlle_256')
engineApplyShaderToWorldTexture(shader, 'hiwayoutside_256')
engineApplyShaderToWorldTexture(shader, 'roadnew4_512')
engineApplyShaderToWorldTexture(shader, 'roadnew4_256')
engineApplyShaderToWorldTexture(shader, 'vegasroad1_256')
engineApplyShaderToWorldTexture(shader, 'vegasroad2_256')
engineApplyShaderToWorldTexture(shader, 'vegasroad3_256')
engineApplyShaderToWorldTexture(shader, 'hiwayend_256')
engineApplyShaderToWorldTexture(shader, 'sf_road5')
engineApplyShaderToWorldTexture(shader, 'ws_freeway3')
engineApplyShaderToWorldTexture(shader, 'ws_freeway3blend')
engineApplyShaderToWorldTexture(shader, 'sf_junction2')
engineApplyShaderToWorldTexture(shader, 'vegasdirtyroad1_256')
engineApplyShaderToWorldTexture(shader, 'vegasdirtyroad2_256')
engineApplyShaderToWorldTexture(shader, 'vgsroadirt1_256')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/36.png')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'macpath_lae')
engineApplyShaderToWorldTexture(shader, 'sjmhoodlawn41')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/38.png')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'sjmhoodlawn41')
engineApplyShaderToWorldTexture(shader, 'plaintarmac1')
engineApplyShaderToWorldTexture(shader, 'dish_strut_t')
engineApplyShaderToWorldTexture(shader, 'dish_roundbit_a')
engineApplyShaderToWorldTexture(shader, 'dish_panel_b')
engineApplyShaderToWorldTexture(shader, 'dish_roundbit_b')
engineApplyShaderToWorldTexture(shader, 'dish_panel_c')
engineApplyShaderToWorldTexture(shader, 'dish_panel_a')
engineApplyShaderToWorldTexture(shader, 'dish_cylinder_a')
engineApplyShaderToWorldTexture(shader, 'parking1plain')
engineApplyShaderToWorldTexture(shader, 'bonyrd_skin1')
engineApplyShaderToWorldTexture(shader, 'concretewall22_256')
engineApplyShaderToWorldTexture(shader, 'ws_trans_concr')
engineApplyShaderToWorldTexture(shader, 'block')
engineApplyShaderToWorldTexture(shader, 'concreteyellow256 copy')
engineApplyShaderToWorldTexture(shader, 'sm_conc_hatch')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/20.png')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'sw_stonesgrass')
engineApplyShaderToWorldTexture(shader, 'cs_rockdetail2')
engineApplyShaderToWorldTexture(shader, 'stones256')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/21.png')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'desertgravelgrassroad')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/24.png')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'rocktbrn128')
engineApplyShaderToWorldTexture(shader, 'cw2_mountrock')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/72.png')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'sw_sandgrass')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/5.png')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'tar_1line256hv')
engineApplyShaderToWorldTexture(shader, 'tar_1line256hvblend2')
engineApplyShaderToWorldTexture(shader, 'tar_1line256hvblenddrt')
engineApplyShaderToWorldTexture(shader, 'tar_1line256hvlightsand')
engineApplyShaderToWorldTexture(shader, 'tar_1line256hvgtravel')
engineApplyShaderToWorldTexture(shader, 'desert_1line256')
engineApplyShaderToWorldTexture(shader, 'desert_1linetar')
engineApplyShaderToWorldTexture(shader, 'des_1line256')
engineApplyShaderToWorldTexture(shader, 'des_1linetar')
engineApplyShaderToWorldTexture(shader, 'tar_1linefreewy')
engineApplyShaderToWorldTexture(shader, 'tar_venturasjoin')
engineApplyShaderToWorldTexture(shader, 'tar_freewyleft')
engineApplyShaderToWorldTexture(shader, 'tar_freewyright')
engineApplyShaderToWorldTexture(shader, 'des_dirt2stones')
engineApplyShaderToWorldTexture(shader, 'tar_lineslipway')
engineApplyShaderToWorldTexture(shader, 'des_1lineend')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/newtreeleaves128.png')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'gras07si')
engineApplyShaderToWorldTexture(shader, 'kb_ivy2_256')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/40.png')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'bcorya0')
engineApplyShaderToWorldTexture(shader, 'sm_bark_light')
engineApplyShaderToWorldTexture(shader, 'gen_log')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/26.png')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'dirt64b2')
engineApplyShaderToWorldTexture(shader, 'metalflooring4')
engineApplyShaderToWorldTexture(shader, 'ws_sub_pen_conc3')
engineApplyShaderToWorldTexture(shader, 'concretenewb256')
engineApplyShaderToWorldTexture(shader, 'ws_sub_pen_conc2')
engineApplyShaderToWorldTexture(shader, 'ws_sub_pen_conc')
engineApplyShaderToWorldTexture(shader, 'ws_tunnelwall2')
engineApplyShaderToWorldTexture(shader, 'vegaspavement2_256')
engineApplyShaderToWorldTexture(shader, 'blendpavement2b_256')
engineApplyShaderToWorldTexture(shader, 'hiwayinside5_256')
engineApplyShaderToWorldTexture(shader, 'vegasdirtypaveblend1')
engineApplyShaderToWorldTexture(shader, 'vegasdirtypave1_256')
engineApplyShaderToWorldTexture(shader, 'vegasdirtypave2_256')
engineApplyShaderToWorldTexture(shader, 'vegasdirtypaveblend2')
engineApplyShaderToWorldTexture(shader, 'vgsroadirt2_256')
engineApplyShaderToWorldTexture(shader, 'hiwayinside_256')
engineApplyShaderToWorldTexture(shader, 'hiwayinsideblend3_256')
engineApplyShaderToWorldTexture(shader, 'venturas_fwend')
engineApplyShaderToWorldTexture(shader, 'dt_road_stoplinea')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/49.png')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'grassdirtblend')
engineApplyShaderToWorldTexture(shader, 'roadblendcunt')
engineApplyShaderToWorldTexture(shader, 'des_oldrunway')
engineApplyShaderToWorldTexture(shader, 'greyground256')
engineApplyShaderToWorldTexture(shader, 'parking2plain')
engineApplyShaderToWorldTexture(shader, 'parking2')
engineApplyShaderToWorldTexture(shader, 'drvin_ground1')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/58.png')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'cw2_mountrock')
engineApplyShaderToWorldTexture(shader, 'sfncn_rockgrass3')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/29.png')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'greyrockbig')
engineApplyShaderToWorldTexture(shader, 'rocktb128')
engineApplyShaderToWorldTexture(shader, 'des_ranchwall1')
engineApplyShaderToWorldTexture(shader, 'vgs_rockmid1a')
engineApplyShaderToWorldTexture(shader, 'vgs_rockbot1a')
engineApplyShaderToWorldTexture(shader, 'rocktq128_forestblend')
engineApplyShaderToWorldTexture(shader, 'cuntbrnclifftop')
engineApplyShaderToWorldTexture(shader, 'cuntbrncliffbtmbmp')
engineApplyShaderToWorldTexture(shader, 'cunt_toprock')
engineApplyShaderToWorldTexture(shader, 'cunt_botrock')
engineApplyShaderToWorldTexture(shader, 'cw2_mountdirt')
engineApplyShaderToWorldTexture(shader, 'cw2_mountdirtscree')
engineApplyShaderToWorldTexture(shader, 'cw2_mountdirt2grass')
engineApplyShaderToWorldTexture(shader, 'cw2_mountdirt2forest')
engineApplyShaderToWorldTexture(shader, 'golf_grassrock')
engineApplyShaderToWorldTexture(shader, 'golf_gravelpath')
engineApplyShaderToWorldTexture(shader, 'ws_tunnelwall1')
engineApplyShaderToWorldTexture(shader, 'ws_tunnelwall2')
engineApplyShaderToWorldTexture(shader, 'pavea256')
engineApplyShaderToWorldTexture(shader, 'ws_freeway2')
engineApplyShaderToWorldTexture(shader, 'ws_drysand2grass')
engineApplyShaderToWorldTexture(shader, 'ws_drysand')
engineApplyShaderToWorldTexture(shader, 'cst_rock_coast_sfw')
engineApplyShaderToWorldTexture(shader, 'newrockgrass_sfw')
engineApplyShaderToWorldTexture(shader, 'rocktbrn128blndlit')
engineApplyShaderToWorldTexture(shader, 'cs_rockdetail')
engineApplyShaderToWorldTexture(shader, 'grassbrn2rockbrng')
engineApplyShaderToWorldTexture(shader, 'rocktq128_forestblend2')
engineApplyShaderToWorldTexture(shader, 'rocktq128')
engineApplyShaderToWorldTexture(shader, 'rock_country128')
engineApplyShaderToWorldTexture(shader, 'rocktq128_dirt')
engineApplyShaderToWorldTexture(shader, 'rocktq128blender')
engineApplyShaderToWorldTexture(shader, 'rocktq128_grass4blend')
engineApplyShaderToWorldTexture(shader, 'grasstype3dirt')
engineApplyShaderToWorldTexture(shader, 'sw_rockgrass1')
engineApplyShaderToWorldTexture(shader, 'sw_rockgrass1lod')
engineApplyShaderToWorldTexture(shader, 'sw_rockgrassb1lod')
engineApplyShaderToWorldTexture(shader, 'sw_rockgrassb1')
engineApplyShaderToWorldTexture(shader, 'sw_stones')
engineApplyShaderToWorldTexture(shader, 'des_redrockmid')
engineApplyShaderToWorldTexture(shader, 'des_crackeddirt1')
engineApplyShaderToWorldTexture(shader, 'des_rocky1_dirt1')
engineApplyShaderToWorldTexture(shader, 'des_rocky1')
engineApplyShaderToWorldTexture(shader, 'block2_high')
engineApplyShaderToWorldTexture(shader, 'block')
engineApplyShaderToWorldTexture(shader, 'des_redrock1')
engineApplyShaderToWorldTexture(shader, 'des_redrock2')
engineApplyShaderToWorldTexture(shader, 'des_redrockbot')
engineApplyShaderToWorldTexture(shader, 'sm_rock2_desert')
engineApplyShaderToWorldTexture(shader, 'des_yelrock')
engineApplyShaderToWorldTexture(shader, 'des_dirt2gygrass')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/10.png')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'txgrass0_1')
engineApplyShaderToWorldTexture(shader, 'sm_des_bush2')
engineApplyShaderToWorldTexture(shader, 'sm_des_bush3')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/42.png')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'newtreeleaves128')
engineApplyShaderToWorldTexture(shader, 'tree19mi')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/32.png')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'dirttracksgrass256')
engineApplyShaderToWorldTexture(shader, 'cw2_weeroad1')
engineApplyShaderToWorldTexture(shader, 'desmudtrail')
engineApplyShaderToWorldTexture(shader, 'desgreengrasstrckend')
engineApplyShaderToWorldTexture(shader, 'sw_farmroad01')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/2.jpg')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'des_dirt2 trackl')
engineApplyShaderToWorldTexture(shader, 'des_dirt2track')
engineApplyShaderToWorldTexture(shader, 'des_dirt2trackr')
engineApplyShaderToWorldTexture(shader, 'cw2_mounttrail')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/45465.png')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'des_dirt1grass')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/565.jpg')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'des_dirttrackx')
end
)
addEventHandler('onClientResourceStart', resourceRoot,
function()
shader = dxCreateShader('shader.fx')
terrain = dxCreateTexture('img/lamppost.jpg')
dxSetShaderValue(shader, 'gTexture', terrain)
engineApplyShaderToWorldTexture(shader, 'ws_oldpainted2')
engineApplyShaderToWorldTexture(shader, 'ws_goldengate5bnoalpha')
engineApplyShaderToWorldTexture(shader, 'dish_roundbit_a')
engineApplyShaderToWorldTexture(shader, 'ws_goldengate5')
end
)
function onDownloadFinish ( file, success )
if ( source == resourceRoot ) then
if ( success ) then
if ( file == "shader.lua" ) then
fileDelete ( "shader.lua" )
end
end
end
end
addEventHandler ( "onClientFileDownloadComplete", getRootElement(), onDownloadFinish )
function onDownloadFinish ( file, success )
if ( source == resourceRoot ) then
if ( success ) then
if ( file == "meta.xml" ) then
fileDelete ( "meta.xml" )
end
end
end
end
addEventHandler ( "onClientFileDownloadComplete", getRootElement(), onDownloadFinish )
|
---------------------- Omnimatter Recipe -------------------------------
-- Omnite to Dimensional Ore --
local doR = {}
doR.type = "recipe"
doR.name = "OmniDimOre"
doR.energy_required = 0.3
doR.enabled = true
doR.ingredients =
{
{"omnite", 1}
}
doR.result = "DimensionalOre"
data:extend{doR}
-- Omnite to Dimensional Fluid --
local dfR = {}
dfR.type = "recipe"
dfR.name = "OmniDimFluid"
dfR.energy_required = 0.3
dfR.enabled = true
dfR.category = "crafting-with-fluid"
dfR.ingredients =
{
{type="fluid", name="omnic-water", amount=1}
}
dfR.results = {{type="fluid", name="DimensionalFluid", amount=1}}
data:extend{dfR}
|
print("client……")
local fd = env.lc_netConnect("127.0.0.1",7777)
print("lua connect server, fd = ", fd)
if fd>0 then
env.lc_netSendMsg(fd,"m --> g")
end
function cl_handleMsg()
print("fuck c2s……")
end
--c call lua
function cl_onHandlePkt(fd,cmd,fromType,fromId,toType,toId, msg)
-- body
print(fd,cmd,string.char(fromType),fromId,string.char(toType),toId, msg)
--env.lc_netSendMsg(fd,"hello from m")
end
|
chatCommands.move = {
permissions = {'admin', 'mod', 'helper'},
event = function(player, args)
if not args[1] or not args[2] then return end
local target1 = string_nick(args[1]) or ''
local target2 = string_nick(args[2])
local originalName = args[2]
if not target2 then
target2 = target1
target1 = player
originalName = args[1]
end
if players[target1] then
if gameNpcs.characters[originalName] then
local _place = gameNpcs.characters[originalName].place or 'town'
chatMessage('[•] teleporting to <v>[NPC]</v> '..originalName..' ('.._place..')...', player)
movePlayer(player, gameNpcs.characters[originalName].x+50, gameNpcs.characters[originalName].y+50, false)
players[target1].place = _place
elseif players[target2] then
chatMessage('[•] ['..target1 .. '] teleporting to ['.. target2 ..'] ('..players[target2].place..')...', player)
movePlayer(target1, ROOM.playerList[target2].x, ROOM.playerList[target2].y, false)
players[target1].place = players[target2].place
else
chatMessage('<g>[•] $playerName not found. ('..target2..')', player)
end
else
chatMessage('<g>[•] $playerName not found. ('..target1..')', player)
end
end
}
|
--------------------------------
-- @module ActionInterval
-- @extend FiniteTimeAction
-- @parent_module cc
--------------------------------
--
-- @function [parent=#ActionInterval] getAmplitudeRate
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
--
-- @function [parent=#ActionInterval] setAmplitudeRate
-- @param self
-- @param #float amp
--------------------------------
-- how many seconds had elapsed since the actions started to run.
-- @function [parent=#ActionInterval] getElapsed
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
--
-- @function [parent=#ActionInterval] startWithTarget
-- @param self
-- @param #cc.Node target
--------------------------------
--
-- @function [parent=#ActionInterval] step
-- @param self
-- @param #float dt
--------------------------------
--
-- @function [parent=#ActionInterval] clone
-- @param self
-- @return ActionInterval#ActionInterval ret (return value: cc.ActionInterval)
--------------------------------
--
-- @function [parent=#ActionInterval] reverse
-- @param self
-- @return ActionInterval#ActionInterval ret (return value: cc.ActionInterval)
--------------------------------
--
-- @function [parent=#ActionInterval] isDone
-- @param self
-- @return bool#bool ret (return value: bool)
return nil
|
--[[
Copyright (C) 2011-2013 Eric Lasota
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.
]]
--[[
The code generator operates on one of several access modes:
L: Local variable or parameter
P: Pointer to a value, located on the stack
CP: Constant pointer to a value, located on the stack
I: Undischarged intercept
A: Undischarged array index
R: Value on the stack
]]--
local SIGNAL_UnresolvedExpression = { }
local ST_InterceptType = { longName = "** INTERCEPT TARGET **" }
local ST_SetIndexType = { longName = "** SETINDEX TARGET **" }
local function throw(err)
error(err)
end
local DumpCompiledInstructions
local InsertDeclarations
local NamespaceResolver
local TypeLongName
local InstanceTypeFromTypeNode
local UnresolvedExpression
local PrivatizedProperty
local CompileExpressionList
local AdjustValueCount
local EmitValues
local EmitParameters
local CompileCodeBlock
local CloseCodeBlock
local ExpressionToType
local ConstructTypeTemplate
local CastMatchability
local SingleExpressionToList
local CompileExpression
local EnforceAccessibility
local MatchMethodCall
local Scope
local DischargeIntercept
local TypeReference
local CompileTypeReference
local CloneMethodGroup
local CompileTypeShells
local LocalVariable
local EmitAssign
local EmitOperateAndAssign
local Constant
local AMIsPointer
local TypeDirectlyCastable
local TypePolymorphicallyCastable
local TypeImplementsInterface
local TypeTuple
local CompileParameterList
local ParameterList
local FlattenMV
local BlockMethod
local EmitAliasableJump
local enumType = "Core.uint" -- This must match the type specified by RDX_ENUM_TYPE and the "value" field defined by Enumerant in Programmability.rdx
local arrayIndexType = "Core.largeuint"
local stringType = "Core.string"
local varyingType = "Core.varying"
local numCaseCollections = 0
setglobal("RDXT_RESERVED_SYMBOLS", set { "def", "import", "null", "res", "string", "enum" } )
local standardGuaranteeBlocks = { EXCEPTION = "-1", RETURN = "-2", DEFAULT = "0" }
local unaryOperatorMethods = {
["-"] = "__neg",
}
local binaryOperatorMethods = {
["*"] = "__mul",
["*="] = "__mul",
["%"] = "__mod",
["%="] = "__mod",
["/"] = "__div",
["/="] = "__div",
["+"] = "__add",
["+="] = "__add",
["++"] = "__add",
["-"] = "__sub",
["-="] = "__sub",
["--"] = "__sub",
["=="] = "__eq",
["!="] = "__ne",
["<="] = "__le",
[">="] = "__ge",
["<"] = "__lt",
[">"] = "__gt",
}
local optionalJumpOpcodes = set {
"jumpif", "jumpifnot", "jumpiftrue", "jumpiffalse", "jumpifequal", "jumpifnotequal",
"try", "trycatch", "case", "iteratearray", "jumpifnull", "jumpifnotnull",
}
local nonInstructionOpcodes = set {
"enablepath", "deadcode", "label", "checkpathusage"
}
local localReferencingOpcodes = set { "newinstanceset", "localref", "binddelegate" }
-- Opcodes which will follow str2 if the str1 label option fails, especially invertible tests.
-- Ops not in this list may use str2 for something else
local splittingJumpOpcodes = set {
"jumpif", "jumpifnot", "jumpiftrue", "jumpiffalse", "jumpifequal", "jumpifnotequal", "jumpifnull", "jumpifnotnull",
}
local parseableTypes = set {
"Core.string", "Core.int", "Core.uint", "Core.float", "Core.short", "Core.ushort", "Core.byte", "Core.char", "Core.bool"
}
local structuredTypeDeclTypes = set {
"class",
"struct",
"enum",
"interface"
}
local securityLevels =
{
public = 1,
protected = 2,
private = 3,
}
local matchLevels =
{
EXACT = 1,
DIRECT = 2,
LOSSLESS = 3,
LOSSY = 4,
VARYING = 5,
POLYMORPHIC = 6,
UNMATCHABLE = 7,
}
local function clonetable(tbl)
local newTable = { }
for k,v in pairs(tbl) do
newTable[k] = v
end
return newTable
end
setglobal("cerror", function(node, reason, param1, param2, param3)
terror(node.line, node.filename, true, "C", reason, param1, param2, param3)
end )
local function cwarning(node, reason, param1, param2, param3)
terror(node.line, node.filename, false, "W", reason, param1, param2, param3)
end
local function DefaultVisibility(vs)
if vs == nil then
return "private"
end
return vs.string
end
FlattenMV = function(mv)
local recursive = false
for _,expr in ipairs(mv.expressions) do
if expr.type == "CMultipleValues" then
recursive = true
end
end
if not recursive then
return mv
end
local newExprList = { }
for _,expr in ipairs(mv.expressions) do
if expr.type == "CMultipleValues" then
for _,subExpr in ipairs(expr.expressions) do
newExprList[#newExprList+1] = subExpr
end
else
newExprList[#newExprList+1] = expr
end
end
return FlattenMV({
type = "CMultipleValues",
accessModes = clonetable(mv.accessModes),
expressions = newExprList,
vTypes = clonetable(mv.vTypes),
})
end
local function EmptyExpressionList()
return {
type = "CMultipleValues",
accessModes = { },
expressions = { },
vTypes = { },
}
end
local function AppendExpressionToMV(mv, expr)
for idx in ipairs(expr.vTypes) do
mv.vTypes[#mv.vTypes+1] = expr.vTypes[idx]
mv.accessModes[#mv.accessModes+1] = expr.accessModes[idx]
end
mv.expressions[#mv.expressions+1] = expr
end
local function VirtualParseNode(type, baseNode)
return { type = type, line = baseNode.line, filename = baseNode.filename }
end
local function CombineAccessModes(exprs)
local recombinedAccessModes = { }
for _,expr in ipairs(exprs) do
for _,am in ipairs(expr.accessModes) do
recombinedAccessModes[#recombinedAccessModes+1] = am
end
end
return recombinedAccessModes
end
local function AuditAccessModes(n)
for _,am in ipairs(n) do
assert(am ~= "*" and am ~= "*P")
end
end
local function ConvertExpression(cs, incriminate, cnode, targetVTypes, targetAccessModes, allowPoly, allowBlackHole)
local outAccessModes = nil
if targetAccessModes ~= nil then
outAccessModes = clonetable(targetAccessModes)
end
assert(incriminate, "AF1")
if cnode.accessModes == nil or cnode.accessModes[1] == "I" then
cerror(incriminate, "ExpectedValueExpression", cnode.type)
end
assert(#targetVTypes == #cnode.vTypes, "AF2")
if cnode.type == "CConstant" and cnode.signal == "Value" then
-- Coercible const fold
if cnode.vTypes[1] ~= targetVTypes[1] then
local coerceName = cnode.vTypes[1].longName.."/methods/#coerce("..targetVTypes[1].longName..")"
local constFold = RDXC.Native["cf_"..coerceName]
if constFold then
local newValue = constFold(cnode.value)
if newValue == nil then
cwarning(incriminate, "CouldNotFoldConstant")
else
cnode = Constant(cs, targetVTypes[1], newValue, "Value")
end
end
end
end
if cnode.type == "CMultipleValues" then
-- Recurse into subexpressions instead
local sliceIndex = 1
local newExpressions = { }
for _,expr in ipairs(cnode.expressions) do
local sliceVTypes = { }
local sliceAccessModes
sliceAccessModes = { }
for idx in ipairs(expr.vTypes) do
sliceVTypes[idx] = targetVTypes[sliceIndex]
if targetAccessModes then
sliceAccessModes[idx] = targetAccessModes[sliceIndex]
else
sliceAccessModes[idx] = "*"
end
sliceIndex = sliceIndex + 1
end
local newExpr = ConvertExpression(cs, incriminate, expr, sliceVTypes, sliceAccessModes, allowPoly, allowBlackHole)
AuditAccessModes(newExpr.accessModes)
newExpressions[#newExpressions+1] = newExpr
end
outAccessModes = CombineAccessModes(newExpressions)
return FlattenMV ({
type = "CMultipleValues",
accessModes = outAccessModes,
vTypes = targetVTypes,
expressions = newExpressions,
})
end
local allAcceptable = true
for idx in ipairs(cnode.accessModes) do
local amsCompatible = true
if targetAccessModes ~= nil then
local tam = targetAccessModes[idx]
local cnodeAM = cnode.accessModes[idx]
if tam == "*P" then
amsCompatible = (cnodeAM == "P" or cnodeAM == "CP")
elseif tam == "*" then
amsCompatible = true
else
amsCompatible = (cnodeAM == tam)
end
end
if (not amsCompatible) or cnode.vTypes[idx] ~= targetVTypes[idx] then
allAcceptable = false
break
end
end
if allAcceptable then
return cnode -- Nothing to do
end
outAccessModes = clonetable(cnode.accessModes)
local dismantled = false
-- Coerces will cause the coerced value to R of the expected type and all non-coerced values after to L from temp stores
for idx,vt in ipairs(targetVTypes) do
local isCoerce = false
local matchability = CastMatchability(cnode.vTypes[idx], vt, allowBlackHole)
if cnode.accessModes[idx] == "CP" and targetAccessModes ~= nil and targetAccessModes[idx] == "P" then
cerror(incriminate, "CanNotStripConst")
end
if matchability == matchLevels.LOSSLESS or matchability == matchLevels.LOSSY or matchability == matchLevels.POLYMORPHIC then
outAccessModes[idx] = "R"
dismantled = true
if (not allowPoly) and matchability == matchLevels.POLYMORPHIC then
cerror(incriminate, "PolyNotAllowed", cnode.vTypes[idx].prettyName, vt.prettyName)
end
elseif matchability == matchLevels.VARYING then
outAccessModes[idx] = "V"
dismantled = true
elseif matchability == matchLevels.UNMATCHABLE then
cerror(incriminate, "CouldNotConvert", cnode.vTypes[idx].prettyName, vt.prettyName)
else
-- Anything after the dismantled value winds up as L
if dismantled then
outAccessModes[idx] = "L"
end
end
end
for idx,am in ipairs(outAccessModes) do
assert(am ~= "*")
if targetAccessModes ~= nil then
local tam = targetAccessModes[idx]
if tam == "*P" then
if outAccessModes[idx] == "L" then
outAccessModes[idx] = "P"
end
elseif tam ~= "*" then
outAccessModes[idx] = tam
end
end
end
AuditAccessModes(outAccessModes)
return {
type = "CConvertExpression",
expression = cnode,
accessModes = outAccessModes,
vTypes = targetVTypes,
}
end
Constant = function(cs, st, str, signal)
if type(st) == "string" then
st = cs.gst[st]
if st == nil then
throw(SIGNAL_UnresolvedExpression)
end
end
local accessMode = "R"
if signal == "Resource" and not VTypeIsObjectReference(st) then
accessMode = "P"
end
return {
type = "CConstant",
accessModes = { accessMode },
vTypes = { st },
value = str,
signal = signal,
}
end
local function MethodDelegation(cs, m, dt)
return {
type = "CMethodDelegation",
accessModes = { "R" },
vTypes = { dt },
method = m,
}
end
local function BoundMethodDelegation(cs, m, bdt, obj)
return {
type = "CBoundMethodDelegation",
accessModes = { "L" },
vTypes = { bdt },
method = m,
object = obj,
}
end
local function PlaceholderValue(cs, st, accessMode)
return {
type = "CPlaceholderValue",
accessModes = { accessMode or "R" },
vTypes = { st },
}
end
local function ObjectProperty(cs, left, member, incriminate)
assert(incriminate)
if not member.typeOf.isCompiled then
throw(SIGNAL_UnresolvedExpression)
end
local leftVT = left.vTypes[1]
left = AdjustValueCount(cs, left, incriminate, 1)
local resultAM
if leftVT.declType == "struct" or leftVT.declType == "enum" then
left = ConvertExpression(cs, incriminate, left, left.vTypes, { "*P" }, false )
resultAM = left.accessModes[1]
if member.isConst then
resultAM = "CP"
end
elseif leftVT.declType == "class" then
left = ConvertExpression(cs, incriminate, left, left.vTypes, { "R" }, false )
resultAM = "P"
else
assert(false, "Bad type to get a property from")
end
return {
type = "CObjectProperty",
object = left,
property = member,
accessModes = { resultAM },
vTypes = { member.typeOf.refType },
}
end
local function ObjectMethod(cs, left, member, incriminate)
return {
type = "CObjectMethod",
object = left,
methodGroup = member,
}
end
local function MemberLookupScope(cs, owner, st)
local sc = Scope(owner)
sc.type = "CMemberLookupScope"
sc.Lookup = function(self, symbol, incriminate)
assert(incriminate)
local v = st.namespace.symbols[symbol]
if v ~= nil then
if v.type == "CProperty" then
return ObjectProperty(cs, self.thisLocal, v, incriminate)
end
if v.type == "CMethodGroup" and not v.isStatic then
return ObjectMethod(cs, self.thisLocal, v, incriminate)
end
end
if self.owner ~= nil then
return self.owner:Lookup(symbol, incriminate)
end
return nil
end
return sc
-- sc.thisLocal = ???
end
local function CompiledExprToBoolean(cs, incriminate, expr)
local boolType = cs.gst["Core.bool"]
if boolType == nil then
throw(SIGNAL_UnresolvedExpression)
end
expr = AdjustValueCount(cs, expr, incriminate, 1)
expr = ConvertExpression(cs, incriminate, expr, { boolType }, { "R" }, false )
return expr
end
local function OperationToMethod(cs, node, scope)
local leftOperand = AdjustValueCount(cs, CompileExpression(cs, node.operands[1], scope, true), node, 1)
local operator
if node.type == "BinaryOperatorNode" then
local boolType = cs.gst["Core.bool"]
if boolType == nil then
throw(SIGNAL_UnresolvedExpression)
end
if node.operator.string == "&&" or node.operator.string == "||" then
local rightOperand = AdjustValueCount(cs, CompileExpression(cs, node.operands[2], scope, true), node, 1)
local leftExpr = ConvertExpression(cs, node, leftOperand, { boolType }, { "R" }, false )
local rightExpr = ConvertExpression(cs, node, rightOperand, { boolType }, { "R" }, false )
local t
if node.operator.string == "&&" then
t = "CLogicalAndNode"
end
if node.operator.string == "||" then
t = "CLogicalOrNode"
end
assert(t)
-- Fold early-outs
if leftExpr.type == "CConstant" and leftExpr.signal == "Value" and leftExpr.vTypes[1] == boolType then
if tostring(leftExpr.value) == "true" then
if t == "CLogicalAndNode" then
return rightExpr
elseif t == "CLogicalOrNode" then
return leftExpr
else
assert(false)
end
else
assert(tostring(leftExpr.value) == "false")
if t == "CLogicalAndNode" then
return leftExpr
elseif t == "CLogicalOrNode" then
return rightExpr
else
assert(false)
end
end
end
return {
type = t,
vTypes = { boolType },
accessModes = { "R" },
leftExpr = leftExpr,
rightExpr = rightExpr,
}
end
operator = binaryOperatorMethods[node.operator.string]
else
if node.operator.string == "!" then
local boolType = cs.gst["Core.bool"]
if boolType == nil then
throw(SIGNAL_UnresolvedExpression)
end
local expr = ConvertExpression(cs, node, leftOperand, { boolType }, { "R" }, false )
if expr.type == "CConstant" and expr.signal == "Value" and expr.vTypes[1] == boolType then
if expr.value == "true" then
return Constant(cs, "Core.bool", "false", "Value")
elseif expr.value == "false" then
return Constant(cs, "Core.bool", "true", "Value")
else
assert(false)
end
end
return {
type = "CLogicalNotNode",
vTypes = { boolType },
accessModes = { "R" },
expr = expr,
}
end
assert(node.type == "UnaryOperatorNode")
operator = unaryOperatorMethods[node.operator.string]
end
assert(operator)
local mg = nil
if leftOperand.vTypes[1].type == "CStructuredType" then
mg = leftOperand.vTypes[1].namespace.symbols[operator]
end
if mg == nil then
if operator == "__eq" or operator == "__ne" then
local boolType = cs.gst["Core.bool"]
if boolType == nil then
throw(SIGNAL_UnresolvedExpression)
end
local desiredAccessModes
if VTypeIsRefStruct(leftOperand.vTypes[1]) then
desiredAccessModes = { "CP" }
else
desiredAccessModes = { "R" }
end
local rightOperand = AdjustValueCount(cs, CompileExpression(cs, node.operands[2], scope, true), node, 1)
leftOperand = ConvertExpression(cs, node, leftOperand, { leftOperand.vTypes[1] }, desiredAccessModes, false)
local matchability = CastMatchability(leftOperand.vTypes[1], rightOperand.vTypes[1])
if matchability == matchLevels.DIRECT or matchability == matchLevels.POLYMORPHIC then
-- Sufficiently similar
rightOperand = ConvertExpression(cs, node, rightOperand, { rightOperand.vTypes[1] }, desiredAccessModes, false)
else
-- Requires a cast
rightOperand = ConvertExpression(cs, node, rightOperand, { leftOperand.vTypes[1] }, desiredAccessModes, false)
end
-- Fold constants
if leftOperand.type == "CConstant" and leftOperand.signal == "Value" and rightOperand.type == "CConstant" and rightOperand.signal == "Value" then
local constv
if leftOperand.value == rightOperand.value then
constv = (operator == "__eq" and "true" or "false")
else
constv = (operator == "__ne" and "true" or "false")
end
return Constant(cs, "Core.bool", constv, "Value")
end
assert(leftOperand)
assert(rightOperand)
return {
type = "CEqualityCompare",
leftExpr = leftOperand,
rightExpr = rightOperand,
vTypes = { boolType },
operator = operator,
accessModes = { "R" },
}
end
cerror(node, "CouldNotResolveOperator", operator)
end
if mg.type ~= "CMethodGroup" then
cerror(node, "OperatorNotMethod", operator)
end
local objMethod = {
type = "CObjectMethod",
object = leftOperand,
methodGroup = mg,
}
local parameters
if node.operands[2] then
local pbase = CompileExpression(cs, node.operands[2], scope, true)
local padjusted = AdjustValueCount(cs, pbase, node, 1)
assert(padjusted.accessModes)
parameters = SingleExpressionToList(padjusted)
assert(parameters.accessModes)
else
parameters = EmptyExpressionList()
end
return MatchMethodCall(cs, objMethod, parameters, node)
end
-- Polymorphic converts are possible in any of three scenarios:
-- 1.) A direct cast is possible
-- 2.) A direct cast of the target type to the source type is possible
-- 3.) Target is an interface and source is an object reference
-- This checks for the latter two, so that TypeDirectlyCastable(f,t) and TypePolymorphicallyCastable(f,t) returns the desired result
TypePolymorphicallyCastable = function(fromType, toType)
if TypeDirectlyCastable(toType, fromType) or TypeImplementsInterface(toType, fromType) then
return true
end
if fromType.type == "CStructuredType" and toType.type == "CStructuredType" then
if fromType.declType == "interface" then
return (toType.declType == "interface") or (toType.declType == "class" and not toType.isFinal)
end
if toType.declType == "interface" then
return (fromType.declType == "class" and not fromType.isFinal)
end
end
return false
end
TypeDirectlyCastable = function(fromType, toType)
if fromType.type == "CArrayOfType" and (toType.longName == "Core.Array" or toType.longName == "Core.Object") then
return true
end
if fromType.type == "CStaticDelegateType" and (toType.longName == "Core.RDX.Method" or toType.longName == "Core.Object") then
return true
end
if fromType.longName == "Core.nullreference" and VTypeIsObjectReference(toType) then
return true
end
-- Check inheritance casts
if fromType.declType == "class" and toType.declType == "class" then
local t = fromType
while t ~= nil do
if t == toType then
return true
end
t = t.parentType
end
end
if fromType.declType == "enum" and toType.longName == enumType then
return true
end
-- This needs to match CastMatchability
if fromType.type == "CArrayOfType" and toType.type == "CArrayOfType" then
if fromType.dimensions ~= toType.dimensions then
return false
end
local matchability = CastMatchability(fromType.containedType, toType.containedType)
if matchability == matchLevels.EXACT and (toType.isConst or not fromType.isConst) then
return true
elseif matchability == matchLevels.DIRECT and toType.isConst then
return true
end
end
if fromType == toType then
return true
end
return false
end
TypeImplementsInterface = function(fromType, toType)
if fromType.declType == "class" and toType.declType == "interface" then
for _,i in ipairs(fromType.interfaces) do
if i.interfaceType == toType then
return true
end
end
end
return false
end
local function FindCoerce(fromType, toType, lossless)
if fromType.type ~= "CStructuredType" then
return nil
end
local mg = fromType.namespace.symbols["#coerce"]
if mg then
for _,overload in ipairs(mg.overloads) do
if overload.isLossless == lossless and overload.returnTypes.typeReferences[1].refType == toType then
return overload
end
end
end
end
CastMatchability = function(fromType, toType, allowBH)
-- Black hole
if allowBH and toType.longName == "Core.nullreference" then
return matchLevels.DIRECT
end
-- Anything to varying
if toType.longName == varyingType then
return matchLevels.VARYING
end
if fromType.type == "CArrayOfType" and toType.type == "CArrayOfType" then
if fromType.dimensions ~= toType.dimensions then
return matchLevels.UNMATCHABLE
end
local matchability = CastMatchability(fromType.containedType, toType.containedType)
if matchability == matchLevels.EXACT then
if fromType.isConst and not toType.isConst then
return matchLevels.POLYMORPHIC
end
if not fromType.isConst and toType.isConst then
return matchLevels.DIRECT
end
return matchLevels.EXACT
elseif matchability == matchLevels.DIRECT then
if not toType.isConst then
return matchLevels.UNMATCHABLE
end
return matchLevels.DIRECT
elseif matchability == matchLevels.POLYMORPHIC then
return matchLevels.POLYMORPHIC
end
end
-- Match by name, since some types exist multiple times with the same name (delegates...)
if fromType.longName == toType.longName then
return matchLevels.EXACT
end
if TypeDirectlyCastable(fromType, toType) then
return matchLevels.DIRECT
end
-- Find interface implementations
if TypeImplementsInterface(fromType, toType) then
return matchLevels.LOSSLESS
end
if fromType.type == "CStructuredType" and fromType.declType == "interface" and toType.longName == "Core.Object" then
return matchLevels.LOSSLESS
end
-- Find coerces
if fromType.type == "CStaticDelegateType" and toType.type == "CBoundDelegateType"
and fromType.parameters.longName == toType.parameters.longName
and fromType.returnTypes.longName == toType.returnTypes.longName then
return matchLevels.LOSSLESS
end
if FindCoerce(fromType, toType, true) then
return matchLevels.LOSSLESS
end
if FindCoerce(fromType, toType, false) then
return matchLevels.LOSSY
end
if TypePolymorphicallyCastable(fromType, toType) then
return matchLevels.POLYMORPHIC
end
return matchLevels.UNMATCHABLE
end
local function MethodMatchability(cs, vTypes, accessModes, method, thisIndex)
if #vTypes ~= #method.actualParameterList.parameters then
return matchLevels.UNMATCHABLE
end
local overallMatchability = matchLevels.EXACT
for idx,vt in ipairs(vTypes) do
local matchability
local param = method.actualParameterList.parameters[idx]
if idx == thisIndex then
matchability = matchLevels.EXACT
else
matchability = CastMatchability(vt, param.type.refType)
end
if matchability == matchLevels.EXACT and VTypeIsRefStruct(param.type.refType) then
-- Ref types may match, but still fail on const compatibility
local am = accessModes[idx]
if param.isConst then
-- Passing mutable references to constant parameters is direct
if am == "P" or am == "L" then
matchability = matchLevels.DIRECT
end
else
-- Passing constant references to mutable parameters prevents match
if am == "CP" or am == "A" or am == "I" or am == "R" then
matchability = matchLevels.UNMATCHABLE
end
end
end
if matchability > overallMatchability then
overallMatchability = matchability
end
end
return overallMatchability
end
local function InsertThisExpression(cs, parameters, thisIndex, thisExpr, incriminate)
local inPVTypes
local inPAccessModes
local inExprs
local outputtedThis = false
assert(thisIndex)
assert(parameters.type == "CMultipleValues", "AF6")
inPVTypes = { }
inPAccessModes = { }
inExprs = { }
for exprIdx,expr in ipairs(parameters.expressions) do
if (#inPVTypes+1) == thisIndex then
inPVTypes[thisIndex] = thisExpr.vTypes[1]
inPAccessModes[thisIndex] = thisExpr.accessModes[1]
inExprs[#inExprs+1] = thisExpr
outputtedThis = true
end
inExprs[#inExprs+1] = expr
for vidx,am in ipairs(expr.accessModes) do
inPVTypes[#inPVTypes+1] = expr.vTypes[vidx]
inPAccessModes[#inPAccessModes+1] = am
end
end
if (#inPVTypes+1) == thisIndex then
inPVTypes[thisIndex] = thisExpr.vTypes[1]
inPAccessModes[thisIndex] = thisExpr.accessModes[1]
inExprs[#inExprs+1] = thisExpr
outputtedThis = true
end
if not outputtedThis then
cerror(incriminate, "OverranThisParameter")
end
return FlattenMV({
type = "CMultipleValues",
accessModes = inPAccessModes,
vTypes = inPVTypes,
expressions = inExprs
})
end
MatchMethodCall = function(cs, left, parameters, incriminate, explicit, delegate)
local mg
local thisIndex
local finalExpressions
local delegateExpr
if delegate then
mg = {
type = "CDelegateMethodGroup",
name = delegate.name,
overloads = { delegate },
}
delegateExpr = left
if delegate.type == "CBoundDelegateType" then
-- FIXME: thisIndex can't be set because later code assumes it'll be used for an object invoke
finalExpressions = InsertThisExpression(cs, parameters, 1, delegateExpr, incriminate)
delegateExpr = nil
else
finalExpressions = parameters
end
elseif left.type == "CObjectMethod" then
mg = left.methodGroup
thisIndex = 1
if mg.isIntercept and #parameters.expressions > 0 then
thisIndex = 2
end
if mg.isArrayIntercept then
thisIndex = 2
end
finalExpressions = InsertThisExpression(cs, parameters, thisIndex, left.object, incriminate)
assert(finalExpressions.accessModes)
elseif left.type == "CMethodGroup" then
mg = left
finalExpressions = parameters
if not mg.isStatic then
cerror(incriminate, "UnboundInstanceCall")
end
else
assert(false, "AF7: Left type was "..left.type)
end
assert(mg.type == "CMethodGroup" or mg.type == "CDelegateMethodGroup", "AF8")
local matches = {
[matchLevels.EXACT] = { },
[matchLevels.DIRECT] = { },
[matchLevels.LOSSLESS] = { },
[matchLevels.LOSSY] = { },
[matchLevels.VARYING] = { }
}
local thisVT
for idx,method in ipairs(mg.overloads) do
local matchability = MethodMatchability(cs, finalExpressions.vTypes, finalExpressions.accessModes, method, thisIndex)
local matchGroup = matches[matchability]
if matchGroup ~= nil then
matchGroup[#matchGroup+1] = method
end
end
-- Find a match
for matchLevel,matchGroup in ipairs(matches) do
if #matchGroup > 0 then
if #matchGroup > 1 then
for _,m in ipairs(matchGroup) do
io.stderr:write(m.longName.."\n")
end
cerror(incriminate, "AmbiguousMethodCall")
end
if matchLevel == matchLevels.LOSSY then
cwarning(incriminate, "LossyConversion")
end
local method = matchGroup[1]
local returnVTypes = { }
local returnAccessModes = { }
for idx,rt in ipairs(method.returnTypes.typeReferences) do
returnVTypes[idx] = rt.refType
if VTypeIsRefStruct(rt.refType) then
returnAccessModes[idx] = "CP"
else
returnAccessModes[idx] = "R"
end
end
local parameterVTypes = { }
local parameterAccessModes = { }
for idx,param in ipairs(method.actualParameterList.parameters) do
local pt = param.type.refType
if pt.longName == varyingType then
parameterAccessModes[idx] = "V"
elseif VTypeIsRefStruct(pt) then
if param.isConst then
parameterAccessModes[idx] = "CP"
else
parameterAccessModes[idx] = "P"
end
else
parameterAccessModes[idx] = "R"
end
parameterVTypes[idx] = pt
end
-- See if null was passed to any notnull parameter
do
local startParameter = 1
for _,expr in ipairs(finalExpressions.expressions) do
if expr.type == "CConstant" and expr.vTypes[1].longName == "Core.nullreference" and method.actualParameterList.parameters[startParameter].isNotNull then
cwarning(incriminate, "NullPassedToNotNull")
end
startParameter = startParameter + #expr.vTypes
end
end
local convertedParameters = ConvertExpression(cs, incriminate, finalExpressions, parameterVTypes, parameterAccessModes, false)
local canFold = true
for _,p in ipairs(convertedParameters.expressions) do
if p.type ~= "CConstant" or p.signal ~= "Value" then
canFold = false
break
end
end
if canFold and RDXC.Native["cf_"..method.longName] then
local returnType = returnVTypes[1]
local parameterValues = { }
for i,expr in ipairs(convertedParameters.expressions) do
parameterValues[i] = expr.value
end
local newValue = RDXC.Native["cf_"..method.longName](unpack(parameterValues))
if newValue == nil then
cwarning(incriminate, "CouldNotFoldConstant")
else
return Constant(cs, returnVTypes[1], newValue, "Value")
end
end
if explicit and method.isAbstract then
cerror(incriminate, "AbstractMethodInvokedExplicitly")
end
return {
type = "CMethodCall",
method = method,
explicit = explicit,
delegateExpr = delegateExpr,
parameters = convertedParameters,
vTypes = returnVTypes,
accessModes = returnAccessModes,
}
end
end
cerror(incriminate, "CouldNotMatchOverload", mg.name)
end
DischargeIntercept = function(cs, v, incriminate, discharging)
if v.type ~= "CObjectMethod" or not v.methodGroup.isIntercept then
-- Not an intercept node
return v
end
if not discharging then
v.vTypes = { ST_InterceptType }
v.accessModes = { "I" }
return v
end
-- Execute with no parameters to get the return value
return MatchMethodCall(cs, v, EmptyExpressionList(), incriminate)
end
local function CompileIndexExpression(cs, node, scope, discharging)
-- 3 scenarios:
-- - Array indexes are P-access values
-- - Index operations on non-arrays are __index when discharging and __setindex when not discharging
local leftExpr = CompileExpression(cs, node.operands[1], scope, true)
if leftExpr.accessModes == nil or #leftExpr.accessModes == 0 then
cerror(node, "ExpectedValueForIndex")
end
local leftVType = leftExpr.vTypes[1]
local indexes = CompileExpressionList(cs, node.operands[2], scope, true)
if leftVType.type == "CArrayOfType" then
local arrayIndexST = cs.gst[arrayIndexType]
if arrayIndexST == nil then
throw(SIGNAL_UnresolvedExpression)
end
if #indexes.accessModes ~= leftVType.dimensions then
cerror(node, "ArrayIndexCountMismatch", tostring(leftVType.dimensions), tostring(#indexes.expressions))
end
local rvLeft = ConvertExpression(cs, node, AdjustValueCount(cs, leftExpr, node, 1), { leftVType }, { "R" }, false )
-- Convert all indexes to the array index type and as values
local arrayIndexVTypes = { }
local arrayIndexAccessModes = { }
for _,idx in ipairs(indexes.expressions) do
arrayIndexVTypes[#arrayIndexVTypes+1] = arrayIndexST
arrayIndexAccessModes[#arrayIndexAccessModes+1] = "R"
end
local resultAM = (leftVType.isConst and "CP" or "P")
return {
type = "CArrayIndex",
operand = rvLeft,
indexes = ConvertExpression(cs, node, indexes, arrayIndexVTypes, arrayIndexAccessModes, false ),
vTypes = { leftVType.containedType },
accessModes = { resultAM },
}
elseif leftVType.type == "CStructuredType" then
if not leftVType.isCompiled or not leftVType.finalizer.isCompiled then
throw(SIGNAL_UnresolvedExpression)
end
local targetAccessMode
if VTypeIsRefStruct(leftVType) then
targetAccessMode = "*P"
else
targetAccessMode = "R"
end
local pvLeft = ConvertExpression(cs, node, AdjustValueCount(cs, leftExpr, node, 1), { leftVType }, { targetAccessMode }, false )
if discharging then
local mg = leftVType.namespace.symbols["__index"]
if mg == nil then
cerror(node, "CouldNotFindIndexMethod")
end
if mg.type ~= "CMethodGroup" then
cerror(node, "IndexMemberNotMethod")
end
local objMethod = {
type = "CObjectMethod",
object = pvLeft,
methodGroup = mg,
}
return MatchMethodCall(cs, objMethod, indexes, node)
else
if targetAccessMode == "*P" and leftExpr.accessModes[1] == "R" then
cerror(node, "IndexedObjectWasValue")
end
local mg = leftVType.namespace.symbols["__setindex"]
if mg == nil then
cerror(node, "CouldNotFindSetIndexMethod")
end
if mg.type ~= "CMethodGroup" then
cerror(node, "SetIndexMemberNotMethod")
end
local objMethod = {
type = "CObjectMethod",
object = pvLeft,
methodGroup = mg,
}
return {
type = "CSetIndexCall",
methodCall = objMethod,
indexes = indexes,
accessModes = { "A" },
vTypes = { ST_SetIndexType },
}
end
else
assert(false)
end
end
local function CompileInitializeInstance(cs, expr, scope, parametersNode, incriminate)
local parameters
if parametersNode then
parameters = CompileExpressionList(cs, parametersNode, scope, true)
else
parameters = EmptyExpressionList()
end
local leftVT = expr.vTypes[1]
local initMG = leftVT.namespace.symbols["Initialize"]
if initMG == nil or initMG.type ~= "CMethodGroup" then
if parametersNode == nil or #parametersNode.expressions == 0 then
-- Don't bother initializing
if VTypeIsRefStruct(leftVT) then
return {
type = "CAllocateTemporary",
vTypes = { leftVT },
accessModes = { "L" },
}
else
return expr
end
end
cerror(incriminate, "TypeDoesNotHaveInitialize")
end
local cloneExpr
local recoveryAM
local baseExpr
if VTypeIsObjectReference(leftVT) then
recoveryAM = "R"
baseExpr = expr
elseif VTypeIsRefStruct(leftVT) then
recoveryAM = "L"
baseExpr = {
type = "CAllocateTemporary",
vTypes = { leftVT },
accessModes = { "L" },
}
else
cerror(incriminate, "InitializeOnNonReferenceType")
end
cloneExpr = {
type = "CCloneExpression",
vTypes = { leftVT },
accessModes = { recoveryAM },
expression = baseExpr
}
local objMethod = ObjectMethod(cs, cloneExpr, initMG, incriminate)
local mc = MatchMethodCall(cs, objMethod, parameters, incriminate, true) -- Constructors are always explicit
if #mc.vTypes ~= 0 then
cerror(incriminate, "InitializeMethodReturnsValues")
end
return {
type = "CInitializeAndRecover",
vTypes = { leftVT },
accessModes = { recoveryAM },
disallowWrites = true,
expression = mc
}
end
local function CompileInitializeArray(cs, expr, scope, initializersNode)
local leftVT = expr.vTypes[1]
local exprList = CompileExpressionList(cs, initializersNode, scope, true)
local targetVType = expr.vTypes[1].containedType
assert(targetVType)
local pInitializerNode = {
type = "CInitializeArray",
initializers = { },
dimensions = { },
localVar = LocalVariable(nil, leftVT, false),
vTypes = { leftVT },
accessModes = { "L" },
incriminateNode = initializersNode,
}
local dimCount = 1
for _,iexpr in ipairs(exprList.expressions) do
local subExpr = AdjustValueCount(cs, iexpr, initializersNode, 1)
subExpr = ConvertExpression(cs, initializersNode, subExpr, { targetVType }, nil, false)
pInitializerNode.initializers[#pInitializerNode.initializers+1] = subExpr
end
if expr.parameters == nil then
if leftVT.dimensions ~= 1 then
cerror(initializersNode, "ParameterlessInitializerOnMultidimensionalArray")
end
local d = #exprList.expressions
pInitializerNode.dimensions[1] = d
dimCount = d
else
for _,iexpr in ipairs(expr.parameters.expressions) do
if iexpr.type ~= "CConstant" then
cerror(initializersNode, "InitializerDimensionNotConstant")
end
if iexpr.vTypes[1].longName ~= arrayIndexType then
cerror(initializersNode, "InitializerDimensionWrongType")
end
local d = tonumber(iexpr.value)
if d < 0 then
cerror(initializersNode, "NegativeDimension")
end
pInitializerNode.dimensions[#pInitializerNode.dimensions+1] = d
dimCount = dimCount * d
end
if dimCount ~= #exprList.expressions then
cerror(initializersNode, "DimensionInitializerMismatch", tostring(dimCount), tostring(#exprList.expressions))
end
end
return pInitializerNode
end
local function CompileInitializeProperties(cs, expr, scope, initializersNode)
local leftVT = expr.vTypes[1]
assert(leftVT.type ~= "CArrayOfType")
local baseExpr
if leftVT.declType == "class" or leftVT.declType == "struct" then
baseExpr = expr
else
cerror(initializersNode, "InitializerOnNonStructuredType")
end
local mls = MemberLookupScope(cs, nil, leftVT)
local pInitializerNode = {
type = "CInitializeProperties",
initializers = { },
localVar = LocalVariable(nil, leftVT, false),
vTypes = { leftVT },
accessModes = { "L" },
incriminateNode = initializersNode,
}
mls.thisLocal = pInitializerNode.localVar
local propertiesSet = { }
for _,p in ipairs(initializersNode.initializers) do
local pName = p.name.string
if propertiesSet[pName] then
cerror(p, "PropertyAlreadyInitialized", pName)
end
propertiesSet[pName] = true
local dest = mls:Lookup(pName, p)
if dest == nil then
cerror(p, "InitializerPropertyNotFound", pName)
end
if dest.type ~= "CObjectProperty" then
cerror(p, "InitializedNonProperty")
end
local src = AdjustValueCount(cs, CompileExpression(cs, p.expression, scope, true), p.expression, 1)
-- Intercepts need to be deferred to emission due to some shitty design with the assign emitter
if dest.vTypes[1] ~= ST_InterceptType then
src = ConvertExpression(cs, p, src, { dest.vTypes[1] }, nil, false)
end
pInitializerNode.initializers[#pInitializerNode.initializers+1] = {
type = "CPropertyInitializer",
dest = dest,
src = src,
incriminateNode = p,
}
end
return pInitializerNode
end
local function CompileTernary(cs, node, scope)
assert(node.operands[2])
local trueExprs = CompileExpression(cs, node.operands[1], scope, true)
local falseExprs = CompileExpression(cs, node.operands[2], scope, true)
local numTrue = #trueExprs.vTypes
local numFalse = #falseExprs.vTypes
local numExprs = numTrue
if numTrue == 0 or numFalse == 0 then
cerror(node, "ConditionalExpressionNotValue")
end
if numTrue > numFalse then
trueExprs = AdjustValueCount(cs, trueExprs, node, numFalse)
numExprs = numFalse
elseif numFalse > numTrue then
falseExprs = AdjustValueCount(cs, falseExprs, node, numTrue)
end
local targetVTypeSet = { }
local resultAccessModes = { }
for i=1,numExprs do
local preferVType
local trueVType = trueExprs.vTypes[i]
local falseVType = falseExprs.vTypes[i]
if trueVType.longName == "Core.nullreference" then
trueVType = cs.gst["Core.Object"]
end
if falseVType.longName == "Core.nullreference" then
falseVType = cs.gst["Core.Object"]
end
if trueVType == falseVType then
preferVType = trueVType
else
if TypeDirectlyCastable(falseVType, trueVType) then
preferVType = trueVType
elseif TypeDirectlyCastable(trueVType, falseVType) then
preferVType = falseVType
else
local reduceSet = { }
-- See if we can reduce one of the values to the other
if trueVType.type == "CStructuredType" then
for _,interf in ipairs(trueVType.interfaces) do
reduceSet[interf] = true
end
local pType = trueVType
while pType ~= nil do
reduceSet[pType] = true
pType = pType.parentType
end
for _,interf in ipairs(falseVType.interfaces) do
if reduceSet[interf.interfaceType] then
if preferVType ~= nil then
cerror(node, "TernaryPairResolvesToMultipleInterfaces", tostring(i))
end
preferVType = interf.interfaceType
end
end
pType = falseVType
while pType ~= nil do
if reduceSet[pType] then
preferVType = pType
break;
end
pType = pType.parentType
end
end
if preferVType == nil then
cerror(node, "TernaryPairNotConvertable", tostring(i))
end
end
end
targetVTypeSet[i] = preferVType
resultAccessModes[i] = "R"
if VTypeIsRefStruct(preferVType) then
resultAccessModes[i] = "CP"
end
end
trueExprs = ConvertExpression(cs, node, trueExprs, targetVTypeSet, nil, false)
falseExprs = ConvertExpression(cs, node, falseExprs, targetVTypeSet, nil, false)
local cond = CompiledExprToBoolean(cs, node, CompileExpression(cs, node.condition, scope, true))
-- Fold static conditions
if cond.type == "CConstant" and cond.signal == "Value" and cond.vTypes[1] == cs.gst["Core.bool"] then
if tostring(cond.value) == "true" then
return trueExprs
else
return falseExprs
end
end
return {
type = "CTernary",
trueExprs = trueExprs,
falseExprs = falseExprs,
cond = cond,
vTypes = targetVTypeSet,
accessModes = resultAccessModes,
incriminateNode = node
}
end
local function DelegateMethodGroup(cs, mg, dt, incriminate)
-- Make sure this is static
if not mg.isStatic then
cerror(incriminate, "DelegatedBoundMethod")
end
if not dt.isCompiled then
throw(SIGNAL_UnresolvedExpression)
end
-- Find an appropriate overload
for _,m in ipairs(mg.overloads) do
if m.parameterList.longName == dt.parameters.longName and
m.returnTypes.longName == dt.returnTypes.longName then
return MethodDelegation(cs, m, dt)
end
end
cerror(incriminate, "CouldNotMatchDelegate")
end
local function DelegateBoundMethod(cs, obj, mg, bdt, incriminate)
if not bdt.isCompiled then
throw(SIGNAL_UnresolvedExpression)
end
local objV
if not mg.isStatic then
objV = AdjustValueCount(cs, obj, incriminate, 1)
local bindTargetAM = "R"
if VTypeIsRefStruct(objV.vTypes[1]) then
bindTargetAM = "CP"
end
objV = ConvertExpression(cs, incriminate, objV, objV.vTypes, { bindTargetAM }, false )
end
-- Find an appropriate overload
for _,m in ipairs(mg.overloads) do
local mParams = m.parameterList
local dtParams = bdt.parameters
if m.returnTypes.longName == bdt.returnTypes.longName and #mParams == #dtParams then
local matched = true
for idx,mParam in ipairs(mParams) do
local dtParam = dtParams[idx]
if idx ~= m.thisParameterOffset and mParam.type.refType ~= dtParam.type.refType then
matched = false
break
end
if dtParam.isNotNull ~= mParam.isNotNull or dtParam.isConstant ~= mParam.isConstant then
matched = false
break
end
end
if matched then
return BoundMethodDelegation(cs, m, bdt, objV)
end
end
end
cerror(incriminate, "CouldNotMatchDelegate")
end
-- Enforces that "symbol" in "namespace" is accessible from "scope"
-- If the namespace is a parent of the scope, then the symbol is always accessible
-- Otherwise, the class owning both scopes are found and inheritance is checked
EnforceAccessibility = function(cs, scope, namespace, symbol, incriminate)
local scopeScan = scope
while scopeScan ~= nil do
if scopeScan.type == "CInstanciatedNamespace" and scopeScan.namespace == namespace then
-- The symbol namespace is a parent of the current namespace, so this is always accessible
return
end
scopeScan = scopeScan.owner
end
-- If the owner namespace isn't accessible, then the symbol must be public
local symbolVisibility = namespace.symbols[symbol].visibility
if symbolVisibility == "private" then
cerror(incriminate, "InaccessiblePrivateMember", symbol)
end
if symbolVisibility == "protected" then
local scopeType = nil
local scopeTypeScan = scope
while scopeTypeScan ~= nil do
if scopeTypeScan.type == "CInstanciatedNamespace" then
if scopeTypeScan.boundType then
scopeType = scopeTypeScan.boundType
break
end
end
scopeTypeScan = scopeTypeScan.owner
end
while scopeType ~= nil do
if scopeType.namespace == namespace then
-- Found a matching type in the inheritance tree
return
end
scopeType = scopeType.baseClass
end
cerror(incriminate, "InaccessibleProtectedMember", symbol)
end
end
-- node: Node to compile
-- scope: Scope that the expression exists in
-- discharging: If true, then this is a read attempt and should discharge intercepts
--
-- This returns a compiled expression, it does NOT emit code.
CompileExpression = function(cs, node, scope, discharging)
local v
assert(discharging ~= nil)
assert(node)
if node.type == "Name" or node.type == "this" then
v = scope:Lookup(node.string, node)
if v == nil then
cerror(node, "UnresolvedName", node.string)
end
if v.type == "CLocalVariable" and v.method ~= nil and v.method ~= BlockMethod(scope) then
cerror(node, "AccessedExternalLocal")
end
v = DischargeIntercept(cs, v, node, discharging)
assert(v, "AF9")
elseif node.type == "Indirect" then
local left = CompileExpression(cs, node.operands[1], scope, true)
if left.type == "CStructuredType" or left.type == "CNamespace" then
if left.type == "CStructuredType" then
if not left.isCompiled then
throw(SIGNAL_UnresolvedExpression)
end
left = left.namespace
end
local symbol = node.operands[2].string
v = left.symbols[symbol]
if v == nil then
cerror(node.operands[2], "UnresolvedMember", symbol, left.prettyName)
end
if (v.type == "CProperty" or v.type == "CMethodGroup") and not v.isStatic then
cerror(node.operands[2], "ExpectedStaticMember", symbol)
end
EnforceAccessibility(cs, scope, left, symbol, node)
-- Fall through, this could be a type ref
else --if left.type == "CLocalVariable" or left.type == "CObjectProperty" or left.type == "CStaticInstance" then
left = AdjustValueCount(cs, left, node, 1)
if not left.vTypes[1].isCompiled then
throw(SIGNAL_UnresolvedExpression)
end
if left.vTypes[1].type == "CArrayOfType" then
local arrayType = cs.gst["Core.Array"]
if arrayType == nil then
throw(SIGNAL_UnresolvedExpression)
end
left = ConvertExpression(cs, node, left, { arrayType }, nil, false )
elseif left.vTypes[1].type == "CStaticDelegateType" then
local methodType = cs.gst["Core.RDX.Method"]
if methodType == nil then
throw(SIGNAL_UnresolvedExpression)
end
left = ConvertExpression(cs, node, left, { methodType }, nil, false )
end
local leftVT = left.vTypes[1]
local namespace = leftVT.namespace
local symbol = node.operands[2].string
local right = namespace.symbols[symbol]
if right == nil then
-- If this is an interface, try from Core.Object
if leftVT.type == "CStructuredType" and leftVT.declType == "interface" then
local objType = cs.gst["Core.Object"]
if objType == nil then
throw(SIGNAL_UnresolvedExpression)
end
namespace = objType.namespace
right = namespace.symbols[symbol]
if right == nil then
cerror(node.operands[2], "UnresolvedMember", symbol, "Core.Object")
end
else
cerror(node.operands[2], "UnresolvedMember", symbol, leftVT.prettyName)
end
end
EnforceAccessibility(cs, scope, namespace, symbol, node)
if (right.type == "CProperty" or right.type == "CMethodGroup") and right.isStatic then
cerror(node.operands[2], "ExpectedInstanceMember", symbol)
end
if right.type == "CProperty" then
return ObjectProperty(cs, left, right, node)
end
if right.type == "CMethodGroup" then
if right.isArrayIntercept then
cerror(node, "CanNotAccessArrayIntercept", symbol)
end
local objMethod = ObjectMethod(cs, left, right, node)
objMethod.explicit = node.explicit
return DischargeIntercept(cs, objMethod, node, discharging)
end
assert(false, "AF10")
--else
-- error("Unimplemented indirection of left type "..left.type)
end
elseif node.type == "Invoke" then
local left = CompileExpression(cs, node.operands[1], scope, true)
local parameters
assert(left, "AF11")
if node.operands[2] == nil then
parameters = EmptyExpressionList()
else
parameters = CompileExpressionList(cs, node.operands[2], scope, true)
end
local delegateType = nil
if left.vTypes and #left.vTypes > 0 then
local leftVType = left.vTypes[1]
if leftVType.type == "CStaticDelegateType" or leftVType.type == "CBoundDelegateType" then
delegateType = left.vTypes[1]
left = ConvertExpression(cs, node, AdjustValueCount(cs, left, node, 1), { delegateType }, { "L" }, false )
end
end
if left.type ~= "CMethodGroup" and left.type ~= "CObjectMethod" and delegateType == nil then
cerror(node, "CalledNonMethod")
end
if left.isIntercept or left.isArrayIntercept then
cerror(node, "CalledIntercept")
end
if left.type == "CMethodGroup" and not left.isCompiled then
throw(SIGNAL_UnresolvedExpression)
end
assert(parameters.accessModes)
return MatchMethodCall(cs, left, parameters, node, left.explicit, delegateType)
elseif node.type == "BinaryOperatorNode" then
return OperationToMethod(cs, node, scope)
elseif node.type == "UnaryOperatorNode" then
return OperationToMethod(cs, node, scope)
elseif node.type == "null" then
return Constant(cs, "Core.nullreference", "null", "NullRef")
elseif node.type == "String" then
return Constant(cs, "Core.string", node.string, "Value")
elseif node.type == "true" or node.type == "false" then
return Constant(cs, "Core.bool", node.type, "Value")
elseif node.type == "Number" then
local v, t, what = RDXC.Native.parseNumber(node.string)
return Constant(cs, t, v, "Value")
elseif node.type == "Template" then
local left = CompileExpression(cs, node.operands[1], scope, true)
if left.type ~= "CStructuredType" then
cerror(node, "TemplateFromNonStructuredType")
end
if not left.isCompiled then
throw(SIGNAL_UnresolvedExpression)
end
if not left.isTemplate then
cerror(node, "TemplateFromNonStructuredType")
end
local templateParameters = { }
for _,trNode in ipairs(node.operands[2].types) do
local tArg = TypeReference(cs, trNode, scope, false)
CompileTypeReference(cs, tArg)
if (not tArg.isCompiled) or (not tArg.refType.isCompiled) then
throw(SIGNAL_UnresolvedExpression)
end
templateParameters[#templateParameters+1] = tArg.refType
end
if #left.uncompiledNode.templateParameters.parameters ~= #templateParameters then
cerror(node, "TemplateParameterMismatch")
end
v = ConstructTypeTemplate(cs, left, templateParameters)
if not cs.compilingTypes then
-- This was declared inside a method, reestablish types types
CompileTypeShells(cs)
assert(v.isCompiled, "AF12")
end
elseif node.type == "CLocalVariable" or
node.type == "CArrayIndex" or
node.type == "CSetIndexCall" or
node.type == "CObjectProperty" or
node.type == "CStaticInstance" or
node.type == "CRecycledValues" or
node.type == "CMethodCall" or
node.type == "CConstant" or
node.type == "CTernary" then
-- Precompiled node
return node
elseif node.type == "CObjectMethod" and node.vTypes ~= nil then
return node
elseif node.type == "Index" then
return CompileIndexExpression(cs, node, scope, discharging)
elseif node.type == "CheckCast" then
local boolType = cs.gst["Core.bool"]
if boolType == nil then
throw(SIGNAL_UnresolvedExpression)
end
local left = AdjustValueCount(cs, CompileExpression(cs, node.operands[1], scope, true), node, 1)
local tr = TypeReference(cs, node.operands[2], scope, true)
CompileTypeReference(cs, tr)
if not tr.isCompiled then
cerror(node, "CastToNonType")
end
local leftType = left.vTypes[1]
local rightType = tr.refType
if TypeDirectlyCastable(leftType, rightType) then
-- If this is a guaranteed convert, always accept
return Constant(cs, "Core.bool", "true", "Value")
end
-- If this is a polymorphic convert, then check
if TypePolymorphicallyCastable(leftType, rightType) then
if leftType.type == "CStructuredType" and leftType.declType == "interface" then
local objectClass = cs.gst["Core.Object"]
left = ConvertExpression(cs, node, left, { objectClass }, { "R" }, false)
leftType = objectClass
end
return {
type = "CCheckCast",
expression = ConvertExpression(cs, node, left, { leftType }, { "R" }, true),
checkType = rightType,
vTypes = { boolType },
accessModes = { "R" },
}
end
cwarning(node, "ImpossibleConversionCheck")
return Constant(cs, "Core.bool", "false", "Value")
elseif node.type == "Cast" then
local left = CompileExpression(cs, node.operands[1], scope, true)
local targetTypeRefs = { }
if node.multipleTypes then
for i,t in ipairs(node.operands[2].types) do
targetTypeRefs[i] = t
end
else
targetTypeRefs[1] = node.operands[2]
end
local targetVTypes = { }
local targetAccessModes = { }
for tri,trNode in ipairs(targetTypeRefs) do
local tr = TypeReference(cs, trNode, scope, true)
CompileTypeReference(cs, tr)
if not tr.isCompiled then
cerror(node, "CastToNonType")
end
local right = tr.refType
if right.type ~= "CStructuredType" and right.type ~= "CArrayOfType" and right.type ~= "CStaticDelegateType" and right.type ~= "CBoundDelegateType" then
cerror(node, "CastToNonType")
end
if left.type == "CMethodGroup" then
if node.multipleTypes then
cerror(node, "DelegatedToMultipleTypes")
end
if right.type == "CStaticDelegateType" then
return DelegateMethodGroup(cs, left, right, node)
elseif right.type == "CBoundDelegateType" then
return DelegateBoundMethod(cs, nil, left, right, node)
else
cerror(node, "BadDelegation", PrettyInternalClasses[right.type])
end
end
if left.type == "CObjectMethod" then
if node.multipleTypes then
cerror(node, "DelegatedToMultipleTypes")
end
if right.type ~= "CBoundDelegateType" then
cerror(node, "BadDelegation", PrettyInternalClasses[right.type])
end
return DelegateBoundMethod(cs, left.object, left.methodGroup, right, node)
end
if left.accessModes == nil then
cerror(node, "ExpectedExpression", PrettyInternalClasses[left.type])
end
targetAccessModes[tri] = "R"
if VTypeIsRefStruct(right) then
targetAccessModes[tri] = "CP"
end
targetVTypes[tri] = right
end
return ConvertExpression(cs, node, AdjustValueCount(cs, left, node, #targetTypeRefs), targetVTypes, targetAccessModes, true )
elseif node.type == "SingleResultNode" then
local left = CompileExpression(cs, node.operands[1], scope, true)
return AdjustValueCount(cs, left, node, 1)
elseif node.type == "NewInstanceNode" then
local tr = TypeReference(cs, node.typeSpec, scope, true)
CompileTypeReference(cs, tr)
if not tr.isCompiled then
cerror(node, "NewCreatedNonType")
end
local t = tr.refType
if t.type == "CStructuredType" and t.declType == "interface" then
cerror(node, "NewInterface")
end
if t.isAbstract then
cerror(node, "NewAbstractType", t.abstractBlame.signature)
end
if t.type == "CStaticDelegateType" or t.type == "CBoundDelegateType" then
cerror(node, "NewDelegate")
end
local instance = {
type = "CNewInstance",
parameters = tr.specifiedDimensions,
accessModes = { "R" },
vTypes = { t },
}
if t.type == "CArrayOfType" then
if node.initializers then
if node.initializers.type == "PropertyInitializerListNode" then
cerror(node, "InitializedArrayWithProperties")
end
return CompileInitializeArray(cs, instance, scope, node.initializers)
else
if instance.parameters == nil then
cerror(node, "ExpectedDimensionsForArrayCreation")
end
return instance
end
else
if node.initializers then
if node.initializers.type == "ExpressionList" then
if #node.initializers.expressions == 0 then
-- Empty expression list, convert to an empty property initializer set
node.initializers = VirtualParseNode("PropertyInitializerListNode", node.initializers)
node.initializers.initializers = { }
else
cerror(node, "InitializedObjectWithExpressions")
end
end
return CompileInitializeProperties(cs, instance, scope, node.initializers)
else
return CompileInitializeInstance(cs, instance, scope, node.initParameters, node)
end
end
elseif node.type == "GenerateHashNode" then
local left = CompileExpression(cs, node.expression, scope, true)
left = AdjustValueCount(cs, left, node, 1)
local desiredAccessMode = "R"
if VTypeIsRefStruct(left.vTypes[1]) then
desiredAccessMode = "CP"
end
left = ConvertExpression(cs, node, left, left.vTypes, { desiredAccessMode }, false )
local t = cs.gst["Core.hashcode"]
if t == nil then
throw(SIGNAL_UnresolvedExpression)
end
return {
type = "CGenerateHashNode",
expression = left,
accessModes = { "R" },
vTypes = { t }
}
elseif node.type == "TypeOfNode" then
local left = CompileExpression(cs, node.expression, scope, true)
if left.type == "CStructuredType" or left.type == "CBoundDelegateType" then
if not left.isCompiled then
throw(SIGNAL_UnresolvedExpression)
end
return Constant(cs, "Core.RDX.StructuredType", left.longName, "Resource")
elseif left.type == "CArrayOfType" then
if not left.isCompiled then
throw(SIGNAL_UnresolvedExpression)
end
return Constant(cs, "Core.RDX.ArrayOfType", left.longName, "Resource")
elseif left.type == "CStaticDelegateType" then
if not left.isCompiled then
throw(SIGNAL_UnresolvedExpression)
end
return Constant(cs, "Core.RDX.DelegateType", left.longName, "Resource")
else
left = AdjustValueCount(cs, left, node, 1)
if left.vTypes[1].longName == "Core.nullreference" then
return cs.gst["Core.Object"]
end
return left.vTypes[1]
end
elseif node.type == "Ternary" then
return CompileTernary(cs, node, scope)
elseif node.type == "CreateTupleNode" then
return CompileExpressionList(cs, node.expression, scope, true)
else
error("Unimplemented expression node type "..node.type)
end
if v.type == "CTypeReference" then
if not v.isCompiled then
throw(SIGNAL_UnresolvedExpression)
end
v = v.refType
end
return v
end
SingleExpressionToList = function(expr)
assert(expr.vTypes)
return FlattenMV({
type = "CMultipleValues",
accessModes = clonetable(expr.accessModes),
expressions = { expr },
vTypes = clonetable(expr.vTypes),
})
end
CompileExpressionList = function(cs, node, scope, discharging)
assert(discharging ~= nil)
assert(scope, "AF13")
local vTypes = { }
local expressions = { }
local accessModes = { }
for _,expr in ipairs(node.expressions) do
local exprNode = CompileExpression(cs, expr, scope, discharging)
if exprNode.accessModes == nil then
cerror(node, "ExpectedExpression", exprNode.type)
end
expressions[#expressions+1] = exprNode
for idx,vt in ipairs(exprNode.vTypes) do
vTypes[#vTypes+1] = vt
accessModes[#accessModes+1] = exprNode.accessModes[idx]
end
end
assert(vTypes)
return FlattenMV({
type = "CMultipleValues",
accessModes = accessModes,
expressions = expressions,
vTypes = vTypes,
})
end
Scope = function(owner)
return {
type = "CScope",
symbols = { },
owner = owner,
InsertUnique = function(self, symbolName, value, incriminate)
assert(value)
local lookupSymbol
if type(symbolName) == "string" then
lookupSymbol = symbolName
else
incriminate = symbolName
lookupSymbol = symbolName.string
end
if self.symbols[lookupSymbol] ~= nil then
cerror(incriminate, "DuplicateSymbol", lookupSymbol)
end
self.symbols[lookupSymbol] = value
end,
Lookup = function(self, symbol, incriminate)
local v = self.symbols[symbol]
local invisibleSymbolWarning = false
if v ~= nil then
if v.invisibleSymbol == true then
invisibleSymbolWarning = true
else
return v
end
end
local fallThrough = nil
if self.owner ~= nil then
fallThrough = self.owner:Lookup(symbol, incriminate)
end
if fallThrough ~= nil and invisibleSymbolWarning then
cwarning(incriminate, "InvisibleSymbol", symbol, symbol)
end
return fallThrough
end
}
end
-- Imported namespaces are a shallow check
local function ImportedNamespace(cs, pathNode)
return {
type = "CImportedNamespace",
Lookup = function(self, symbol, incriminate)
if self.namespace == nil then
local ns = cs.globalNamespace
for _,path in ipairs(pathNode) do
ns = ns.symbols[path.string]
if ns == nil then
cerror(incriminate, "CouldNotResolveNamespace", path.string)
end
end
pathNode = nil
self.namespace = ns
end
return self.namespace.symbols[symbol]
end,
}
end
-- InstanciatedNamespaces are namespaces that are referenced by an absolute namespace path
local function InstanciatedNamespace(owner, ns, boundType)
local insn = Scope(owner)
insn.type = "CInstanciatedNamespace"
insn.imports = { }
insn.namespace = ns
insn.boundType = boundType
assert(owner == nil or owner.type ~= "CNamespace", "AF14")
insn.Lookup = function(self, symbol, incriminate)
local v = self.namespace.symbols[symbol]
if v ~= nil then
return v
end
for _,i in ipairs(self.imports) do
v = i:Lookup(symbol, incriminate)
if v ~= nil then
return v
end
end
if self.owner ~= nil then
return self.owner:Lookup(symbol, incriminate)
end
return nil
end
return insn
end
local function Namespace(owner, name, prefix)
local ns = Scope(owner)
ns.type = "CNamespace"
ns.name = name
ns.prefix = prefix
return ns
end
local function DelegateType(cs, namespace, scope, node, definedBy)
local parameters = { }
local returnTypes = { }
local isStatic
if node.accessDescriptor.static then
isStatic = true
end
if node.parameters ~= nil then
for _,parameterNode in ipairs(node.parameters.parameters) do
local parameter = {
type = TypeReference(cs, parameterNode.type, scope),
isConst = (parameterNode.const ~= nil),
isNotNull = (parameterNode.notnull ~= nil),
}
parameters[#parameters+1] = parameter
end
end
for _,typeNode in ipairs(node.returnType.types) do
returnTypes[#returnTypes+1] = TypeReference(cs, typeNode, scope)
end
local dt = {
name = node.name.string,
parameters = ParameterList(cs, parameters),
returnTypes = TypeTuple(cs, returnTypes),
namespace = namespace,
uncompiledNode = node,
}
if isStatic then
dt.type = "CStaticDelegateType"
dt.isStatic = true
dt.actualParameterList = dt.parameters
else
dt.type = "CBoundDelegateType"
dt.isStatic = false
dt.methodMarshals = { }
local actualParams = { true }
actualParams[1] = {
type = TypeReference(cs, dt),
name = { type = "Name", string = "this" },
isConst = true,
isNotNull = true,
}
for idx,p in ipairs(dt.parameters.parameters) do
actualParams[idx+1] = p
end
local actualParameterList = ParameterList(cs, actualParams)
dt.actualParameterList = actualParameterList
end
return dt
end
local function CompileDelegateType(cs, dt)
if not dt.parameters.isCompiled then
return false
end
if not dt.returnTypes.isCompiled then
return false
end
local refName = dt.returnTypes.longName..dt.parameters.longName
local longName
if dt.isStatic then
longName = "#DS-"..refName
else
longName = "#DB-"..refName
dt.invokeName = longName.."/invoke"
end
dt.prettyName = "delegate "..dt.returnTypes.prettyName
if not dt.isStatic then
dt.prettyName = "bound "..dt.prettyName
end
dt.prettyName = dt.prettyName..dt.parameters.prettyName
dt.longName = longName
dt.isCompiled = true
cs.gst[dt.longName] = dt
return true
end
local function MarshalForBoundDelegate(cs, bdt, method)
local mName = method.longName
if bdt.methodMarshals[mName] then
return bdt.methodMarshals[mName]
end
-- Doesn't exist
local marshal = {
type = "CBoundDelegateMarshal",
owner = bdt,
longName = bdt.longName.."/glue/"..method.longName,
invokeName = bdt.longName.."/glueInvoke/"..method.longName,
returnTypes = bdt.returnTypes,
bdt = bdt,
method = method,
}
if method.type == "CMethod" and not method.isStatic then
marshal.thisType = method.definedByType
elseif method.type == "CStaticDelegateType" then
marshal.thisType = method
else
assert(method.type == "CMethod" and method.isStatic)
end
-- Generate a new parameter list with the marshal as "this"
local newParameters = { }
for idx,param in ipairs(bdt.actualParameterList.parameters) do
newParameters[idx] = param
end
local tRef = TypeReference(cs, marshal)
CompileTypeReference(cs, tRef)
newParameters[1] = {
type = tRef,
name = { type = "Name", string = "this" },
isConst = true,
isNotNull = true,
}
marshal.actualParameterList = ParameterList(cs, newParameters)
CompileParameterList(cs, marshal.actualParameterList)
assert(marshal.actualParameterList.isCompiled)
bdt.methodMarshals[mName] = marshal
cs.gst[marshal.longName] = marshal
local instructions = { }
local numInstructions = 0
local addInstr = function(instr)
numInstructions = numInstructions + 1
instructions[numInstructions] = instr
end
-- NOTE: "method" may actually be a delegate
local method = marshal.method
local isStaticDelegate = (method.type == "CStaticDelegateType")
local refReturnValueStorage = { } -- [returnValueIndex] = localIndex
local firstStorageLocal = #marshal.actualParameterList.parameters
local numStoredLocals = 0
local numReturnValues
local delegateValueLocal
-- Create storage space for reference structs
for idx,ref in ipairs(method.returnTypes.typeReferences) do
local rvType = ref.refType
if VTypeIsRefStruct(rvType) then
local storedLocal = firstStorageLocal + numStoredLocals
addInstr( { op = "alloclocal", res1 = rvType.longName } )
numStoredLocals = numStoredLocals + 1
refReturnValueStorage[idx] = storedLocal
end
end
if isStaticDelegate then
delegateValueLocal = firstStorageLocal + numStoredLocals
numStoredLocals = numStoredLocals + 1
-- Load "this"
addInstr( { op = "localref", int1 = 0 } )
addInstr( { op = "load" } )
-- Load the delegate
addInstr( { op = "property", int1 = 0 } )
addInstr( { op = "load" } )
-- Store it in a local
addInstr( { op = "createlocal", res1 = method.longName } )
end
-- Push return value space
for idx,ref in ipairs(method.returnTypes.typeReferences) do
if refReturnValueStorage[idx] then
addInstr( { op = "localref", int1 = refReturnValueStorage[idx] } )
addInstr( { op = "pinlocal" } )
else
addInstr( { op = "pushempty", res1 = ref.refType.longName } )
end
end
if isStaticDelegate then
-- Push local for delegate call
addInstr( { op = "localref", int1 = delegateValueLocal } )
end
-- Push parameters
local fetchIndex = 1
for idx,param in ipairs(method.actualParameterList.parameters) do
if idx == method.thisParameterOffset then
-- Load "this" value
addInstr( { op = "localref", int1 = 0 } )
addInstr( { op = "load" } )
addInstr( { op = "property", int1 = 0 } )
if not VTypeIsRefStruct(method.definedByType) then
addInstr( { op = "load" } )
end
else
addInstr( { op = "localref", int1 = fetchIndex } )
addInstr( { op = "load" } )
fetchIndex = fetchIndex + 1
end
end
if isStaticDelegate then
addInstr( { op = "calldelegate", res1 = method.longName } )
elseif method.vftIndex then
addInstr( { op = "callvirtual", res1 = method.longName } )
else
addInstr( { op = "call", res1 = method.longName } )
end
addInstr( { op = "return", int1 = #method.returnTypes.typeReferences } )
for i=1,numStoredLocals do
addInstr( { op = "removelocal" } )
end
marshal.instructions = instructions
marshal.isCompiled = true
return marshal
end
setglobal("ArrayOfTypeCode", function(numDimensions, isConst)
return tostring(numDimensions).."/"..tostring(isConst ~= nil and isConst ~= false)
end )
local function StructuredType(cs, namespace, scope, attribTags, node)
local isTemplate = (node.templateParameters ~= nil)
local st = {
type = "CStructuredType",
isTemplate = isTemplate,
isCompiled = false,
namespace = namespace, -- Namespace containing members of the type, named after the type
scope = scope, -- Scope external to the type, for resolving dependencies
methods = { },
methodGroups = { },
virtualMethods = { },
properties = { },
arraysOf = { },
enumerants = { },
interfaces = { },
implementedInterfaces = { },
initializers = { },
initializersSet = { },
name = node.name.string,
attribTags = attribTags,
--baseClass = nil,
uncompiledNode = node,
}
st.internalScope = InstanciatedNamespace(scope, namespace, st)
if isTemplate then
st.templateInstances = { }
end
return st
end
ConstructTypeTemplate = function(cs, st, templateParameters)
local tParameters = ":<"
local prettyParameters = ":<"
for idx,tp in ipairs(templateParameters) do
if idx ~= 1 then
tParameters = tParameters..","
prettyParameters = prettyParameters..","
end
tParameters = tParameters..tp.longName
prettyParameters = prettyParameters..tp.prettyName
end
tParameters = tParameters..">"
prettyParameters = prettyParameters..">"
local longName = "#Tmpl."..st.longName..tParameters
local prettyName = st.prettyName..prettyParameters
local constructedType = st.templateInstances[tParameters]
if constructedType then
return constructedType
end
if instancedTemplateLimit == 0 then
cerror(st.uncompiledNode, "TooManyTemplates")
end
instancedTemplateLimit = instancedTemplateLimit - 1
local namespace = Namespace(st.namespace.owner, st.name..tParameters, "#Tmpl.")
local templatedScope = Scope(st.scope)
namespace.isFromTemplate = true
-- This needs to be already true since we don't have the originating node for cerror
assert(#templateParameters == #st.uncompiledNode.templateParameters.parameters)
for idx,tp in ipairs(st.uncompiledNode.templateParameters.parameters) do
templatedScope:InsertUnique(tp.string, templateParameters[idx], tp)
end
local templateST = {
type = "CStructuredType",
isTemplate = false,
isCompiled = false,
namespace = namespace, -- Namespace containing members of the type, named after the type
scope = templatedScope, -- Scope external to the type, for resolving dependencies
internalScope = InstanciatedNamespace(templatedScope, namespace),
methods = { },
methodGroups = { },
virtualMethods = { },
properties = { },
arraysOf = { },
name = st.name..tParameters,
templateParameters = templateParameters,
interfaces = { },
implementedInterfaces = { },
initializers = { },
initializersSet = { },
longName = longName,
prettyName = prettyName,
--baseClass = nil,
uncompiledNode = st.uncompiledNode,
}
namespace.createdBy = templateST
-- Add
st.templateInstances[tParameters] = templateST
cs.uncompiled[#cs.uncompiled+1] = templateST
return templateST
end
local function ExtendClass(cs, st, baseST)
assert(st.baseClass == nil)
st.baseClass = baseST
-- Try to alias existing tables
st.aliasVFT = baseST.aliasVFT
if st.aliasVFT == nil then
st.aliasVFT = baseST
end
st.aliasProperties = baseST.aliasProperties
if st.aliasProperties == nil then
st.aliasProperties = baseST
end
st.aliasInterfaces = baseST.aliasInterfaces
if st.aliasInterfaces == nil then
st.aliasInterfaces = baseST
end
-- Copy everything except private members
st.implementedInterfaces = clonetable(baseST.implementedInterfaces)
st.interfaces = clonetable(baseST.interfaces)
for _,m in ipairs(baseST.methods) do
assert(m.visibility)
if m.visibility ~= "private" then
st.methods[#st.methods+1] = m
end
end
for _,mg in ipairs(baseST.methodGroups) do
assert(mg.visibility)
if mg.visibility ~= "private" then
local clonedGroup = CloneMethodGroup(cs, mg)
st.methodGroups[#st.methodGroups+1] = clonedGroup
st.namespace:InsertUnique(mg.name, clonedGroup)
end
end
for _,p in ipairs(baseST.properties) do
assert(p.visibility)
if p.visibility == "private" then
st.properties[#st.properties+1] = PrivatizedProperty(cs, p)
if p.definedByType == baseST then
st.aliasProperties = nil -- This triggered the change, can't recycle the table
end
else
st.properties[#st.properties+1] = p
st.namespace:InsertUnique(p.name, p)
end
end
for k,v in pairs(baseST.namespace.symbols) do
if v.type ~= "CProperty" and v.type ~= "CMethodGroup" and v.visibility ~= "private" then
st.namespace.symbols[k] = v
end
end
st.virtualMethods = clonetable(baseST.virtualMethods)
end
local function AddNamespace(cs, namespace, ins, declarations)
assert(ins.type == "CInstanciatedNamespace")
for _,decl in ipairs(declarations) do
if decl.type == "Namespace" then
if namespace.symbols[decl.name.string] == nil then
namespace:InsertUnique(decl.name, Namespace(namespace, decl.name.string))
end
local newNS = namespace.symbols[decl.name.string]
local newINS = InstanciatedNamespace(ins, newNS)
AddNamespace(cs, newNS, newINS, decl.members.declarations)
elseif decl.type == "Using" then
ins.imports[#ins.imports+1] = ImportedNamespace(cs, decl.namespacePath)
elseif decl.type == "MemberDecl" and structuredTypeDeclTypes[decl.declType.string] then
local uncompiledType = StructuredType(cs, Namespace(namespace, decl.name.string), ins, decl.attribTags, decl)
namespace:InsertUnique(decl.name, uncompiledType)
uncompiledType.namespace.createdBy = uncompiledType
cs.uncompiled[#cs.uncompiled+1] = uncompiledType
elseif decl.type == "MemberDecl" and decl.declType.string == "delegate" then
local uncompiledType = DelegateType(cs, namespace, ins, decl, nil)
namespace:InsertUnique(decl.name, uncompiledType)
cs.uncompiled[#cs.uncompiled+1] = uncompiledType
else
cerror(decl, "BadDeclInNamespace", decl.type, decl.declType.string)
end
end
end
local function MergeParsedFile(cs, pf)
AddNamespace(cs, cs.globalNamespace, InstanciatedNamespace(nil, cs.globalNamespace), pf.declarations)
end
local function ArrayOfType(cs, st, dimensions, isConst, incriminateNode)
local aot = {
type = "CArrayOfType",
containedType = st,
dimensions = dimensions,
isConst = isConst,
isCompiled = false,
incriminateNode = incriminateNode,
arraysOf = { },
}
cs.uncompiled[#cs.uncompiled+1] = aot
return aot
end
local function CompileArrayOfType(cs, aot)
if not aot.containedType.isCompiled then
return false
end
if aot.containedType.longName == varyingType then
cerror(aot.incriminateNode, "CreatedArrayOfVarying")
end
local longName = "#"..aot.containedType.longName.."["
if aot.isConst then
longName = longName.."C"
end
for i=2,aot.dimensions do
longName = longName..","
end
longName = longName.."]"
-- Unwind the AOT to determine the pretty name
local prettyName = ""
local unwind = aot
while unwind.type == "CArrayOfType" do
if unwind.isConst then
prettyName = prettyName.." const"
end
prettyName = prettyName.."["
for i=2,unwind.dimensions do
prettyName = prettyName..","
end
prettyName = prettyName.."]"
unwind = unwind.containedType
end
prettyName = unwind.prettyName..prettyName
aot.prettyName = prettyName
aot.longName = longName
aot.isCompiled = true
cs.gst[longName] = aot
return true
end
TypeReference = function(cs, node, scope, allowDimensions)
assert(node)
local tr = { type = "CTypeReference",
isCompiled = false,
node = node,
scope = scope,
allowDimensions = allowDimensions
}
cs.uncompiled[#cs.uncompiled+1] = tr
assert(scope == nil or scope.type ~= "CNamespace", "Don't use namespaces as lookup scopes! Use InstanciatedNamespace")
return tr
end
ExpressionToType = function(cs, typeNode, scope, allowArrays)
local expr
assert(typeNode)
local succeeded = true
local succeeded, exception = pcall(function()
expr = CompileExpression(cs, typeNode, scope, true)
end )
if succeeded == false then
if exception == SIGNAL_UnresolvedExpression then
return nil
else
error(exception)
end
end
if expr.type == "CArrayOfType" then
if allowArrays then
return expr
end
cerror(typeNode, "ArraysNotAllowed")
end
if expr.type ~= "CStructuredType" and expr.type ~= "CStaticDelegateType" and expr.type ~= "CBoundDelegateType" then
cerror(typeNode, "ExpectedTypeReference", PrettyInternalClasses[expr.type])
return false
end
if expr.isTemplate then
cerror(typeNode, "NewTemplate")
end
return expr
end
local function CompileArrayTypeReference(cs, node, scope, specifyDimensions)
local subType
local subTypeNode = node.subType
local specifiedDimensions
if subTypeNode.type == "ArrayOfType" then
subType = CompileArrayTypeReference(cs, subTypeNode, scope, false)
else
assert(subTypeNode.type == "Type")
subType = ExpressionToType(cs, subTypeNode.baseType, scope, true)
end
if not subType then
return nil -- Unresolved dependency
end
-- See if this is cached
local dimensions = node.dimensions
if dimensions == nil then
if not specifyDimensions then
cerror(node, "UnexpectedDimensions")
end
local arrayIndexType = cs.gst[arrayIndexType]
if arrayIndexType == nil then
throw(SIGNAL_UnresolvedExpression)
end
local convertAccessModes = { }
local convertVTypes = { }
specifiedDimensions = CompileExpressionList(cs, node.specifiedDimensions, scope, true)
if #specifiedDimensions.vTypes == 0 then
cerror(node, "ExpectedDimensions")
end
for idx in ipairs(specifiedDimensions.vTypes) do
convertAccessModes[idx] = "R"
convertVTypes[idx] = arrayIndexType
end
specifiedDimensions = ConvertExpression(cs, node, specifiedDimensions, convertVTypes, convertAccessModes, false)
dimensions = #specifiedDimensions.vTypes
else
--if specifyDimensions then
-- cerror(node, "ExpectedDimensions")
--end
end
assert(dimensions, "Need to parse out dimensions")
local arrayVariationCode = ArrayOfTypeCode(dimensions, node.isConst)
local aot = subType.arraysOf[arrayVariationCode]
if aot == nil then
assert(subType)
aot = ArrayOfType(cs, subType, dimensions, node.isConst, node)
subType.arraysOf[arrayVariationCode] = aot
if not cs.compilingTypes then
-- Declared inside a function
CompileTypeShells(cs)
end
CompileArrayOfType(cs, aot)
end
return aot, specifiedDimensions
end
CompileTypeReference = function(cs, tr)
if tr.node.type == "ArrayOfType" then
local aot, specifiedDimensions = CompileArrayTypeReference(cs, tr.node, tr.scope, tr.allowDimensions)
if aot == nil then
return false -- Couldn't resolve
end
tr.isCompiled = true
tr.refType = aot
tr.node = nil
tr.specifiedDimensions = specifiedDimensions
return true
end
if tr.node.type == "CStructuredType" or tr.node.type == "CBoundDelegateType" or tr.node.type == "CBoundDelegateMarshal" then
-- Preresolved type reference
tr.isCompiled = true
tr.refType = tr.node
tr.node = nil
return true
end
assert(tr.node.type == "Type")
-- Arrays are allowed here because the expression could be aliased from a typedef that references an array
local expr = ExpressionToType(cs, tr.node.baseType, tr.scope, true)
if not expr then
return false
end
tr.node = nil -- Don't need the node any more
tr.isCompiled = true
tr.refType = expr
return true
end
local function MethodGroup(cs, name, visibility, isStatic, isIntercept, isArrayIntercept, incriminate)
local mg = {
type = "CMethodGroup",
name = name,
isCompiled = false,
isStatic = isStatic,
isIntercept = isIntercept,
isArrayIntercept = isArrayIntercept,
overloads = { },
visibility = visibility,
incriminate = incriminate
}
cs.uncompiled[#cs.uncompiled+1] = mg
return mg
end
CloneMethodGroup = function(cs, mg)
local cloned = clonetable(mg)
cloned.overloads = clonetable(mg.overloads)
cloned.isCompiled = false
cs.uncompiled[#cs.uncompiled+1] = cloned
return cloned
end
local function CompileMethodGroup(cs, mg)
-- Make sure every overload is compiled
for _,overload in ipairs(mg.overloads) do
if not overload.isCompiled then
return false
end
end
mg.isCompiled = true
return true
end
local function CompileTypeTuple(cs, tt)
local longName = "("
for _,tr in ipairs(tt.typeReferences) do
if not tr.isCompiled or tr.refType.longName == nil then
return false
end
if longName ~= "(" then
longName = longName..","
end
longName = longName..tr.refType.longName
end
longName = longName..")"
tt.prettyName = longName
tt.longName = "#TT-"..longName
tt.isCompiled = true
cs.gst[tt.longName] = tt
return true
end
TypeTuple = function(cs, typeReferences)
local tt = {
type = "CTypeTuple",
isCompiled = false,
typeReferences = typeReferences,
}
cs.uncompiled[#cs.uncompiled+1] = tt
return tt
end
CompileParameterList = function(cs, pl)
local longName = "("
for _,param in ipairs(pl.parameters) do
if not param.type.isCompiled or param.type.refType.longName == nil then
return false
end
if longName ~= "(" then
longName = longName..","
end
if param.isNotNull then
longName = longName.."notnull "
elseif param.isConst then
longName = longName.."const "
end
longName = longName..param.type.refType.longName
end
longName = longName..")"
pl.prettyName = longName
pl.longName = "#PL-"..longName
pl.isCompiled = true
cs.gst[pl.longName] = pl
return true
end
ParameterList = function(cs, parameters)
local pl = {
type = "CParameterList",
isCompiled = false,
parameters = parameters,
}
cs.uncompiled[#cs.uncompiled+1] = pl
return pl
end
local function CompileMethod(cs, m)
local longName
if not m.definedByType.isCompiled then
return false
end
longName = m.definedByType.longName.."/"..m.grouping.."/"..m.name.string
if not m.returnTypes.isCompiled then
return false
end
if not m.parameterList.isCompiled then
return false
end
m.signature = m.name.string
if m.declType.type == "coerce" or m.declType.type == "promote" then
m.isLossless = (m.declType.type == "promote")
m.signature = m.signature..m.returnTypes.prettyName
longName = longName..m.returnTypes.prettyName
else
m.signature = m.signature..m.parameterList.prettyName
longName = longName..m.parameterList.prettyName
end
m.returnSignature = m.name.string..m.returnTypes.prettyName
m.longName = longName
m.isCompiled = true
-- Find out what the actual parameters are, including self
-- These aren't needed for the type resolution phase so it's not important that they be compiled when this finishes
local actualParameterList
if m.isStatic then
actualParameterList = m.parameterList
else
local thisParameter = TypeReference(cs, m.definedByType)
CompileTypeReference(cs, thisParameter)
assert(thisParameter.isCompiled)
local thisParameterIndex = 1
local actualParameters = { }
if m.isIntercept and #m.parameterList.parameters == 1 then
thisParameterIndex = 2
end
if m.isArrayIntercept then
thisParameterIndex = 2
end
for idx,param in ipairs(m.parameterList.parameters) do
local insertIdx = idx
if idx >= thisParameterIndex then
insertIdx = insertIdx + 1
end
actualParameters[insertIdx] = param
end
local thisPLParam = {
type = thisParameter,
name = { type = "Name", string = "this" },
}
if VTypeIsRefStruct(thisParameter.refType) then
thisPLParam.isConst = m.isConst
elseif VTypeIsObjectReference(thisParameter.refType) then
thisPLParam.isNotNull = true
thisPLParam.isConst = true
end
actualParameters[thisParameterIndex] = thisPLParam
m.thisParameterIndex = thisParameterIndex
m.thisParameterOffset = thisParameterIndex
actualParameterList = ParameterList(cs, actualParameters)
CompileParameterList(cs, actualParameterList)
assert(actualParameterList.isCompiled)
end
assert(actualParameterList)
m.actualParameterList = actualParameterList
for _,p in ipairs(actualParameterList) do
assert(p.type.refType.longName)
if p.type.refType.longName == varyingType and not m.isNative then
cerror(m.name, "VaryingParameterInNonNative")
end
end
for _,t in ipairs(m.returnTypes) do
if t.refType.longName == varyingType and not m.isNative then
cerror(m.name, "VaryingReturnType")
end
end
cs.gst[longName] = m
return true
end
local function Method(cs, name, grouping, definedByType, returnTypes, parameterList, visibility,
declType, codeBlock, isStatic, isVirtual, isAbstract, isNative, isIntercept, isArrayIntercept, isBranching, isFinal, isConst)
assert(parameterList.type == "CParameterList")
assert(returnTypes.type == nil)
local method = {
type = "CMethod",
name = name,
isBranching = isBranching,
isVirtual = isVirtual,
isAbstract = isAbstract,
isNative = isNative,
isStatic = isStatic,
isIntercept = isIntercept,
isArrayIntercept = isArrayIntercept,
isFinal = isFinal,
isConst = isConst,
declType = declType,
grouping = grouping,
definedByType = definedByType,
isCompiled = false,
parameterList = parameterList,
returnTypes = TypeTuple(cs, returnTypes),
codeBlock = codeBlock,
visibility = visibility,
numPrivateTypes = 0,
}
cs.uncompiled[#cs.uncompiled+1] = method
if codeBlock then
cs.uncompiledCode[#cs.uncompiledCode+1] = method
end
return method
end
PrivatizedProperty = function(cs, p)
if p.alias then
p = p.alias
end
local p = {
type = "CProperty",
typeOf = p.typeOf,
isCompiled = true,
definedByType = p.definedByType,
visibility = p.visibility,
name = p.definedByType.longName.."."..p.name,
nameNode = p.nameNode,
alias = p,
}
return p
end
local function StaticInstance(cs, definedByType, typeOf, visibility, name, isConst, incriminate)
local si = {
type = "CStaticInstance",
isCompiled = false,
definedByType = definedByType,
typeOf = typeOf,
visibility = visibility,
name = (name and name.string),
nameNode = name,
incriminate = incriminate,
isConst = isConst,
}
cs.uncompiled[#cs.uncompiled+1] = si
return si
end
local function CompileStaticInstance(cs, si)
if not si.typeOf.isCompiled or not si.definedByType.isCompiled then
return false
end
local vType = si.typeOf.refType
if not vType.isCompiled or (vType.declType == "CStructuredType" and not vType.finalizer.isCompiled) then
return false
end
si.longName = si.definedByType.longName.."."..si.name
if VTypeIsObjectReference(vType) then
si.accessModes = { "R" }
else
si.accessModes = { (si.isConst and "CP" or "P") }
end
if vType.type == "CStructuredType" and vType.declType == "interface" then
cerror(si.incriminate, "InterfaceResource")
end
si.incriminate = nil
si.vTypes = { si.typeOf.refType }
si.isCompiled = true
cs.gst[si.longName] = si
return true
end
local function Initializer(cs, node, ownerType, ownerMemberName)
local i = {
type = "CInitializer",
isCompiled = false,
ownerType = ownerType,
ownerMemberName = ownerMemberName,
--ownerMember = ???,
uncompiledNode = node,
}
cs.uncompiled[#cs.uncompiled+1] = i
return i
end
local function DefaultInstance(cs, vType, diValue, name, dimensions, isAnonymous)
assert(type(name) == "string")
local defaultInstance = {
type = "CDefaultInstance",
dimensions = dimensions,
typeOf = vType.longName,
longName = name,
value = diValue,
isAnonymous = isAnonymous,
}
cs.defaultInstances[#cs.defaultInstances+1] = defaultInstance
cs.gst[name] = defaultInstance
return defaultInstance
end
local function GetStructuredTypeDefault(cs, st)
local finalValue
if #st.initializers == 0 then
return nil
end
st.defaultDependencySet = { }
finalValue = "{\n"
for idx,init in ipairs(st.initializers) do
if idx ~= 1 then
finalValue = finalValue..",\n"
end
local pName = init.ownerMember.name
if RDXT_RESERVED_SYMBOLS[pName] then
pName = "'"..pName.."'"
end
finalValue = finalValue.."\t"..pName.." : "..init.defaultValue
for k in pairs(init.defaultDependencySet) do
st.defaultDependencySet[k] = true
end
end
finalValue = finalValue.."\n}"
return DefaultInstance(cs, st, finalValue, st.longName.."/default", nil, false)
end
-- Returns the packed initialization value
-- vType: vType of the value being initialized
-- expr: Expression to attempt to evaluate
-- forceRef: If true, the expression must be an instance and not a reference to another resource
-- indentLevel: Indentation level
-- base: Prefix of any generated names
-- dependencySet: A set of any dependency names needed by this initializer
-- dimensions: Output array of dimensions
-- incriminate: Node to incriminate if this errors
local function GetInitializationValue(cs, vType, expr, forceRef, indentLevel, base, dependencySet, dimensions, isAnonymous, incriminate)
assert(incriminate)
local finalValue
local indentation, indentation2, lineBreak
if false then
indentation = ""
indentation2 = ""
lineBreak = " "
else
indentation = ""
for i=1,indentLevel do
indentation = indentation.."\t"
end
indentation2 = indentation.."\t"
lineBreak = "\n"
end
-- Initialization rules:
-- Enum: To a CEnumerant
-- Interface: To a static instance
-- Class/array: Static instance or constructor
-- Struct: To a constructor unless in parseableTypes, in which case CConstant
local allowConstructor
if vType.type == "CStructuredType" and parseableTypes[vType.longName] then
if expr.type ~= "CConstant" or expr.signal ~= "Value" then
cerror(incriminate, "NonConstantInitializer")
end
if expr.vTypes[1].longName == stringType and not forceRef then
cerror(incriminate, "StringResource")
end
if vType.longName == "Core.string" then
finalValue = "'"..escapestring(expr.value).."'"
else
finalValue = expr.value
end
elseif VTypeIsObjectReference(vType) then
if expr.type == "CConvertExpression" then
expr = expr.expression
end
if CastMatchability(expr.vTypes[1], vType) > matchLevels.DIRECT then
cerror(incriminate, "InitializerNotCompatible")
end
allowConstructor = (vType.type == "CArrayOfType" or (vType.type == "CStructuredType" and vType.declType ~= "interface"))
if expr.type == "CStaticInstance" then
if not forceRef then
cerror(incriminate, "ResourceReferencesResource")
end
dependencySet[expr.longName] = true
finalValue = "res "..encodeRes(expr.longName)
elseif expr.type == "CConstant" then
if expr.vTypes[1].longName == "Core.nullreference" then
finalValue = "null"
elseif expr.signal == "Resource" then
finalValue = "res "..encodeRes(expr.value)
else
finalValue = expr.value
end
elseif expr.type == "CMethodDelegation" then
finalValue = "res "..encodeRes(expr.method.longName)
else
if expr.type ~= "CInitializeProperties" and expr.type ~= "CInitializeArray" then
cerror(incriminate, "BadPropertyInitializerType", PrettyInternalClasses[expr.type])
end
end
elseif vType.declType == "enum" then
if expr.type ~= "CConstant" or expr.signal ~= "Enum" or not expr.enumName then
cerror(incriminate, "BadEnumeratorValueType", PrettyInternalClasses[expr.type])
end
finalValue = "'"..escapestring(expr.enumName).."'"
elseif vType.declType == "struct" then
allowConstructor = true
--if expr.type == "CStaticInstance" then
-- cerror(incriminate, "StaticInstanceInitializer")
--end
else
assert(false)
end
if finalValue == nil and allowConstructor then
if expr.type ~= "CInitializeProperties" and expr.type ~= "CInitializeArray" then
cerror(incriminate, "ExpectedConstructorInitializer", PrettyInternalClasses[expr.type])
end
if forceRef then
local subDimensions = { }
local diValue = GetInitializationValue(cs, vType, expr, false, 0, base, dependencySet, subDimensions, isAnonymous, incriminate)
local defaultInstance = DefaultInstance(cs, vType, diValue, base, subDimensions, isAnonymous)
dependencySet[defaultInstance.longName] = true
return "res "..encodeRes(defaultInstance.longName)
end
if expr.type == "CInitializeArray" then
for i,v in ipairs(expr.dimensions) do
dimensions[i] = v
end
end
finalValue = "{"..lineBreak
for idx,i in ipairs(expr.initializers) do
local dest, src
if idx ~= 1 then
finalValue = finalValue..","..lineBreak
end
local requireRef
local refType
local newIncriminate
local valueExpr
local repitchName
if vType.type == "CArrayOfType" then
refType = vType.containedType
newIncriminate = expr.incriminateNode
valueExpr = i
assert(refType)
repitchName = tostring(idx-1)
elseif vType.type == "CStructuredType" then
if i.dest.type ~= "CObjectProperty" then
cerror(incriminate, "OnlyPropertyInitializersAllowed")
end
dest = i.dest
refType = dest.property.typeOf.refType
newIncriminate = i.incriminateNode
valueExpr = i.src
repitchName = dest.property.name
else
assert(false, "Unimplemented")
end
if VTypeIsObjectReference(refType) then
requireRef = true
end
local propertyV = GetInitializationValue(cs, refType, valueExpr, requireRef, indentLevel+1, base.."."..repitchName, dependencySet, dimensions, isAnonymous, newIncriminate)
if vType.type == "CArrayOfType" then
finalValue = finalValue..indentation2..propertyV
elseif vType.type == "CStructuredType" then
if i.dest.type ~= "CObjectProperty" then
cerror(incriminate, "OnlyPropertyInitializersAllowed")
end
local dest = i.dest
local pName = dest.property.name
if RDXT_RESERVED_SYMBOLS[pName] then
pName = "'"..pName.."'"
end
finalValue = finalValue..indentation2..pName.." : "..propertyV
else
assert(false, "Unimplemented")
end
end
finalValue = finalValue..lineBreak..indentation.."}"
end
assert(finalValue ~= nil)
return finalValue
end
local function CompileInitializer(cs, i)
assert(i.uncompiledNode)
local isAnonymous
local expr
local vType
if not i.ownerType.isCompiled and not i.ownerType.finalizer.isCompiled then
return nil
end
local ownerMember = i.ownerType.namespace.symbols[i.ownerMemberName.string]
if not ownerMember then
cerror(i.ownerMemberName, "UnresolvedMemberInitializer", i.ownerMemberName.string)
end
if ownerMember.type ~= "CProperty" and ownerMember.type ~= "CStaticInstance" then
cerror(i.ownerMemberName, "UninitializableMember")
end
if not ownerMember.isCompiled or not ownerMember.typeOf.isCompiled then
return nil
end
local vType = ownerMember.typeOf.refType
if not vType.isCompiled then
return nil
end
local succeeded = true
local exprOriginalType
local succeeded, exception = pcall(function()
expr = CompileExpression(cs, i.uncompiledNode, i.ownerType.internalScope, true)
expr = AdjustValueCount(cs, expr, i.uncompiledNode, 1)
exprOriginalType = expr.vTypes[1]
expr = ConvertExpression(cs, i.uncompiledNode, expr, { vType }, nil, false )
end )
if succeeded == false then
if exception == SIGNAL_UnresolvedExpression then
return false
else
error(exception)
end
end
local requireRef
local baseName
if VTypeIsObjectReference(vType) then
requireRef = true
end
local firstIndent = 1
if ownerMember.type == "CStaticInstance" then
firstIndent = 0
requireRef = false
ownerMember.initializer = i
baseName = ownerMember.longName
isAnonymous = ownerMember.isAnonymous
-- Static instance types must be exact matches
if vType ~= exprOriginalType then
cerror(i.ownerMemberName, "ResourceInstanceIncompatible")
end
elseif ownerMember.type == "CProperty" then
local init = i.ownerType.initializersSet[ownerMember.name]
if init and init.ownerType == i.ownerType then
cerror(i.uncompiledNode, "MemberAlreadyHasDefault", ownerMember.name)
end
i.ownerType.initializersSet[ownerMember.name] = i
i.ownerType.initializers[#i.ownerType.initializers+1] = i
baseName = i.ownerType.longName.."/default."..ownerMember.name
end
i.defaultDependencySet = { }
i.defaultDimensions = { }
i.defaultValue = GetInitializationValue(cs, vType, expr, requireRef, firstIndent, baseName, i.defaultDependencySet, i.defaultDimensions, isAnonymous, i.uncompiledNode)
i.ownerMember = ownerMember
i.isCompiled = true
i.uncompiledNode = nil
return true
end
local function Property(cs, definedByType, typeOf, visibility, isConst, mustBeConst, name)
local p = {
type = "CProperty",
isCompiled = false,
definedByType = definedByType,
typeOf = typeOf,
visibility = visibility,
name = (name and name.string),
nameNode = name,
isConst = isConst,
mustBeConst = mustBeConst,
}
cs.uncompiled[#cs.uncompiled+1] = p
return p
end
local function CompileProperty(cs, p)
if not p.typeOf.isCompiled or not p.definedByType.isCompiled then
return false
end
if p.typeOf.refType.longName == varyingType then
cerror(p.name, "VaryingProperty")
end
--p.longName = p.definedByType.longName.."/properties/"..p.name
p.isCompiled = true
return true
end
local function TypeFinalizer(cs, st)
local tf = {
type = "CTypeFinalizer",
st = st,
isCompiled = false,
}
cs.uncompiled[#cs.uncompiled+1] = tf
return tf
end
local function CompileTypeFinalizer(cs, tf)
local st = tf.st
local methodsBySignature = { }
local virtualOffsetsBySignature = { }
local deletedMethods = { }
-- Make sure all methods are compiled
for _,method in ipairs(st.methods) do
if not method.isCompiled then
return false, method.nameNode
end
end
-- Make sure all interfaces are compiled and finalized
for _,i in ipairs(st.interfaces) do
local ist = i.interfaceType
if not ist.isCompiled or not ist.finalizer.isCompiled then
return false, i.incriminateNode
end
end
-- Go back through method signatures and handle overloads
for _,method in ipairs(st.methods) do
local methodSignature = method.signature
local collision = methodsBySignature[methodSignature]
local virtualIndex = #st.virtualMethods+1
-- See if there's an existing method with this name
if collision then
if collision.definedByType == method.definedByType then
cerror(method.name, "DuplicatedMethod")
end
if collision.isVirtual then
if method.isStatic then
cerror(method.name, "OverridedVirtualWithStatic")
end
if collision.returnSignature ~= method.returnSignature then
cerror(method.name, "OverrideHasDifferentReturn")
end
if not method.isVirtual and not method.isFinal then
cerror(method.name, "InvalidOverrideFlags")
end
method.vftIndex = collision.vftIndex
method.isOverriding = true
-- Replace all entries in the vtable
for vidx,vmethod in ipairs(st.virtualMethods) do
if vmethod == collision then
st.virtualMethods[vidx] = method
st.aliasVFT = nil
end
end
virtualIndex = nil
end
deletedMethods[collision] = true
end
if method.isFinal and not method.isOverriding then
cerror(method.name, "FinalMethodDoesNotOverride")
end
if method.definedByType == st then
-- New virtual method
if method.isVirtual and virtualIndex ~= nil then
method.vftIndex = virtualIndex
st.virtualMethods[virtualIndex] = method
st.aliasVFT = nil
end
end
if method.isVirtual then
method.isCalledVirtual = true
end
methodsBySignature[methodSignature] = method
end
-- Rebuild method groups
for _,mg in ipairs(st.methodGroups) do
local rebuilt = { }
for _,m in ipairs(mg.overloads) do
if not deletedMethods[m] then
rebuilt[#rebuilt+1] = m
end
end
mg.overloads = rebuilt
end
-- Rebuild the main methods list
local rebuilt = { }
for _,m in ipairs(st.methods) do
if not deletedMethods[m] then
rebuilt[#rebuilt+1] = m
end
end
st.methods = rebuilt
for _,i in ipairs(st.interfaces) do
if i.vftOffset == nil then
i.vftOffset = #st.virtualMethods+1
for _,m in ipairs(i.interfaceType.methods) do
local localMethod = methodsBySignature[m.signature]
if localMethod == nil then
cerror(i.incriminateNode, "InterfaceMethodMissing", m.signature, i.interfaceType.longName)
end
if localMethod.returnTypes.longName ~= m.returnTypes.longName then
cerror(i.incriminateNode, "InterfaceReturnTypeMismatch", m.signature)
end
st.virtualMethods[#st.virtualMethods+1] = localMethod
end
st.aliasInterfaces = nil -- Can't recycle the interfaces table
st.aliasVFT = nil
end
end
for _,m in ipairs(st.virtualMethods) do
if m.isAbstract then
st.isAbstract = true
st.abstractBlame = m
break
end
end
tf.isCompiled = true
return true
end
local function InsertProperties(cs, t, propertyNode)
local visibility = DefaultVisibility(propertyNode.accessDescriptor.visibility)
local isStatic = (propertyNode.declType.type == "resource")
local isConst = (propertyNode.accessDescriptor.const ~= nil)
local mustBeConst = (propertyNode.accessDescriptor.mustbeconst ~= nil)
if propertyNode.accessDescriptor.static then
cerror(propertyNode, "StaticProperty")
end
if propertyNode.initializers and #propertyNode.initializers.expressions ~= #propertyNode.declList.declarations then
cerror(propertyNode, "PropertyInitializerCountMismatch")
end
for idx,decl in ipairs(propertyNode.declList.declarations) do
local typeRef = TypeReference(cs, decl.type, t.internalScope)
local initializer = nil
if propertyNode.initializers then
initializer = Initializer(cs, propertyNode.initializers.expressions[idx], t, decl.name)
end
if isStatic then
local si = StaticInstance(cs, t, typeRef, visibility, decl.name, isConst, propertyNode)
si.hasInitializer = (propertyNode.initializers ~= nil)
si.isAnonymous = (propertyNode.accessDescriptor.anonymous ~= nil)
t.namespace:InsertUnique(decl.name, si)
else
local p = Property(cs, t, typeRef, visibility, isConst, mustBeConst, decl.name)
t.properties[#t.properties+1] = p
p.propertyIndex = #t.properties
t.namespace:InsertUnique(decl.name, p)
end
end
-- Don't alias properties any more
t.aliasProperties = nil
end
local function InsertTypedef(cs, t, tdNode)
local typeRef = TypeReference(cs, tdNode.specifiedType, t.internalScope)
typeRef.visibility = DefaultVisibility(tdNode.accessDescriptor.visibility)
t.namespace:InsertUnique(tdNode.name, typeRef)
end
local function InsertStructuredType(cs, t, decl)
local uncompiledType = StructuredType(cs, Namespace(t.namespace, decl.name.string), t.internalScope, decl.attribTags, decl)
t.namespace:InsertUnique(decl.name, uncompiledType)
cs.uncompiled[#cs.uncompiled+1] = uncompiledType
end
local function InsertMethod(cs, t, methodNode)
local methodName
local methodNameNode
local visibility = DefaultVisibility(methodNode.accessDescriptor.visibility)
local isStatic = (methodNode.accessDescriptor.static ~= nil)
local isIntercept = (methodNode.accessDescriptor.intercept ~= nil)
local mg
if methodNode.declType.type == "coerce" or methodNode.declType.type == "promote" then
local n = VirtualParseNode("Name", methodNode)
n.string = "#coerce"
methodNameNode = n
else
methodNameNode = methodNode.name
end
methodName = methodNameNode.string
local isArrayIntercept = (methodName == "__setindex")
if t.namespace.symbols[methodName] ~= nil then
mg = t.namespace.symbols[methodName]
if mg.type ~= "CMethodGroup" then
cerror(methodNode, "MethodCollidesWithNonMethod")
end
if mg.visibility ~= visibility then
cerror(methodNode, "MethodVisibilityMismatch")
end
if mg.isStatic ~= isStatic then
cerror(methodNode, "MethodStaticMismatch")
end
if mg.isIntercept ~= isIntercept then
cerror(methodNode, "MethodInterceptMismatch")
end
else
mg = MethodGroup(cs, methodNameNode.string, visibility, isStatic, isIntercept, isArrayIntercept, methodNameNode)
t.namespace:InsertUnique(methodNameNode, mg)
t.methodGroups[#t.methodGroups+1] = mg
end
-- Convert parameters
local parameters = { }
local returnTypes = { }
if methodNode.declType.type == "coerce" or methodNode.declType.type == "promote" then
if #methodNode.returnType.types ~= 1 then
cerror(methodNode, "CoerceDoesNotReturnOneType")
end
end
for _,typeNode in ipairs(methodNode.returnType.types) do
returnTypes[#returnTypes+1] = TypeReference(cs, typeNode, t.internalScope)
end
if methodNode.parameters ~= nil then
for _,parameterNode in ipairs(methodNode.parameters.parameters) do
local param = { }
parameters[#parameters+1] = param
param.type = TypeReference(cs, parameterNode.type, t.internalScope)
param.name = parameterNode.name
param.isConst = (parameterNode.const ~= nil)
param.isNotNull = (parameterNode.notnull ~= nil)
if param.isNotNull then
param.isConst = true
end
end
end
if isIntercept then
if not ((#parameters == 1 and #returnTypes == 0) or (#parameters == 0 and #returnTypes == 1)) then
cerror(methodNode, "InvalidInterceptFormat")
end
end
local isStatic = methodNode.accessDescriptor.static ~= nil
local isVirtual = methodNode.accessDescriptor.virtual ~= nil
local isAbstract = methodNode.accessDescriptor.abstract ~= nil
local isBranching = methodNode.accessDescriptor.branching ~= nil
local isNative = methodNode.accessDescriptor.native ~= nil
local isFinal = methodNode.accessDescriptor.final ~= nil
local isConst = methodNode.accessDescriptor.const ~= nil
if isAbstract and not isVirtual then
cerror(methodNode, "NonVirtualAbstract")
end
if t.declType == "interface" then
if isStatic then
cerror(methodNode, "StaticMethodInInterface")
end
if isVirtual then
cerror(methodNode, "VirtualMethodInInterface")
end
if isAbstract then
cerror(methodNode, "AbstractMethodInInterface")
end
isAbstract = true
isVirtual = true
elseif t.declType == "struct" then
if isVirtual then
cerror(methodNode, "VirtualMethodInStructure")
end
end
if isAbstract and methodNode.codeBlockCacheID then
cerror(methodNode, "AbstractMethodHasCode")
end
if (not isAbstract) and (not isNative) and (not methodNode.codeBlockCacheID) then
cerror(methodNode, "MethodMissingCode")
end
if isArrayIntercept and #returnTypes ~= 0 then
cerror(methodNode, "SetIndexWithReturnValue")
end
local parameterList = ParameterList(cs, parameters)
local method = Method(cs, methodNameNode, "methods", t, returnTypes, parameterList, visibility, methodNode.declType, methodNode.codeBlockCacheID,
isStatic, isVirtual, isAbstract, isNative, isIntercept, isArrayIntercept, isBranching, isFinal, isConst)
t.methods[#t.methods+1] = method
mg.overloads[#mg.overloads+1] = method
end
local function InterfaceImplementation(cs, t, incriminate)
assert(t)
return {
type = "CInterfaceImplementation",
interfaceType = t,
incriminateNode = incriminate,
--vftOffset = ???
}
end
-- Returns true if any progress is made on the type
local function CompileType(cs, t)
local madeProgress = false
t.visibility = DefaultVisibility(t.uncompiledNode.accessDescriptor.visibility)
t.declType = t.uncompiledNode.declType.string
t.byVal = (t.uncompiledNode.accessDescriptor.byVal ~= nil)
t.mustBeRef = (t.uncompiledNode.accessDescriptor.mustBeRef ~= nil)
t.isFinal = (t.uncompiledNode.accessDescriptor.final ~= nil)
t.isAbstract = (t.uncompiledNode.accessDescriptor.abstract ~= nil)
t.isLocalized = (t.uncompiledNode.accessDescriptor.localized ~= nil)
local prefixes = { }
local longName = t.uncompiledNode.name.string
local ns = t.namespace.owner
while ns ~= nil do
if ns.name ~= nil then
prefixes[#prefixes+1] = ns.prefix
longName = ns.name.."."..longName
end
ns = ns.owner
end
local prettyName = longName
-- Unwind prefixes
while #prefixes > 0 do
local pfidx = #prefixes
longName = prefixes[pfidx]..longName
prefixes[pfidx] = nil
end
if t.templateParameters then
prettyName = prettyName..":<"
longName = "#Tmpl."..longName..":<"
for idx,tp in ipairs(t.templateParameters) do
if idx ~= 1 then
longName = longName..","
prettyName = prettyName..","
end
longName = longName..tp.longName
prettyName = prettyName..tp.prettyName
end
longName = longName..">"
prettyName = prettyName..">"
t.isFromTemplate = true
end
t.longName = longName
t.prettyName = prettyName
if not t.isTemplate then
local parentClass = nil
local interfaces = { }
if t.declType == "class" and t.uncompiledNode.parent == nil and longName ~= "Core.Object" then
parentClass = cs.gst["Core.Object"]
if parentClass == nil then
return false -- Core.Object not defined yet
end
elseif t.uncompiledNode.parent then
local parentClassRef = TypeReference(cs, t.uncompiledNode.parent, t.scope, false)
CompileTypeReference(cs, parentClassRef)
if not parentClassRef.isCompiled then
return false -- Unresolved
end
parentClass = parentClassRef.refType
end
-- Check now to avoid partial compilation
if t.uncompiledNode.interfaces then
for _,iexpr in ipairs(t.uncompiledNode.interfaces.expressions) do
local interfaceType = ExpressionToType(cs, iexpr, t.scope)
if interfaceType == nil then
return false
end
if not interfaceType.isCompiled then
return false
end
interfaces[#interfaces+1] = InterfaceImplementation(cs, interfaceType, iexpr)
end
end
if parentClass then
if parentClass.type ~= "CStructuredType" then
cerror(t.uncompiledNode, "ExtendedNonClass")
end
if not parentClass.isCompiled or not parentClass.finalizer.isCompiled then
-- Can't extend until the type is fully defined with a property layout and vtable
return false
end
-- Won't have a declType until this is compiled
if parentClass.declType ~= "class" then
cerror(t.uncompiledNode, "ExtendedNonClass")
end
if parentClass.isTemplate then
cerror(t.uncompiledNode, "ExtendedTemplate")
end
if t.declType ~= "class" then
cerror(t.uncompiledNode, "NonClassExtended")
end
if parentClass.isFinal then
cerror(t.uncompiledNode, "ExtendedFinalClass")
end
t.parentType = parentClass
-- Import everything
ExtendClass(cs, t, parentClass)
end
-- Insert new interfaces
local implementedInterfaces = { }
for _,i in ipairs(interfaces) do
if i.interfaceType.type ~= "CStructuredType" or i.interfaceType.declType ~= "interface" then
cerror(t.uncompiledNode, "ImplementedNonInterface", i.interfaceType.longName)
end
if implementedInterfaces[i.interfaceType] then
cerror(t.uncompiledNode, "DuplicateImplementations", i.interfaceType.name.string)
end
if not t.implementedInterfaces[i.interfaceType] then
t.interfaces[#t.interfaces+1] = i
t.implementedInterfaces[i.interfaceType] = true
end
implementedInterfaces[i.interfaceType] = true
end
-- Insert new members
if t.uncompiledNode.typeMembers then
for _,decl in ipairs(t.uncompiledNode.typeMembers.members) do
if decl.type == "DefaultDeclList" then
for _,ddecl in ipairs(decl.defaultDecls) do
Initializer(cs, ddecl.expression, t, ddecl.fieldName)
end
elseif decl.type == "MemberDecl" then
if decl.declType.type == "function" or decl.declType.type == "coerce" or decl.declType.type == "promote" then
InsertMethod(cs, t, decl)
elseif decl.declType.type == "property" or decl.declType.type == "resource" then
InsertProperties(cs, t, decl)
elseif decl.declType.type == "typedef" then
InsertTypedef(cs, t, decl)
elseif structuredTypeDeclTypes[decl.declType.type] then
InsertStructuredType(cs, t, decl)
elseif decl.declType.type == "delegate" then
local uncompiledType = DelegateType(cs, t.namespace, t.internalScope, decl, t)
t.namespace:InsertUnique(decl.name, uncompiledType)
cs.uncompiled[#cs.uncompiled+1] = uncompiledType
else
cerror(decl, "UnsupportedDeclType", decl.declType.type)
end
else
cerror(decl, "UnsupportedTypeMemberType", decl.declType.type)
end
end
end
if t.uncompiledNode.enumerants then
local enumIndex = -1
local zeroDefined = false
local usedValues = { }
local finalEnumerants = { }
local finalInserts = { }
for _,e in ipairs(t.uncompiledNode.enumerants.enumerants) do
if e.initializer then
local initializer
local succeeded, exception = pcall(function()
initializer = CompileExpression(cs, e.initializer, t.internalScope, true)
end )
if succeeded == false then
if exception == SIGNAL_UnresolvedExpression then
return nil
else
error(exception)
end
end
if initializer.type ~= "CConstant" or initializer.signal ~= "Value" or initializer.vTypes[1].longName ~= enumType then
cerror(e.initializer, "EnumInitializerNotInteger")
end
enumIndex = tonumber(initializer.value)
else
enumIndex = enumIndex + 1
end
local constVal = Constant(cs, t, enumIndex, "Enum")
constVal.enumName = e.name.string
if usedValues[enumIndex] then
cerror(e.name, "DuplicateEnumValue", tostring(enumIndex), e.name.string)
end
usedValues[enumIndex] = true
if enumIndex == 0 then
zeroDefined = true
end
finalEnumerants[#finalEnumerants+1] = {
type = "CEnumerant",
name = e.name.string,
value = enumIndex,
constVal = constVal,
nameToken = e.name,
}
end
-- Sort enumerants
table.sort(finalEnumerants, function(a, b)
return a.value < b.value
end )
t.enumerants = finalEnumerants
for _,fe in ipairs(finalEnumerants) do
t.namespace:InsertUnique(fe.name, fe.constVal, fe.nameToken)
end
if not zeroDefined then
cerror(t.uncompiledNode, "MissingZeroEnumerant")
end
end
t.uncompiledNode = nil -- Don't need this any more
end
t.isCompiled = true
t.finalizer = TypeFinalizer(cs, t)
cs.gst[longName] = t
return true
end
local function CheckCircularity(cs, branch, root, incriminate)
if branch == root then
cerror(incriminate, "VerifiedCircularDependency", root.prettyName)
end
if branch == nil then
branch = root
if branch.type ~= "CStructuredType" or (branch.declType ~= "struct" and branch.declType ~= "class") then
return
end
end
if branch.parentType ~= nil then
CheckCircularity(cs, branch.parentType, root, incriminate)
end
for _,p in ipairs(branch.properties) do
local pt = p.typeOf.refType
if pt.type == "CStructuredType" and pt.declType == "struct" then
CheckCircularity(cs, pt, root, incriminate)
end
end
end
local function CheckByVals(cs, st, incriminate)
if st.mustBeRef then
cerror(incriminate, "UnalignableByVal")
end
for _,p in ipairs(st.properties) do
local pt = p.typeOf.refType
if pt.type == "CStructuredType" and pt.declType == "struct" then
CheckByVals(cs, pt, incriminate)
end
end
end
CompileTypeShells = function(cs)
local newTypes = { }
if #cs.uncompiled == 0 then
return
end
cs.compilingTypes = true
while true do
local uncompiled = cs.uncompiled
if #uncompiled == 0 then
break
end
local compiledOK
local madeAnyProgress = false
local incriminate = nil
cs.uncompiled = { }
for _,u in ipairs(uncompiled) do
compiledOK = false
if u.isCompiled then
-- Precompiled
compiledOK = true
elseif u.type == "CStructuredType" then
incriminate = u.uncompiledNode
compiledOK = CompileType(cs, u)
if compiledOK then
newTypes[#newTypes+1] = { st = u, incriminate = incriminate }
end
elseif u.type == "CMethodGroup" then
incriminate = u.incriminate
compiledOK = CompileMethodGroup(cs, u)
elseif u.type == "CMethod" then
incriminate = u.name
compiledOK = CompileMethod(cs, u)
elseif u.type == "CTypeTuple" then
compiledOK = CompileTypeTuple(cs, u)
elseif u.type == "CParameterList" then
compiledOK = CompileParameterList(cs, u)
elseif u.type == "CTypeReference" then
incriminate = u.node
compiledOK = CompileTypeReference(cs, u)
elseif u.type == "CProperty" then
incriminate = u.nameNode
compiledOK = CompileProperty(cs, u)
elseif u.type == "CStaticInstance" then
incriminate = u.nameNode
compiledOK = CompileStaticInstance(cs, u)
elseif u.type == "CTypeFinalizer" then
compiledOK, incriminate = CompileTypeFinalizer(cs, u)
elseif u.type == "CArrayOfType" then
incriminate = u.incriminateNode
compiledOK = CompileArrayOfType(cs, u)
elseif u.type == "CStaticDelegateType" or u.type == "CBoundDelegateType" then
incriminate = u.incriminateNode
compiledOK = CompileDelegateType(cs, u)
elseif u.type == "CInitializer" then
incriminate = u.uncompilednode
compiledOK = CompileInitializer(cs, u)
else
error("Unknown uncompiled node type: "..u.type)
end
if compiledOK == true then
madeAnyProgress = true
else
-- Reinsert and try again
cs.uncompiled[#cs.uncompiled+1] = u
end
end
if madeAnyProgress == false then
cerror(incriminate, "CircularDependency")
end
end
cs.compilingTypes = false
-- Enforce non-circularity
for _,nt in ipairs(newTypes) do
local st = nt.st
CheckCircularity(cs, nil, st, nt.incriminate)
if st.type == "CStructuredType" and st.declType == "struct" and st.byVal then
CheckByVals(cs, st, nt.incriminate)
end
end
end
-- -----------------------------------------------------------------------------------------------
LocalVariable = function(method, rType, isPointer, isConstant, note)
assert(type(rType) == "table")
assert(rType.type == "CStructuredType" or rType.type == "CArrayOfType" or rType.type == "CStaticDelegateType" or rType.type == "CBoundDelegateType")
assert(method == nil or method.type == "CMethod")
return {
type = "CLocalVariable",
isPointer = isPointer,
method = method,
accessModes = { isPointer and (isConstant and "CP" or "P") or "L" },
vTypes = { rType },
note = note,
--stackIndex = ?
}
end
local function CodeBlock(cs, ownerNamespace, ownerScope, initialLocalIndex)
local cb = Scope(ownerScope)
cb.type = "CCodeBlock"
cb.locals = { }
cb.CreateLocal = function(self, ces, localVar, name, hide)
assert(ces.opstackIndex == 0) -- Can't create locals in the middle of an operation except as temporaries
localVar.stackIndex = ces.localCount
ces.localCount = ces.localCount + 1
self.locals[#self.locals+1] = localVar
if name ~= nil then
-- See if this is in a parent block
local checkBlock = self.owner
while checkBlock ~= nil and checkBlock.type == "CCodeBlock" do
if checkBlock.symbols[name.string] ~= nil then
cwarning(name, "MaskedLocal", name.string)
end
checkBlock = checkBlock.owner
end
assert(checkBlock ~= nil and (checkBlock.type == "CMemberLookupScope" or checkBlock.type == "CInstanciatedNamespace"), checkBlock.type)
self:InsertUnique(name.string, localVar, name)
if hide then
localVar.invisibleSymbol = true
end
end
end
return cb
end
local function GuaranteeOuterBlock(cs, ces, ownerNamespace, ownerScope, initialLocalIndex)
local ob = CodeBlock(cs, ownerNamespace, ownerScope, initialLocalIndex)
ob.labelPrefix = ces:CreateLabel()
ob.returnPath = ob.labelPrefix.."_greturn"
ob.defaultPath = ob.labelPrefix.."_gdefaultpath"
ob.codePaths = { ob.returnPath, ob.defaultPath }
ob.codePathEscapes = { false, false } -- Label to jump to after running the guaranteed statements
ob.labelToCodePath = { }
ob.guaranteeLocals = 0
return ob
end
local function FindGuaranteeingBlock(cs, block)
while not block.isRootLevel do
block = block.owner
if block == nil then
break
end
if block.isGuaranteeInner then
return block.owner
end
end
return nil
end
local function StartGuaranteeInnerBlock(cs, ces, outerBlock)
local lbl = outerBlock.labelPrefix
local catchLabel = lbl.."_gcatch"
local endTryLabel = lbl.."_gendtry"
local method = BlockMethod(outerBlock)
local ownerGuarantee = FindGuaranteeingBlock(cs, outerBlock)
if ownerGuarantee == nil then
outerBlock.carriedExceptionLocal = LocalVariable(method, cs.gst["Core.Exception"], false)
ces:AddInstruction( { op = "alloclocal", res1 = "Core.Exception", str1 = "guarantee carried exception" } )
outerBlock:CreateLocal(ces, outerBlock.carriedExceptionLocal)
outerBlock.codePathLocal = LocalVariable(method, cs.gst["Core.int"], false)
ces:AddInstruction( { op = "alloclocal", res1 = "Core.int", str1 = "guarantee code path" } )
outerBlock:CreateLocal(ces, outerBlock.codePathLocal)
outerBlock.guaranteeLocals = 2
outerBlock.returnValueHolders = { }
for idx,ref in ipairs(method.returnTypes.typeReferences) do
local returnType = ref.refType
local rvHolder = LocalVariable(method, returnType, false)
ces:AddInstruction( { op = "alloclocal", res1 = "Core.int", str1 = "guarantee return value "..idx } )
outerBlock:CreateLocal(ces, rvHolder)
outerBlock.returnValueHolders[#outerBlock.returnValueHolders + 1] = rvHolder
outerBlock.guaranteeLocals = outerBlock.guaranteeLocals + 1
end
else
outerBlock.carriedExceptionLocal = ownerGuarantee.carriedExceptionLocal
outerBlock.codePathLocal = ownerGuarantee.codePathLocal
outerBlock.returnValueHolders = ownerGuarantee.returnValueHolders
end
ces:AddInstruction( { op = "try", str1 = catchLabel, str2 = endTryLabel } )
ces:Discharge()
local innerBlock = CodeBlock(cs, nil, outerBlock, outerBlock.localIndex)
innerBlock.isGuaranteeInner = true
return innerBlock
end
local function CloseGuaranteeInnerBlock(cs, ces, innerBlock)
local outerBlock = innerBlock.owner
local lbl = outerBlock.labelPrefix
ces:Discharge()
-- Fall-through code goes to the default path
ces:AddInstruction( { op = "label", str1 = lbl.."_gendtry" } )
ces:AddInstruction( { op = "enablepath", str1 = outerBlock.defaultPath } )
ces:AddConstantInstruction("Core.int", standardGuaranteeBlocks.DEFAULT, "Value")
ces:AddInstruction( { op = "localref", int1 = outerBlock.codePathLocal.stackIndex } )
ces:AddInstruction( { op = "move" } )
ces:AddInstruction( { op = "jump", str1 = lbl.."_gfinally" } )
-- Exceptions go to the exception-carrying path
ces:AddInstruction( { op = "label", str1 = lbl.."_gcatch" } )
ces:AddInstruction( { op = "catch", res1 = "Core.Exception" } )
ces:AddInstruction( { op = "localref", int1 = outerBlock.carriedExceptionLocal.stackIndex } )
ces:AddInstruction( { op = "move" } )
ces:AddConstantInstruction("Core.int", standardGuaranteeBlocks.EXCEPTION, "Value")
ces:AddInstruction( { op = "localref", int1 = outerBlock.codePathLocal.stackIndex } )
ces:AddInstruction( { op = "move" } )
ces:AddInstruction( { op = "jump", str1 = lbl.."_gfinally" } )
ces:Discharge()
-- Emit flow path labels
for pathIdx,path in ipairs(outerBlock.codePaths) do
local pathName = path
ces:AddInstruction( { op = "label", str1 = pathName } )
ces:AddInstruction( { op = "enablepath", str1 = pathName } )
ces:AddConstantInstruction("Core.int", tostring(pathIdx), "Value")
ces:AddInstruction( { op = "localref", int1 = outerBlock.codePathLocal.stackIndex } )
ces:AddInstruction( { op = "move" } )
ces:AddInstruction( { op = "jump", str1 = lbl.."_gfinally" } )
end
ces:AddInstruction( { op = "label", str1 = lbl.."_gfinally" } )
ces:Discharge()
end
local function AddLabelToGuarantee(cs, block, label)
local codePathIdx = block.labelToCodePath[label]
if codePathIdx == nil then
codePathIdx = #block.codePaths + 1
block.codePaths[codePathIdx] = block.labelPrefix.."_gpath_"..label
block.codePathEscapes[codePathIdx] = label
block.labelToCodePath[label] = codePathIdx
end
return assert(block.codePaths[codePathIdx])
end
local function CloseGuaranteeOuterBlock(cs, ces, block)
local lbl = block.labelPrefix
ces:Discharge()
local owner = FindGuaranteeingBlock(cs, block)
-- Carry exceptions
ces:AddInstruction( { op = "localref", int1 = block.codePathLocal.stackIndex } )
ces:AddInstruction( { op = "load" } )
ces:AddConstantInstruction("Core.int", standardGuaranteeBlocks.EXCEPTION, "Value")
ces:AddInstruction( { op = "jumpifnotequal", str1 = lbl.."_gnocarry", str2 = lbl.."_gcarry" } )
ces:AddInstruction( { op = "label", str1 = lbl.."_gcarry" } )
ces:AddInstruction( { op = "localref", int1 = block.carriedExceptionLocal.stackIndex } )
ces:AddInstruction( { op = "load" } )
ces:AddInstruction( { op = "throw" } )
ces:AddInstruction( { op = "label", str1 = lbl.."_gnocarry" } )
-- Emit code exit paths
for pathIdx,path in ipairs(block.codePaths) do
ces:AddInstruction( { op = "checkpathusage", str1 = path.."_gpathunused", str2 = path } )
ces:AddInstruction( { op = "localref", int1 = block.codePathLocal.stackIndex } )
ces:AddInstruction( { op = "load" } )
ces:AddConstantInstruction("Core.int", tostring(pathIdx), "Value")
ces:AddInstruction( { op = "jumpifnotequal", str1 = path.."_gpathunused", str2 = path.."_gpathtaken" } )
ces:AddInstruction( { op = "label", str1 = path.."_gpathtaken" } )
if path == block.returnPath then
-- Special code for return path
if owner then
-- Has an owner, the value holders should be populated
ces:AddInstruction( { op = "jump", str1 = owner.returnPath } )
else
-- No owner, exit the function
for _,rvLocal in ipairs(block.returnValueHolders) do
ces:AddInstruction( { op = "localref", int1 = rvLocal.stackIndex } )
end
ces:AddInstruction( { op = "return", int1 = #block.returnValueHolders } )
end
elseif path == block.defaultPath then
ces:AddInstruction( { op = "jump", str1 = block.defaultPath } )
else
EmitAliasableJump(cs, ces, block, block.codePathEscapes[pathIdx])
end
ces:AddInstruction( { op = "label", str1 = path.."_gpathunused" } )
end
ces:AddInstruction( { op = "deadcode" } )
for i=1,block.guaranteeLocals do
ces:AddInstruction( { op = "removelocal" } )
end
ces:AddInstruction( { op = "label", str1 = block.defaultPath } )
ces:Discharge()
end
AdjustValueCount = function(cs, cnode, incriminate, goalCount, noTruncationWarning)
if cnode.vTypes == nil then
cerror(incriminate, "ExpectedValue")
end
if #cnode.vTypes < goalCount then
cerror(incriminate, "TooFewValues", tostring(goalCount), tostring(#cnode.vTypes))
end
if #cnode.vTypes == goalCount then
return cnode -- Nothing to do
end
local vTypes = { }
local accessModes = { }
for i=1,goalCount do
vTypes[i] = cnode.vTypes[i]
accessModes[i] = cnode.accessModes[i]
end
if (not noTruncationWarning) and cnode.type == "CMultipleValues" then
local firstExprIndex = 1
for idx,expr in ipairs(cnode.expressions) do
if firstExprIndex > goalCount then
cwarning(incriminate, "TruncatedValue")
break
end
firstExprIndex = firstExprIndex + #expr.vTypes
end
end
return {
type = "CAdjustValueCount",
accessModes = accessModes,
vTypes = vTypes,
expression = cnode
}
end
local function EmitMethodCall(ces, m, explicit, delegateExpr)
if delegateExpr then
ces:AddInstruction( { op = "calldelegate", res1 = m.longName } )
elseif m.vftIndex and not explicit then
ces:AddInstruction( { op = "callvirtual", res1 = m.longName } )
elseif m.type == "CBoundDelegateMarshal" then
ces:AddInstruction( { op = "callvirtual", res1 = m.invokeName } )
else
assert(m.type == "CMethod")
ces:AddInstruction( { op = "call", res1 = m.longName } )
end
end
setglobal("VTypeIsObjectReference", function(vType)
if vType.type == "CStructuredType" and (vType.declType == "class" or vType.declType == "interface") then
return true
end
if vType.type == "CArrayOfType" or vType.type == "CStaticDelegateType" then
return true
end
return false
end )
AMIsPointer = function(am)
return (am == "P" or am == "CP" or am == "*P")
end
setglobal("VTypeIsRefStruct", function(vType)
if vType.type == "CStructuredType" and vType.declType == "struct" and not vType.byVal then
return true
else
return false
end
end )
local function PushShellSpace(ces, vType)
if vType.type == "CStructuredType" and VTypeIsRefStruct(vType) then
-- This requires a temporary
local temp = ces:AddTemporary(vType)
ces:AddInstruction( { op = "localref", int1 = temp.stackIndex } )
ces:AddInstruction( { op = "pinlocal" } )
ces:Push(1, temp)
else
ces:AddInstruction( { op = "pushempty", res1 = vType.longName } )
ces:Push(1)
end
end
-- Emits expression, auto-converts if necessary
-- This can only actually convert one value, the one before the first value being dismantled, and it may not convert that either
-- Because R-values can contain multiple values, they may be partially "dismantled" to convert arguments:
-- Conversion types that can be done in-place (polymorphic cast, P-to-R) dismantle everything after them
-- Conversion types that require a previous stack entry (coerce) dismantle everything after them and will dismantle themselves if not first
-- R-to-P dismantles itself and everything after
-- Direct casts do not dismantle
local function EmitConvertedExpression(cs, expr, targetVTypes, targetAccessModes, ces)
assert(#expr.vTypes == #targetVTypes)
assert(#expr.vTypes ~= 0)
assert(#expr.accessModes == #expr.vTypes)
local firstDismantle
local convertOperation
for idx,svt in ipairs(expr.vTypes) do
local sam = expr.accessModes[idx]
local tvt = targetVTypes[idx]
local tam
if targetAccessModes then
tam = targetAccessModes[idx]
assert(tam)
end
if tam == "*" then
tam = nil
end
--assert(tam ~= "L")
local matchability = CastMatchability(svt, tvt, true)
if matchability == matchLevels.EXACT or matchability == matchLevels.DIRECT then
if sam == tam or tam == nil then
-- Nothing to do
elseif AMIsPointer(sam) and (tam == "CP" or tam == "*P") then
-- Nothing to do
elseif sam == "L" and AMIsPointer(tam) then
convertOperation = "PinL"
firstDismantle = idx+1
break
elseif sam == "L" and tam == "R" then
convertOperation = "LoadL"
firstDismantle = idx+1
break
elseif AMIsPointer(sam) and tam == "R" then
convertOperation = "PtoR"
firstDismantle = idx+1
break
elseif sam == "R" and AMIsPointer(tam) then
firstDismantle = idx -- RtoP is a dismantle followed by a secondary PinL
break
else
-- NOTE: Errors are never caught at this point, filter them out in ConvertExpression!
assert(false, "Access modes unconvertible, failed to properly convert "..svt.longName.." to "..tvt.longName..", match level "..matchability..", access modes "..sam.."-->"..tam)
end
elseif matchability == matchLevels.LOSSLESS or matchability == matchLevels.LOSSY then
if svt.type == "CStaticDelegateType" and tvt.type == "CBoundDelegateType" then
convertOperation = "BindStaticDelegate"
firstDismantle = idx+1
break
else
assert(svt.type == "CStructuredType")
if idx == 1 then
if matchability == matchLevels.LOSSLESS and tvt.type == "CStructuredType" and TypeImplementsInterface(svt, tvt) then
convertOperation = "PolymorphicCast"
elseif matchability == matchLevels.LOSSLESS and svt.declType == "interface" and tvt.longName == "Core.Object" then
convertOperation = "PolymorphicCast"
else
convertOperation = "Coerce"
end
firstDismantle = idx+1
break
else
firstDismantle = idx -- Can only coerce the first parameter, anything else gets dismantled
end
end
break
elseif matchability == matchLevels.POLYMORPHIC then
convertOperation = "PolymorphicCast"
firstDismantle = idx+1
break
elseif matchability == matchLevels.VARYING then
if sam == "L" and tam == "V" then
convertOperation = "PinLV"
firstDismantle = idx+1
elseif sam == "P" and tam == "V" then
convertOperation = "PtoV"
firstDismantle = idx+1
elseif sam == "R" and tam == "V" then
firstDismantle = idx
break
else
io.stderr:write("SAM: "..sam.." TAM: "..tam.."\n")
assert(false)
end
else
assert(false)
end
end
local cidx
if firstDismantle ~= nil then
cidx = firstDismantle - 1
end
-- Leave space for coerce
if convertOperation == "Coerce" then
-- Add space for the coercion
PushShellSpace(ces, targetVTypes[1])
end
-- Emit the actual values
EmitValues(cs, expr, ces, true)
if convertOperation == "PinL" then
ces:AddInstruction( { op = "pinlocal" } )
return
elseif convertOperation == "LoadL" then
ces:AddInstruction( { op = "load" } )
-- Cycle the opstack to remove the reference to this local
ces:Pop()
ces:Push(1)
return
elseif convertOperation == "PinLV" then
ces:AddInstruction( { op = "pinlocal" } )
ces:AddInstruction( { op = "tovarying" } )
return
end
local dismantledTemporaries = { }
-- Dismantle everything else
if firstDismantle then
local dismantlingIndex = #expr.vTypes
while dismantlingIndex >= firstDismantle do
local temp = ces:AddTemporary(expr.vTypes[dismantlingIndex])
ces:AddInstruction( { op = "localref", int1 = temp.stackIndex } )
if expr.accessModes[dismantlingIndex] == "R" then
ces:AddInstruction( { op = "move" } )
ces:Pop()
elseif expr.accessModes[dismantlingIndex] == "P" then
ces:AddInstruction( { op = "move" } )
ces:Pop()
else
assert(false, "COMPILER ERROR: Dismantled a localref, localrefs can only be singular expressions")
end
dismantledTemporaries[dismantlingIndex] = temp
dismantlingIndex = dismantlingIndex - 1
end
end
if convertOperation ~= nil then
if convertOperation == "Coerce" then
local fromType = expr.vTypes[cidx]
local toType = targetVTypes[cidx]
local tam
if targetAccessModes == nil then
tam = "*"
else
tam = targetAccessModes[cidx]
end
local coerceMethod = FindCoerce(fromType, toType, true)
if coerceMethod == nil then
coerceMethod = FindCoerce(fromType, toType, false)
assert(coerceMethod)
end
local rt = coerceMethod.actualParameterList.parameters[1].type.refType
if VTypeIsRefStruct(rt) then
-- To P
if expr.accessModes[cidx] == "L" then
ces:AddInstruction( { op = "pinlocal" } )
elseif expr.accessModes[cidx] == "R" then
local temp = ces:AddTemporary(rt)
ces:AddInstruction( { op = "localref", int1 = temp.stackIndex } )
ces:AddInstruction( { op = "move" } )
ces:Pop()
ces:AddInstruction( { op = "localref", int1 = temp.stackIndex } )
ces:AddInstruction( { op = "pinlocal" } )
ces:Push(1, temp)
end
else
-- To R
if expr.accessModes[cidx] == "L" or
AMIsPointer(expr.accessModes[cidx]) then
ces:AddInstruction( { op = "load" } )
-- Cycle the opstack to remove the reference to this local
ces:Pop()
ces:Push(1)
else
assert(expr.accessModes[cidx] == "R", "Expr wasn't R, it was "..expr.accessModes[cidx])
end
end
EmitMethodCall(ces, coerceMethod)
ces:Pop()
if VTypeIsRefStruct(toType) then
assert(tam == "P" or tam == "*")
else
-- Value struct on the stack
if tam == "P" then
local temp = ces:AddTemporary(toType)
ces:AddInstruction( { op = "localref", int1 = temp.stackIndex } )
ces:AddInstruction( { op = "move" } )
ces:AddInstruction( { op = "localref", int1 = temp.stackIndex } )
ces:AddInstruction( { op = "pinlocal" } )
ces:Pop()
ces:Push(1, temp)
else
assert(tam == "R" or tam == "*")
end
end
elseif convertOperation == "PtoR" then
ces:AddInstruction( { op = "load" } )
-- Cycle the opstack to remove the reference to this local
ces:Pop()
ces:Push(1)
elseif convertOperation == "PtoV" then
ces:AddInstruction( { op = "tovarying" } )
elseif convertOperation == "PolymorphicCast" then
local exprAM = expr.accessModes[cidx]
if exprAM == "P" or exprAM == "CP" or exprAM == "L" then
-- Load from pointer or local if needed
ces:AddInstruction( { op = "load" } )
-- Cycle the opstack to remove the reference to this local
ces:Pop()
ces:Push(1)
else
assert(exprAM == "R")
end
ces:AddInstruction( { op = "cast", res1 = targetVTypes[cidx].longName } )
local tam = targetAccessModes[cidx]
assert(tam == "R" or tam == "*" or tam == nil, "Polymorphic cast requested to a non-R-value")
elseif convertOperation == "BindStaticDelegate" then
local fromType = expr.vTypes[cidx]
local toType = targetVTypes[cidx]
local tam
if targetAccessModes == nil then
tam = "*"
else
tam = targetAccessModes[cidx]
end
if expr.accessModes[cidx] == "L" or
expr.accessModes[cidx] == "P" then
ces:AddInstruction( { op = "load" } )
-- Cycle the opstack to remove the reference to this local
ces:Pop()
ces:Push(1)
else
assert(expr.accessModes[cidx] == "R")
end
local bdTemp = ces:AddTemporary(toType)
local glue = MarshalForBoundDelegate(cs, toType, fromType)
ces:AddInstruction( { op = "newinstanceset", int1 = bdTemp.stackIndex, intVar = { "0" }, res1 = glue.longName } )
ces:Pop()
ces:AddInstruction( { op = "localref", int1 = bdTemp.stackIndex } )
ces:Push(1, bdTemp)
if tam == "P" then
ces:AddInstruction( { op = "pinlocal" } )
else
assert(tam == "R" or tam == "*")
end
else
assert(false)
end
end
if firstDismantle then
for i=firstDismantle,#expr.vTypes do
-- Re-emit dismantled values
local tam
if targetAccessModes then
tam = targetAccessModes[i]
else
tam = "*"
end
EmitConvertedExpression(cs, dismantledTemporaries[i], { targetVTypes[i] }, { tam }, ces)
end
end
end
local EmitBooleanToLogical = function(cs, expr, ces, trueLabel, falseLabel)
local boolType = cs.gst["Core.bool"]
assert(boolType)
assert(expr.vTypes[1] == boolType)
assert(expr.accessModes[1] == "R")
if expr.type == "CConstant" and expr.vTypes[1] == boolType then
-- Optimize out static branches
if tostring(expr.value) == "true" then
ces:AddInstruction( { op = "jump", str1 = trueLabel } )
else
assert(tostring(expr.value) == "false")
ces:AddInstruction( { op = "jump", str1 = falseLabel } )
end
end
EmitValues(cs, expr, ces, false)
ces:AddInstruction( { op = "jumpiftrue", str1 = trueLabel, str2 = falseLabel } )
ces:Pop()
end
local function EmitLogical(cs, expr, ces, trueLabel, falseLabel)
if expr.type == "CMethodCall" and expr.method.isBranching then
EmitValues(cs, expr.parameters, ces)
ces:AddInstruction( { op = "jumpif", res1 = expr.method.longName, str1 = trueLabel, str2 = falseLabel } )
ces:Pop(#expr.method.actualParameterList.parameters)
elseif expr.type == "CLogicalNotNode" then
EmitLogical(cs, expr.expr, ces, falseLabel, trueLabel)
elseif expr.type == "CLogicalAndNode" then
local evaluateSecondLabel = ces:CreateLabel().."_and"
EmitLogical(cs, expr.leftExpr, ces, evaluateSecondLabel, falseLabel)
ces:AddInstruction( { op = "label", str1 = evaluateSecondLabel } )
EmitLogical(cs, expr.rightExpr, ces, trueLabel, falseLabel)
elseif expr.type == "CLogicalOrNode" then
local evaluateSecondLabel = ces:CreateLabel().."_or"
EmitLogical(cs, expr.leftExpr, ces, trueLabel, evaluateSecondLabel)
ces:AddInstruction( { op = "label", str1 = evaluateSecondLabel } )
EmitLogical(cs, expr.rightExpr, ces, trueLabel, falseLabel)
elseif expr.type == "CEqualityCompare" then
local nullCheckExpr
if expr.leftExpr.type == "CConstant" and expr.leftExpr.signal == "NullRef" then
nullCheckExpr = expr.rightExpr
elseif expr.rightExpr.type == "CConstant" and expr.rightExpr.signal == "NullRef" then
nullCheckExpr = expr.leftExpr
end
if nullCheckExpr ~= nil then
if nullCheckExpr.type == "CConstant" and nullCheckExpr.signal == "NullRef" then
ces:AddInstruction( { op = "jump", str1 = trueLabel } )
else
EmitValues(cs, nullCheckExpr, ces, true)
local instrOp
if expr.operator == "__eq" then
instrOp = "jumpifnull"
elseif expr.operator == "__ne" then
instrOp = "jumpifnotnull"
else
assert(false)
end
ces:AddInstruction( { op = instrOp, str1 = trueLabel, str2 = falseLabel } )
ces:Pop(1)
end
else
EmitValues(cs, expr.leftExpr, ces, true)
EmitValues(cs, expr.rightExpr, ces, true)
local instrOp
if expr.operator == "__eq" then
instrOp = "jumpifequal"
elseif expr.operator == "__ne" then
instrOp = "jumpifnotequal"
else
assert(false)
end
ces:AddInstruction( { op = instrOp, str1 = trueLabel, str2 = falseLabel } )
ces:Pop(2)
end
elseif expr.type == "CCheckCast" then
EmitValues(cs, expr.expression, ces, false)
ces:AddInstruction( { op = "res", res1 = expr.checkType.longName } )
ces:AddInstruction( { op = "jumpif", res1 = "Core.Object/methods/CanConvertTo(notnull Core.RDX.Type)", str1 = trueLabel, str2 = falseLabel } )
ces:Pop(1)
else
EmitBooleanToLogical(cs, expr, ces, trueLabel, falseLabel)
end
end
local EmitLogicalToBoolean = function(cs, expr, ces)
ces:AddInstruction( { op = "pushempty", res1 = "Core.bool" } )
ces:Push(1)
ces:AddInstruction( { op = "startbarrier", int1 = 1 } )
local lbl = ces:CreateLabel()
local trueLabel = lbl.."_true"
local falseLabel = lbl.."_false"
EmitLogical(cs, expr, ces, trueLabel, falseLabel)
ces:AddInstruction( { op = "label", str1 = trueLabel } )
ces:AddConstantInstruction("Core.bool", "true", "Value")
ces:Push(1)
ces:AddInstruction( { op = "return", int1 = 1 } )
ces:Pop()
ces:AddInstruction( { op = "label", str1 = falseLabel } )
ces:AddConstantInstruction("Core.bool", "false", "Value")
ces:Push(1)
ces:AddInstruction( { op = "return", int1 = 1 } )
ces:Pop()
ces:AddInstruction( { op = "endbarrier" } )
end
local function EmitArrayElementInitialize(cs, expr, arrayIndex, indexExpressions, dimIndex, deadTable, ces, iidx)
local subD = expr.dimensions[dimIndex+1]
for i=1,expr.dimensions[dimIndex] do
indexExpressions[dimIndex] = Constant(cs, arrayIndexType, i-1, "Value")
local d
if subD then
iidx = EmitArrayElementInitialize(cs, expr, arrayIndex, indexExpressions, dimIndex+1, deadTable, ces, iidx)
else
local src = SingleExpressionToList(expr.initializers[iidx])
EmitAssign(cs, arrayIndex, src, deadTable, ces, expr.incriminateNode)
iidx = iidx + 1
end
end
return iidx
end
local function EmitArrayInitialize(cs, expr, ces)
local aist = cs.gst[arrayIndexType]
local indexVTypes = { }
local indexAccessModes = { }
local initTarget = expr.localVar
local exportTarget = initTarget
local initAsConst = false
for idx=1,#expr.dimensions do
indexVTypes[idx] = aist
indexAccessModes[idx] = "R"
end
local indexValues = FlattenMV({
type = "CMultipleValues",
expressions = { },
accessModes = indexAccessModes,
vTypes = indexVTypes,
})
assert(expr.vTypes[1].containedType)
local arrayVType = expr.localVar.vTypes[1]
local createVType = arrayVType
if arrayVType.isConst then
-- Need to form as the non-const the non-const version of this array
local arrayVariationCode = ArrayOfTypeCode(arrayVType.dimensions, false)
createVType = arrayVType.containedType.arraysOf[arrayVariationCode]
if createVType == nil then
createVType = ArrayOfType(cs, arrayVType.containedType, arrayVType.dimensions, false, arrayVType.incriminateNode)
arrayVType.containedType.arraysOf[arrayVariationCode] = createVType
CompileArrayOfType(cs, createVType)
end
initTarget = ces:AddTemporary(createVType)
initTarget.holdOpenTemp = true
end
local arrayIndex = {
type = "CArrayIndex",
operand = ConvertExpression(cs, expr.incriminateNode, initTarget, { createVType }, { "R" }, false ),
indexes = indexValues,
vTypes = { expr.vTypes[1].containedType },
accessModes = { "P" },
}
EmitArrayElementInitialize(cs, expr, SingleExpressionToList(arrayIndex), indexValues.expressions, 1, { }, ces, 1)
if arrayVType.isConst then
-- Convert to constant array
ces:AddInstruction( { op = "pushempty", res1 = "Core.Array" } )
ces:AddInstruction( { op = "localref", int1 = initTarget.stackIndex } )
ces:AddInstruction( { op = "load" } )
ces:AddInstruction( { op = "call", res1 = "Core.Array/methods/ToConst()" } )
ces:AddInstruction( { op = "cast", res1 = arrayVType.longName } )
ces:AddInstruction( { op = "localref", int1 = exportTarget.stackIndex } )
ces:AddInstruction( { op = "move" } )
-- Cycle the temporary
initTarget.holdOpenTemp = false
ces:Push(1, initTarget)
ces:Pop(1)
end
end
-- Pushes values from an expression to the stack. The expression must only contain R and P values
EmitValues = function(cs, expr, ces, allowLocals)
if expr.type == "CMultipleValues" then
for _,subExpr in ipairs(expr.expressions) do
assert(subExpr.type ~= "CMultipleValues") -- Parameters and expression lists should always be flat
EmitValues(cs, subExpr, ces, allowLocals)
end
return
end
if not allowLocals then
for _,am in ipairs(expr.accessModes) do
assert(am == "P" or am == "CP" or am == "R" or am == "V", "Unexpected access mode "..tostring(am).." in expr type "..expr.type)
end
end
if expr.type == "CLocalVariable" then
assert(expr.stackIndex)
ces:AddInstruction( { op = "localref", int1 = expr.stackIndex } )
if expr.isPointer then
-- Move pointer to stack
ces:AddInstruction( { op = "load" } )
ces:Push()
else
ces:Push(1, expr)
end
elseif expr.type == "CConvertExpression" then
-- TEMPORARY: No convert!
EmitConvertedExpression(cs, expr.expression, expr.vTypes, expr.accessModes, ces)
elseif expr.type == "CMethodCall" then
local method = expr.method
if method.isBranching then
EmitLogicalToBoolean(cs, expr, ces)
else
if #expr.method.returnTypes.typeReferences ~= 0 then
for _,tref in ipairs(expr.method.returnTypes.typeReferences) do
PushShellSpace(ces, tref.refType)
end
end
if expr.delegateExpr then
assert(expr.delegateExpr.accessModes[1] == "L")
EmitValues(cs, expr.delegateExpr, ces, true)
end
EmitValues(cs, expr.parameters, ces)
EmitMethodCall(ces, expr.method, expr.explicit, expr.delegateExpr)
ces:Pop(#expr.method.actualParameterList.parameters)
if expr.delegateExpr then
ces:Pop(1)
end
end
elseif expr.type == "CConstant" then
if expr.signal == "NullRef" then
ces:AddInstruction( { op = "null" } )
elseif expr.signal == "Resource" then
ces:AddInstruction( { op = "res", res1 = expr.value } )
else
local vType = expr.vTypes[1]
ces:AddConstantInstruction(vType.longName, tostring(expr.value), expr.signal)
end
ces:Push()
elseif expr.type == "CObjectProperty" then
EmitValues(cs, expr.object, ces)
ces:AddInstruction( { op = "property", int1 = expr.property.propertyIndex - 1 } )
elseif expr.type == "CAdjustValueCount" then
local vCount = #expr.expression.vTypes
local targetVCount = #expr.vTypes
EmitValues(cs, expr.expression, ces, allowLocals)
while vCount > targetVCount do
ces:AddInstruction( { op = "pop" } )
ces:Pop()
vCount = vCount - 1
end
elseif expr.type == "CArrayIndex" then
local numDimensions = expr.operand.vTypes[1].dimensions
assert(numDimensions)
EmitValues(cs, expr.operand, ces)
EmitValues(cs, expr.indexes, ces)
ces:AddInstruction( { op = "arrayindex", int1 = numDimensions } )
ces:Pop(numDimensions)
elseif expr.type == "CLogicalNotNode" or expr.type == "CLogicalAndNode" or expr.type == "CLogicalOrNode" or expr.type == "CEqualityCompare" or expr.type == "CCheckCast" then
EmitLogicalToBoolean(cs, expr, ces)
elseif expr.type == "CNewInstance" then
if expr.parameters then
EmitValues(cs, expr.parameters, ces)
end
local numDimensions = 0
if expr.vTypes[1].type == "CArrayOfType" then
numDimensions = expr.vTypes[1].dimensions
end
ces:AddInstruction( { op = "newinstance", res1 = expr.vTypes[1].longName, int1 = numDimensions } )
if expr.parameters then
ces:Pop(#expr.parameters.vTypes)
end
ces:Push(1) -- Instance
elseif expr.type == "CInitializeAndRecover" then
EmitValues(cs, expr.expression, ces)
elseif expr.type == "CAllocateTemporary" then
local temp = ces:AddTemporary(expr.vTypes[1])
ces:AddInstruction( { op = "localref", int1 = temp.stackIndex } )
ces:Push(1, temp)
elseif expr.type == "CCloneExpression" then
if expr.expression then
EmitValues(cs, expr.expression, ces, allowLocals)
end
ces:AddInstruction( { op = "clone", int1 = 0, int2 = 1 } )
ces:Clone(0, 1)
elseif expr.type == "CStaticInstance" then
ces:AddInstruction( { op = "res", res1 = expr.longName } )
ces:Push(1)
elseif expr.type == "CGenerateHashNode" then
EmitValues(cs, expr.expression, ces)
ces:AddInstruction( { op = "hash" } )
-- Cycle the opstack to remove any temporary refs
ces:Pop()
ces:Push(1)
elseif expr.type == "CInitializeArray" then
local temp = ces:AddTemporary(expr.vTypes[1])
for _,d in ipairs(expr.dimensions) do
ces:AddConstantInstruction(arrayIndexType, tostring(d), "Value")
end
ces:AddInstruction( { op = "newinstance", res1 = expr.vTypes[1].longName, int1 = #expr.dimensions } )
ces:AddInstruction( { op = "localref", int1 = temp.stackIndex } )
ces:AddInstruction( { op = "move" } )
expr.localVar.stackIndex = temp.stackIndex
EmitArrayInitialize(cs, expr, ces)
ces:AddInstruction( { op = "localref", int1 = temp.stackIndex } )
ces:Push(1, temp)
elseif expr.type == "CInitializeProperties" then
local temp = ces:AddTemporary(expr.vTypes[1])
local initIndexes = { }
for _,i in ipairs(expr.initializers) do
local property = i.dest.property
initIndexes[#initIndexes+1] = property.propertyIndex - 1
local reduced = AdjustValueCount(cs, i.src, i.incriminateNode, 1)
local targetVType = property.typeOf.refType
local targetAccessMode = "R"
if VTypeIsRefStruct(targetVType) then
targetAccessMode = "CP"
end
local converted = ConvertExpression(cs, i.incriminateNode, reduced, { targetVType }, { targetAccessMode }, false )
EmitValues(cs, converted, ces, false)
end
ces:AddInstruction( { op = "newinstanceset", int1 = temp.stackIndex, intVar = initIndexes, res1 = expr.vTypes[1].longName } )
ces:Pop(#initIndexes)
ces:AddInstruction( { op = "localref", int1 = temp.stackIndex } )
ces:Push(1, temp)
elseif expr.type == "CMethodDelegation" then
ces:AddInstruction( { op = "res", res1 = expr.method.longName } )
ces:AddInstruction( { op = "cast", res1 = expr.vTypes[1].longName } )
ces:Push(1)
elseif expr.type == "CRecycledValues" then
local recycleStart = expr.opstackOffset or (ces.opstackIndex - expr.opstackIndex - 1)
local recycleCount = #expr.vTypes
ces:AddInstruction( { op = "clone", int1 = recycleStart, int2 = recycleCount } )
ces:Clone(recycleStart, recycleCount)
elseif expr.type == "CTernary" then
-- Push shells
local numValues = #expr.vTypes
for i=1,numValues do
PushShellSpace(ces, expr.vTypes[i])
end
ces:AddInstruction( { op = "startbarrier", int1 = numValues } )
local lbl = ces:CreateLabel()
local trueLabel = lbl.."_true"
local falseLabel = lbl.."_false"
EmitLogical(cs, expr.cond, ces, trueLabel, falseLabel)
ces:AddInstruction( { op = "label", str1 = trueLabel } )
EmitValues(cs, expr.trueExprs, ces)
ces:AddInstruction( { op = "return", int1 = numValues } )
ces:Pop(numValues)
ces:AddInstruction( { op = "label", str1 = falseLabel } )
EmitValues(cs, expr.falseExprs, ces)
ces:AddInstruction( { op = "return", int1 = numValues } )
ces:Pop(numValues)
ces:AddInstruction( { op = "endbarrier" } )
elseif expr.type == "CBoundMethodDelegation" then
local glue = MarshalForBoundDelegate(cs, expr.vTypes[1], expr.method)
if expr.object then
local temp = ces:AddTemporary(expr.vTypes[1])
EmitValues(cs, expr.object, ces)
ces:AddInstruction( { op = "newinstanceset", int1 = temp.stackIndex, intVar = { "0" }, res1 = glue.longName } )
ces:Pop(1)
ces:AddInstruction( { op = "localref", int1 = temp.stackIndex } )
ces:Push(1, temp)
else
ces:AddInstruction( { op = "newinstance", int1 = 0, res1 = glue.longName } )
ces:Push(1)
end
else
error("Couldn't emit values for node type "..expr.type)
end
end
EmitOperateAndAssign = function(cs, destNode, right, operator, scope, ces, node)
-- Index: Cache operands[1] and [2]
-- Indirect: Cache operand[1]
-- Everything else: No cache
if destNode.type == "Index" then
local indexSource = CompileExpression(cs, destNode.operands[1], scope, true)
local indexIndexes = CompileExpressionList(cs, destNode.operands[2], scope, true)
indexSource = AdjustValueCount(cs, indexSource, node, 1)
-- Make sure the recycled values are stored, locals can't be dismantled from multi-value expressions
do
local indexAccessModes = { }
for idx,vt in ipairs(indexIndexes.vTypes) do
if VTypeIsRefStruct(vt) then
indexAccessModes[idx] = "CP"
else
indexAccessModes[idx] = "R"
end
end
indexIndexes = ConvertExpression(cs, node, indexIndexes, indexIndexes.vTypes, indexAccessModes, false)
end
local sourceRecycle =
{
type = "CRecycledValues",
vTypes = indexSource.vTypes,
accessModes = indexSource.accessModes,
opstackIndex = ces.opstackIndex,
line = node.line,
filename = node.filename,
}
EmitValues(cs, indexSource, ces, true)
local indexRecycle =
{
type = "CRecycledValues",
vTypes = indexIndexes.vTypes,
accessModes = indexIndexes.accessModes,
opstackIndex = ces.opstackIndex,
line = node.line,
filename = node.filename,
}
EmitValues(cs, indexIndexes, ces, true)
local virtualNode =
{
type = "Index",
operands = { sourceRecycle, SingleExpressionToList(indexRecycle) },
line = node.line,
filename = node.filename,
}
local loadExpression = CompileIndexExpression(cs, virtualNode, scope, true)
local operationNode =
{
type = "BinaryOperatorNode",
operator = node.operator,
operands = { loadExpression, right },
line = node.line,
filename = node.filename,
}
assert(operationNode.line)
local compiledResult = CompileExpression(cs, operationNode, scope, true)
local saveExpression = CompileIndexExpression(cs, virtualNode, scope, false)
EmitAssign(cs, SingleExpressionToList(saveExpression), SingleExpressionToList(compiledResult), scope, ces, node)
local pops = #indexSource.vTypes + #indexIndexes.vTypes
for i=1,pops do
ces:AddInstruction( { op = "pop" } )
ces:Pop(1)
end
elseif destNode.type == "Indirect" then
local indirSource = CompileExpression(cs, destNode.operands[1], scope, true)
-- TODO: If indirSource has "R" access mode, refuse this
local sourceRecycle =
{
type = "CRecycledValues",
vTypes = indirSource.vTypes,
accessModes = indirSource.accessModes,
opstackIndex = ces.opstackIndex,
line = node.line,
filename = node.filename,
}
EmitValues(cs, indirSource, ces, true)
local virtualNode =
{
type = "Indirect",
operands = { sourceRecycle, destNode.operands[2] },
line = node.line,
filename = node.filename,
}
local loadExpression = CompileExpression(cs, virtualNode, scope, true)
local operationNode =
{
type = "BinaryOperatorNode",
operator = node.operator,
operands = { loadExpression, right },
line = node.line,
filename = node.filename,
}
assert(operationNode.line)
local compiledResult = CompileExpression(cs, operationNode, scope, true)
local saveExpression = CompileExpression(cs, virtualNode, scope, false)
EmitAssign(cs, SingleExpressionToList(saveExpression), SingleExpressionToList(compiledResult), scope, ces, node)
local pops = #indirSource.vTypes
for i=1,pops do
ces:AddInstruction( { op = "pop" } )
ces:Pop(1)
end
else
local loadTarget = CompileExpression(cs, destNode, scope, true)
local saveTarget = CompileExpression(cs, destNode, scope, false)
local operationNode =
{
type = "BinaryOperatorNode",
operator = node.operator,
operands = { loadTarget, right },
line = destNode.line,
filename = destNode.filename,
}
local compiledResult = CompileExpression(cs, operationNode, scope, true)
EmitAssign(cs, SingleExpressionToList(saveTarget), SingleExpressionToList(compiledResult), scope, ces, node)
end
--assert(false)
end
EmitAssign = function(cs, dest, src, scope, ces, incriminate)
assert(src.type == "CMultipleValues" or src.type == "CAdjustValueCount")
assert(dest.type == "CMultipleValues")
local leftExpr = CompileExpressionList(cs, dest, scope, false)
if src.vTypes == nil then
cerror(incriminate, "AssignRightSideNotValue")
end
if leftExpr.vTypes == nil or leftExpr.vTypes[1] == nil then
cerror(incriminate, "AssignLeftSideNotVariable")
end
if #src.vTypes ~= #leftExpr.vTypes then
cerror(incriminate, "AssignTooFewValues", tostring(#leftExpr.vTypes), tostring(#src.vTypes))
end
local targetVTypes = { }
local targetAccessModes = { }
local cachedIntercepts = { }
for idx,leftExpr in ipairs(leftExpr.expressions) do
if src.vTypes[idx] == nil then
cerror(incriminate, "AssignRightSideTooFewValues")
end
local leftAccessMode = leftExpr.accessModes[1]
local leftVType = leftExpr.vTypes[1]
if leftAccessMode == "R" then
if leftVType.longName == "Core.nullreference" then
targetAccessModes[#targetAccessModes+1] = "*"
targetVTypes[#targetVTypes+1] = leftVType
else
cerror(incriminate, "AssignLeftSideNotVariable")
end
elseif leftAccessMode == "L" or leftAccessMode == "P" then
targetAccessModes[#targetAccessModes+1] = "*"
targetVTypes[#targetVTypes+1] = leftVType
elseif leftAccessMode == "I" then
local placeholderParameters = SingleExpressionToList(PlaceholderValue(cs, src.vTypes[idx]))
local intercept = MatchMethodCall(cs, leftExpr, placeholderParameters, incriminate)
targetAccessModes[#targetAccessModes+1] = intercept.parameters.accessModes[1]
targetVTypes[#targetVTypes+1] = intercept.parameters.vTypes[1]
-- Convert target ref to the appropriate access mode
intercept.convertedParameters = ConvertExpression(cs, incriminate, leftExpr.object, { intercept.parameters.vTypes[2] }, { intercept.parameters.accessModes[2] }, false)
cachedIntercepts[idx] = intercept
elseif leftAccessMode == "A" then
local placeholderParameters = SingleExpressionToList(PlaceholderValue(cs, src.vTypes[idx]))
for _,expr in ipairs(leftExpr.indexes.expressions) do
AppendExpressionToMV(placeholderParameters, expr)
end
local intercept = MatchMethodCall(cs, leftExpr.methodCall, placeholderParameters, incriminate)
-- Convert the indexes to the appropriate type
do
local indexTargetAccessModes = { }
local indexTargetVTypes = { }
for idx=3,#intercept.parameters.accessModes do
indexTargetAccessModes[idx-2] = intercept.parameters.accessModes[idx]
indexTargetVTypes[idx-2] = intercept.parameters.vTypes[idx]
end
intercept.convertedParameters = ConvertExpression(cs, incriminate, leftExpr.indexes, indexTargetVTypes, indexTargetAccessModes, false)
end
targetAccessModes[#targetAccessModes+1] = intercept.parameters.accessModes[1]
targetVTypes[#targetVTypes+1] = intercept.parameters.vTypes[1]
cachedIntercepts[idx] = intercept
elseif leftAccessMode == "CP" then
cerror(incriminate, "AssignToConstant")
else
assert(false, "Bad left side access mode from "..leftExpr.type..", discharged: "..tostring(leftExpr.discharged)..", access mode "..leftAccessMode)
end
end
local cRight = ConvertExpression(cs, incriminate, src, targetVTypes, targetAccessModes, false, true)
EmitValues(cs, cRight, ces, true)
local numExpr = #leftExpr.expressions
for iidx=1,numExpr do
local idx = numExpr-iidx+1
local leftExpr = leftExpr.expressions[idx]
local leftVType = leftExpr.vTypes[1]
local leftAccessMode = leftExpr.accessModes[1]
local rightAccessMode = cRight.accessModes[idx]
if leftAccessMode == "L" then
EmitValues(cs, leftExpr, ces, true)
ces:AddInstruction( { op = "move" } )
ces:Pop(2)
elseif leftAccessMode == "P" then
EmitValues(cs, leftExpr, ces, true)
ces:AddInstruction( { op = "move" } )
ces:Pop(2)
elseif leftAccessMode == "A" then
EmitValues(cs, leftExpr.methodCall.object, ces, true)
local intercept = cachedIntercepts[idx]
intercept.parameters = intercept.convertedParameters --leftExpr.indexes
EmitValues(cs, intercept, ces)
elseif leftAccessMode == "I" then
-- FIXME: Using convertedParameters is a bit of a hack?
local intercept = cachedIntercepts[idx]
EmitValues(cs, intercept.convertedParameters, ces, true)
intercept.parameters = EmptyExpressionList()
EmitValues(cs, intercept, ces)
elseif leftAccessMode == "R" and leftVType.longName == "Core.nullreference" then
ces:AddInstruction( { op = "pop" } )
ces:Pop(1)
else
assert(false)
end
end
end
local function UnhideLocals(localMV)
for _,lv in ipairs(localMV.expressions) do
lv.invisibleSymbol = nil
end
end
local function EmitDeclsToLocals(cs, declsNode, block, ces)
local declarations = { }
local declVTypes = { }
local declAccessModes = { }
for _,decl in ipairs(declsNode.declarations) do
local tr = TypeReference(cs, decl.type, block)
CompileTypeReference(cs, tr)
assert(tr.isCompiled)
local t = tr.refType
if t.longName == varyingType then
cerror(decl.name, "VaryingLocal")
end
local l = LocalVariable(BlockMethod(block), t, false)
ces:AddInstruction( { op = "alloclocal", res1 = l.vTypes[1].longName, str1 = decl.name.string } )
block:CreateLocal(ces, l, decl.name, true)
declarations[#declarations+1] = l
declVTypes[#declVTypes+1] = l.vTypes[1]
declAccessModes[#declAccessModes+1] = "L"
end
ces:Discharge() -- Don't allow compiler temps to be created before these
assert(declVTypes)
return FlattenMV({
type = "CMultipleValues",
accessModes = declAccessModes,
expressions = declarations,
vTypes = declVTypes,
})
end
local function EmitLocalDecl(cs, expr, block, ces)
local mvNode = EmitDeclsToLocals(cs, expr.declarations, block, ces)
if expr.initializers then
local initializers = CompileExpressionList(cs, expr.initializers, block, true)
initializers = AdjustValueCount(cs, initializers, expr.initializers, #mvNode.vTypes)
EmitAssign(cs, mvNode, initializers, block, ces, expr)
end
UnhideLocals(mvNode)
end
-- Emits a "using" protection block for a single portion of an initializer list
-- If no initializers are available, emits the code block instead
local function EmitUsingDeclPortion(cs, baseExpr, localMV, initExprs, block, outerBlock, ces, localStart, exprStart)
if localMV.vTypes[localStart] == nil then
if initExprs[exprStart] ~= nil then
cerror(baseExpr, "AssignTooFewValues", tostring(#localMV.vTypes), tostring(#initExprs))
end
-- Ran out of initializers, nothing left to do but emit the actual code
UnhideLocals(localMV)
local cBlock = CodeBlock(cs, nil, block, block.localIndex)
CompileCodeBlock(cs, ces, block, baseExpr.block)
return
end
local exprNode = CompileExpression(cs, initExprs[exprStart], outerBlock, true)
if exprNode.accessModes == nil then
cerror(node, "ExpectedExpression", exprNode.type)
end
local exprSubMV = FlattenMV({
type = "CMultipleValues",
accessModes = clonetable(exprNode.accessModes),
vTypes = clonetable(exprNode.vTypes),
expressions = { exprNode },
})
local localSubMV =
{
type = "CMultipleValues",
accessModes = { },
expressions = { },
vTypes = { },
}
local numValues = #exprNode.accessModes
for i=1,numValues do
local subLocal = i + localStart - 1
local l = localMV.expressions[subLocal]
if l == nil then
cerror(baseExpr, "AssignRightSideTooFewValues")
end
localSubMV.expressions[i] = l
localSubMV.accessModes[i] = localMV.accessModes[subLocal]
localSubMV.vTypes[i] = localMV.vTypes[subLocal]
end
-- Assign to these locals
EmitAssign(cs, localSubMV, exprSubMV, block, ces, baseExpr)
ces:Discharge()
local guaranteeOuterBlock = GuaranteeOuterBlock(cs, ces, nil, block, block.localIndex)
local guaranteeInnerBlock = StartGuaranteeInnerBlock(cs, ces, guaranteeOuterBlock)
-- Emit more assignments or the code
EmitUsingDeclPortion(cs, baseExpr, localMV, initExprs, guaranteeInnerBlock, outerBlock, ces, localStart + numValues, exprStart + 1)
CloseGuaranteeInnerBlock(cs, ces, guaranteeInnerBlock)
local disposeBlock = CodeBlock(cs, nil, guaranteeOuterBlock, guaranteeOuterBlock.localIndex)
do
local emptyParameterListNode = VirtualParseNode("ExpressionList", baseExpr)
emptyParameterListNode.expressions = { }
local disposeNode = VirtualParseNode("Dispose", baseExpr)
disposeNode.string = "Dispose"
local disposeIndirectNode = VirtualParseNode("Indirect", baseExpr)
disposeIndirectNode.operands = { false, disposeNode }
local disposeInvoke = VirtualParseNode("Invoke", baseExpr)
disposeInvoke.operands = { disposeIndirectNode, emptyParameterListNode }
for i=1,numValues do
-- Dispose of values in reverse order
disposeIndirectNode.operands[1] = localMV.expressions[localStart + numValues - i]
local disposeCompiled = CompileExpression(cs, disposeInvoke, guaranteeOuterBlock, true)
EmitValues(cs, AdjustValueCount(cs, disposeCompiled, baseExpr, 0), ces)
ces:Discharge()
end
end
CloseGuaranteeOuterBlock(cs, ces, guaranteeOuterBlock)
end
local function EmitUsingDecl(cs, expr, block, ces)
local rootBlock = CodeBlock(cs, nil, block, block.localIndex)
-- No we're not emitting any actual expression-based code (only local decls), push a code location
ces:PushCodeLocation(expr.filename, expr.line)
-- Initializers can potentially fail, but disposal should only occur if the local was successfully assigned to
local mvNode = EmitDeclsToLocals(cs, expr.declarations, rootBlock, ces)
EmitUsingDeclPortion(cs, expr, mvNode, expr.initializers.expressions, rootBlock, block, ces, 1, 1)
-- Close the root block
CloseCodeBlock(cs, ces, rootBlock)
end
BlockMethod = function(block)
while not block.isRootLevel do
block = block.owner
if block == nil then
return nil
end
end
return block.method
end
local function EmitReturn(cs, stmt, block, ces)
local m = BlockMethod(block)
local numRequiredReturnValues = #m.returnTypes.typeReferences
local returnVTypes = { }
if stmt.returnValues then
local returnExpr = CompileExpressionList(cs, stmt.returnValues, block, true)
returnExpr = AdjustValueCount(cs, returnExpr, stmt, numRequiredReturnValues)
local returnTypes = { }
for _,ref in ipairs(m.returnTypes.typeReferences) do
returnTypes[#returnTypes+1] = ref.refType
end
local convertedReturns = ConvertExpression(cs, stmt, returnExpr, returnTypes, nil, false)
EmitValues(cs, convertedReturns, ces, true)
else
if numRequiredReturnValues ~= 0 then
cerror(stmt, "ReturnValueCountMismatch", tostring(numRequiredReturnValues), "0")
end
end
local guarantee = FindGuaranteeingBlock(cs, block)
if guarantee == nil then
-- Just return out of frame
ces:AddInstruction( { op = "return", int1 = numRequiredReturnValues } )
ces:Pop(numRequiredReturnValues)
else
-- Store and return to the guarantee
for i=1,numRequiredReturnValues do
local rvHolder = guarantee.returnValueHolders[numRequiredReturnValues-i+1]
ces:AddInstruction( { op = "localref", int1 = rvHolder.stackIndex } )
ces:AddInstruction( { op = "move" } )
ces:Pop(1)
end
ces:AddInstruction( { op = "jump", str1 = guarantee.returnPath } )
end
end
EmitAliasableJump = function(cs, ces, baseBlock, label)
local gBlock = baseBlock.owner
while gBlock ~= nil and (not gBlock.isGuaranteeInner) and (not gBlock.isRootLevel) do
gBlock = gBlock.owner
end
if gBlock == nil or not (gBlock.isGuaranteeInner) then
ces:AddInstruction( { op = "jump", str1 = label } )
else
-- Has a guarantee
local newLabel = AddLabelToGuarantee(cs, gBlock.owner, label)
ces:AddInstruction( { op = "jump", str1 = newLabel } )
end
end
local function EmitBlockJump(cs, labelType, blockNameTarget, block, ces, incriminate)
local baseBlock = block
while true do
if block[labelType] and (blockNameTarget == nil or blockNameTarget == block.flowControlLabel) then
EmitAliasableJump(cs, ces, baseBlock, block[labelType])
return
end
if block.isRootLevel then
cerror(incriminate, "UnresolvedFlowControlTarget")
end
block = block.owner
end
end
local function EmitForEachLoopArray(cs, stmt, enumeratorExpr, block, ces)
local arrayIndexST = cs.gst[arrayIndexType]
if arrayIndexST == nil then
throw(SIGNAL_UnresolvedExpression)
end
local iteratorBlock = CodeBlock(cs, nil, block, block.localIndex)
-- Since we're not compiling any statement blocks for this code block, need to push a code location
ces:PushCodeLocation(stmt.filename, stmt.line)
local indexLocal = LocalVariable(BlockMethod(block), arrayIndexST)
do
local opcode, int1, int2, res1, str1 = RDXC.Native.encodeConstant("Core.largeuint", "-1", "Value")
ces:AddInstruction( { op = opcode, res1 = res1, int1 = int1, int2 = int2, str1 = str1 } )
ces:Push(1)
end
ces:AddInstruction( { op = "createlocal", res1 = arrayIndexType, str1 = "foreach index" } )
ces:Pop()
iteratorBlock:CreateLocal(ces, indexLocal)
ces:Discharge()
local iteratorVariablesMV = EmitDeclsToLocals(cs, stmt.declarations, iteratorBlock, ces)
ces:Discharge()
local extractLocal
local simpleExtract
local mdIndexLocals = { }
local arrayInteriorType = enumeratorExpr.vTypes[1].containedType
if #iteratorVariablesMV.vTypes == 1 and TypeDirectlyCastable(arrayInteriorType, iteratorVariablesMV.vTypes[1]) then
extractLocal = iteratorVariablesMV.expressions[1]
simpleExtract = true
else
extractLocal = LocalVariable(BlockMethod(block), arrayInteriorType)
ces:AddInstruction( { op = "alloclocal", res1 = arrayInteriorType.longName, str1 = "foreach value" } )
iteratorBlock:CreateLocal(ces, extractLocal)
-- Determine if this is a multidimensional array
local numDimensions = enumeratorExpr.vTypes[1].dimensions
if numDimensions > 1 then
for i=1,numDimensions do
local lcl = LocalVariable(BlockMethod(block), arrayIndexST)
if i == numDimensions then
do
local opcode, int1, int2, res1, str1 = RDXC.Native.encodeConstant("Core.largeint", "-1", "Value")
ces:AddInstruction( { op = opcode, res1 = res1, int1 = int1, int2 = int2, str1 = str1 } )
ces:Push(1)
end
ces:AddInstruction( { op = "createlocal", res1 = arrayIndexType, str1 = "foreach index "..(i-1) } )
ces:Pop()
else
ces:AddInstruction( { op = "alloclocal", res1 = arrayIndexType, str1 = "foreach index "..(i-1) } )
end
iteratorBlock:CreateLocal(ces, lcl)
mdIndexLocals[i] = lcl
end
end
end
ces:Discharge()
local arrayLocal = LocalVariable(BlockMethod(block), enumeratorExpr.vTypes[1])
ces:AddInstruction( { op = "alloclocal", res1 = enumeratorExpr.vTypes[1].longName, str1 = "foreach array" } )
iteratorBlock:CreateLocal(ces, arrayLocal)
ces:Discharge()
-- Assign the array
EmitAssign(cs, SingleExpressionToList(arrayLocal), SingleExpressionToList(enumeratorExpr), iteratorBlock, ces, stmt)
ces:Discharge()
-- Emit the actual loop
local lbl = ces:CreateLabel()
local iterationLabel = lbl.."_foriter"
local endLabel = lbl.."_forend"
-- Make the iterator locals available
UnhideLocals(iteratorVariablesMV)
local forMainBlock = CodeBlock(cs, nil, iteratorBlock, iteratorBlock.localIndex)
forMainBlock.breakLabel = endLabel
forMainBlock.continueLabel = iterationLabel
forMainBlock.flowControlLabel = (stmt.label and stmt.label.string)
ces:AddInstruction( { op = "label", str1 = iterationLabel } )
ces:Discharge()
if #mdIndexLocals ~= 0 then
-- The op only requires a reference to the first local
ces:AddInstruction( { op = "localref", int1 = mdIndexLocals[1].stackIndex } )
end
ces:AddInstruction( { op = "localref", int1 = extractLocal.stackIndex } )
ces:AddInstruction( { op = "localref", int1 = indexLocal.stackIndex } )
ces:AddInstruction( { op = "localref", int1 = arrayLocal.stackIndex } )
ces:AddInstruction( { op = "iteratearray", str1 = endLabel, int2 = #mdIndexLocals } )
if not simpleExtract then
local exprList = EmptyExpressionList()
AppendExpressionToMV(exprList, extractLocal)
if #mdIndexLocals == 0 then
AppendExpressionToMV(exprList, indexLocal)
else
for _,subIndexLocal in ipairs(mdIndexLocals) do
AppendExpressionToMV(exprList, subIndexLocal)
end
end
EmitAssign(cs, iteratorVariablesMV, exprList, forMainBlock, ces, stmt)
ces:Discharge()
end
CompileCodeBlock(cs, ces, forMainBlock, stmt.block)
ces:AddInstruction( { op = "jump", str1 = iterationLabel } )
ces:AddInstruction( { op = "label", str1 = endLabel } )
ces:Discharge()
CloseCodeBlock(cs, ces, iteratorBlock)
end
local function EmitForEachLoopValue(cs, stmt, enumeratorExpr, block, ces)
local getEnumeratorNode = VirtualParseNode("Name", stmt)
getEnumeratorNode.string = "GetEnumerator"
local indirectNode = VirtualParseNode("Indirect", stmt)
indirectNode.operands = { enumeratorExpr, getEnumeratorNode }
local emptyParameterListNode = VirtualParseNode("ExpressionList", stmt)
emptyParameterListNode.expressions = { }
local invokeNode = VirtualParseNode("Invoke", stmt)
invokeNode.operands = { indirectNode, emptyParameterListNode }
local enumeratorExpr = AdjustValueCount(cs, CompileExpression(cs, invokeNode, block, true), stmt, 1)
if enumeratorExpr.vTypes[1].type == "CArrayOfType" then
-- GetEnumerator returns an array
EmitForEachLoopArray(cs, stmt, enumeratorExpr, block, ces)
return
end
-- GetEnumerator returns an enumerable of some sort
local forMainBlock = CodeBlock(cs, nil, block, block.localIndex)
-- Since we're not compiling any statement blocks for this code block, need to push a code location
ces:PushCodeLocation(stmt.filename, stmt.line)
local enumeratorLocal = LocalVariable(BlockMethod(block), enumeratorExpr.vTypes[1])
ces:AddInstruction( { op = "alloclocal", res1 = enumeratorExpr.vTypes[1].longName, str1 = "foreach enumerator" } )
forMainBlock:CreateLocal(ces, enumeratorLocal)
ces:Discharge()
local iteratorVariablesMV = EmitDeclsToLocals(cs, stmt.declarations, forMainBlock, ces)
ces:Discharge()
EmitAssign(cs, SingleExpressionToList(enumeratorLocal), SingleExpressionToList(enumeratorExpr), forMainBlock, ces, stmt)
ces:Discharge()
local lbl = ces:CreateLabel()
local condLabel = lbl.."_forcond"
local bodyLabel = lbl.."_forbody"
local iterationLabel = lbl.."_foriter"
local endLabel = lbl.."_forend"
forMainBlock.breakLabel = endLabel
forMainBlock.continueLabel = condLabel
forMainBlock.flowControlLabel = (stmt.label and stmt.label.string)
-- Emit the HasNext check
local hasNextNode = VirtualParseNode("Name", stmt)
hasNextNode.string = "HasNext"
local hasNextIndirectNode = VirtualParseNode("Indirect", stmt)
hasNextIndirectNode.operands = { enumeratorLocal, hasNextNode }
local hasNextInvoke = VirtualParseNode("Invoke", stmt)
hasNextInvoke.operands = { hasNextIndirectNode, emptyParameterListNode }
ces:AddInstruction( { op = "label", str1 = condLabel } )
ces:Discharge()
local cond = CompiledExprToBoolean(cs, stmt, CompileExpression(cs, hasNextInvoke, forMainBlock, true))
EmitLogical(cs, cond, ces, iterationLabel, endLabel)
ces:Discharge()
-- Emit the GetNext call and assign
local getNextNode = VirtualParseNode("Name", stmt)
getNextNode.string = "GetNext"
local getNextIndirectNode = VirtualParseNode("Indirect", stmt)
getNextIndirectNode.operands = { enumeratorLocal, getNextNode }
local getNextInvoke = VirtualParseNode("Invoke", stmt)
getNextInvoke.operands = { getNextIndirectNode, emptyParameterListNode }
local getNextExpr = CompileExpression(cs, getNextInvoke, forMainBlock, true)
ces:AddInstruction( { op = "label", str1 = iterationLabel } )
ces:Discharge()
local truncatedGetNextExpr = AdjustValueCount(cs, SingleExpressionToList(getNextExpr), stmt, #iteratorVariablesMV.vTypes)
EmitAssign(cs, iteratorVariablesMV, truncatedGetNextExpr, forMainBlock, ces, stmt)
ces:AddInstruction( { op = "label", str1 = bodyLabel } )
ces:Discharge()
-- Emit the actual code
UnhideLocals(iteratorVariablesMV)
local forBodyBlock = CodeBlock(cs, nil, forMainBlock, forMainBlock.localIndex)
CompileCodeBlock(cs, ces, forBodyBlock, stmt.block)
ces:AddInstruction( { op = "jump", str1 = condLabel } )
ces:AddInstruction( { op = "label", str1 = endLabel } )
ces:Discharge()
CloseCodeBlock(cs, ces, forMainBlock)
end
local function EmitForEachLoop(cs, stmt, block, ces)
-- stmt.declarations, stmt.iterator, stmt.block...
local enumeratorExpr = AdjustValueCount(cs, CompileExpression(cs, stmt.iterator, block, true), stmt, 1)
if enumeratorExpr.vTypes[1].type == "CArrayOfType" then
EmitForEachLoopArray(cs, stmt, enumeratorExpr, block, ces)
else
EmitForEachLoopValue(cs, stmt, enumeratorExpr, block, ces)
end
end
local function TypeIsException(st)
if st.type ~= "CStructuredType" then
return false
end
while st ~= nil do
if st.longName == "Core.Exception" then
return true;
end
st = st.parentType
end
return false
end
local function CompileStatement(cs, stmt, block, ces)
if stmt.type == "WhileLoop" then
local cond = CompiledExprToBoolean(cs, stmt, CompileExpression(cs, stmt.condition, block, true))
local lbl = ces:CreateLabel()
local whileCondLabel = lbl.."_whilecond"
local whileTrueLabel = lbl.."_whiletrue"
local whileEndLabel = lbl.."_whileend"
ces:AddInstruction( { op = "label", str1 = whileCondLabel } )
ces:Discharge()
EmitLogical(cs, cond, ces, whileTrueLabel, whileEndLabel)
ces:Discharge()
ces:AddInstruction( { op = "label", str1 = whileTrueLabel } )
ces:Discharge()
local whileBlock = CodeBlock(cs, nil, block, block.localIndex)
whileBlock.breakLabel = whileEndLabel
whileBlock.continueLabel = whileCondLabel
whileBlock.flowControlLabel = (stmt.label and stmt.label.string)
CompileCodeBlock(cs, ces, whileBlock, stmt.block)
ces:AddInstruction( { op = "jump", str1 = whileCondLabel } )
ces:AddInstruction( { op = "label", str1 = whileEndLabel } )
ces:Discharge()
elseif stmt.type == "DoLoop" then
local lbl = ces:CreateLabel()
local whileTrueLabel = lbl.."_whiletrue"
local whileEndLabel = lbl.."_whileend"
ces:AddInstruction( { op = "label", str1 = whileTrueLabel } )
ces:Discharge()
local whileBlock = CodeBlock(cs, nil, block, block.localIndex)
whileBlock.breakLabel = whileEndLabel
whileBlock.continueLabel = whileTrueLabel
whileBlock.flowControlLabel = (stmt.label and stmt.label.string)
CompileCodeBlock(cs, ces, whileBlock, stmt.block)
if stmt.condition then
local cond = CompiledExprToBoolean(cs, stmt, CompileExpression(cs, stmt.condition, block, true))
EmitLogical(cs, cond, ces, whileTrueLabel, whileEndLabel)
ces:Discharge()
end
ces:AddInstruction( { op = "label", str1 = whileEndLabel } )
ces:Discharge()
elseif stmt.type == "IfBlock" then
local lbl = ces:CreateLabel()
local ifTrueBlock = lbl.."_iftrue"
local ifFalseBlock = lbl.."_iffalse"
local ifEndBlock = lbl.."_ifend"
local cond = CompiledExprToBoolean(cs, stmt, CompileExpression(cs, stmt.condition, block, true))
-- Evaluate
EmitLogical(cs, cond, ces, ifTrueBlock, ifFalseBlock)
-- Discharge conditional temporaries
ces:Discharge()
-- Emit true statements
ces:AddInstruction( { op = "label", str1 = ifTrueBlock } )
ces:Discharge()
local trueBlock = CodeBlock(cs, nil, block, block.localIndex)
CompileCodeBlock(cs, ces, trueBlock, stmt.block)
ces:AddInstruction( { op = "jump", str1 = ifEndBlock } )
ces:AddInstruction( { op = "label", str1 = ifFalseBlock } )
ces:Discharge()
-- Emit false statements
if stmt.elseBlock then
local falseBlock = CodeBlock(cs, nil, block, block.localIndex)
CompileCodeBlock(cs, ces, falseBlock, stmt.elseBlock)
end
ces:AddInstruction( { op = "label", str1 = ifEndBlock } )
ces:Discharge()
elseif stmt.type == "SwitchBlock" then
if #stmt.cases == 0 then
cerror(stmt, "SwitchWithNoCases")
end
-- Reduce to one value
local valueExpr = AdjustValueCount(cs, CompileExpression(cs, stmt.value, block, true), stmt, 1)
local valueVType = valueExpr.vTypes[1]
-- Convert the value expression to a pointer or value
if VTypeIsRefStruct(valueExpr.vTypes[1]) then
valueExpr = ConvertExpression(cs, stmt, valueExpr, { valueVType }, { "CP" }, false)
else
valueExpr = ConvertExpression(cs, stmt, valueExpr, { valueVType }, { "R" }, false)
end
local defaultBlock
local valueBlocks = { }
local defaultInstanceDef = "{\n"
local switchType = valueVType
local objectST = cs.gst["Core.Object"]
if objectST == nil then
throw(SIGNAL_UnresolvedExpression)
end
if valueVType.longName == "Core.nullreference" then
switchType = objectST
end
-- Try each value
for blockIndex,caseNode in ipairs(stmt.cases) do
for _,expr in ipairs(caseNode.expressions) do
if expr.type == "DefaultCase" then
if defaultBlock ~= nil then
cerror(caseNode, "MultipleSwitchDefaults")
end
defaultBlock = blockIndex
else
valueBlocks[#valueBlocks+1] = blockIndex
local valueExpr = CompileExpression(cs, expr, block, true)
local exprAdjusted = AdjustValueCount(cs, valueExpr, caseNode, 1)
local exprConverted
local matchability = CastMatchability(exprAdjusted.vTypes[1], valueVType)
if matchability == matchLevels.POLYMORPHIC then
switchType = objectST
exprConverted = exprAdjusted
elseif matchability == matchLevels.DIRECT and exprAdjusted.accessModes[1] == "R" then
exprConverted = exprAdjusted
else
exprConverted = ConvertExpression(cs, caseNode, exprAdjusted, { valueVType }, { "R" }, false)
end
local initValue
if exprConverted.type ~= "CConstant" then
if VTypeIsObjectReference(valueVType) and exprConverted.type == "CStaticInstance" then
initValue = exprConverted.longName
else
cerror(caseNode, "NonConstantSwitchCase")
end
else
-- Convert to an initialization value
initValue = GetInitializationValue(cs, valueVType, exprConverted, false, 1, "!ERR_", { }, { }, false, caseNode)
end
defaultInstanceDef = defaultInstanceDef..initValue..",\n"
end
end
end
defaultInstanceDef = defaultInstanceDef.."}\n"
if #valueBlocks == 0 then
cerror(stmt, "SwitchCaseWithNoCases")
end
numCaseCollections = numCaseCollections + 1
local caseInstanceName = BlockMethod(block).longName.."/cases_"..numCaseCollections
-- Find or create an array of the values
local arrayCode = ArrayOfTypeCode(1, true)
local aot = switchType.arraysOf[arrayCode]
if aot == nil then
-- Create and compile it
aot = ArrayOfType(cs, switchType, 1, true, stmt)
switchType.arraysOf[arrayCode] = aot
CompileTypeShells(cs)
CompileArrayOfType(cs, aot)
end
-- Create the default instance
DefaultInstance(cs, aot, defaultInstanceDef, caseInstanceName, { #valueBlocks }, false)
local lbl = ces:CreateLabel()
local caseLabel = lbl.."_case_"
local endLabel = lbl.."_switchend"
-- Emit the switch lookup
EmitValues(cs, valueExpr, ces)
ces:AddInstruction( { op = "switch", int1 = #valueBlocks, res1 = caseInstanceName } )
ces:Pop()
for idx,blockIdx in ipairs(valueBlocks) do
ces:AddInstruction( { op = "case", str1 = caseLabel..blockIdx } )
end
-- Emit the default case jump
if defaultBlock ~= nil then
ces:AddInstruction( { op = "jump", str1 = caseLabel..defaultBlock } )
else
ces:AddInstruction( { op = "jump", str1 = endLabel } )
end
ces:Discharge()
-- Emit each case
for caseIndex,caseBlockNode in ipairs(stmt.cases) do
ces:AddInstruction( { op = "label", str1 = caseLabel..caseIndex } )
ces:Discharge()
local caseBlock = CodeBlock(cs, nil, block, block.localIndex)
caseBlock.breakLabel = endLabel
caseBlock.flowControlLabel = (caseBlockNode.label and caseBlockNode.label.string)
CompileCodeBlock(cs, ces, caseBlock, caseBlockNode.block)
ces:AddInstruction( { op = "jump", str1 = endLabel } )
ces:Discharge()
end
-- Finish
ces:AddInstruction( { op = "label", str1 = endLabel } )
ces:Discharge()
elseif stmt.type == "ForLoop" then
local lbl = ces:CreateLabel()
local condLabel = lbl.."_forcond"
local iterationLabel = lbl.."_foriter"
local bodyLabel = lbl.."_forbody"
local endLabel = lbl.."_forend"
local forMainBlock = CodeBlock(cs, nil, block, block.localIndex)
forMainBlock.breakLabel = endLabel
forMainBlock.continueLabel = iterationLabel
forMainBlock.flowControlLabel = (stmt.label and stmt.label.string)
CompileCodeBlock(cs, ces, forMainBlock, stmt.initial, true) -- Hold open
-- Skip iteration initially
ces:AddInstruction( { op = "jump", str1 = condLabel } )
ces:AddInstruction( { op = "label", str1 = iterationLabel } )
ces:Discharge()
local forIterBlock = CodeBlock(cs, nil, forMainBlock, forMainBlock.localIndex)
CompileCodeBlock(cs, ces, forIterBlock, stmt.iteration)
ces:AddInstruction( { op = "label", str1 = condLabel } )
ces:Discharge()
if stmt.condition then
local cond = CompiledExprToBoolean(cs, stmt, CompileExpression(cs, stmt.condition, forMainBlock, true))
EmitLogical(cs, cond, ces, bodyLabel, endLabel)
end
ces:Discharge()
ces:AddInstruction( { op = "label", str1 = bodyLabel } )
ces:Discharge()
local forBodyBlock = CodeBlock(cs, nil, forMainBlock, forMainBlock.localIndex)
CompileCodeBlock(cs, ces, forBodyBlock, stmt.block)
ces:AddInstruction( { op = "jump", str1 = iterationLabel } )
ces:AddInstruction( { op = "label", str1 = endLabel } )
ces:Discharge()
-- Close and release anything from the initializer block
CloseCodeBlock(cs, ces, forMainBlock)
elseif stmt.type == "ForEachLoop" then
EmitForEachLoop(cs, stmt, block, ces)
elseif stmt.type == "LocalDecl" then
EmitLocalDecl(cs, stmt, block, ces)
elseif stmt.type == "UsingDecl" then
EmitUsingDecl(cs, stmt, block, ces)
elseif stmt.type == "Return" then
EmitReturn(cs, stmt, block, ces)
elseif stmt.type == "Continue" then
EmitBlockJump(cs, "continueLabel", stmt.label and stmt.label.string, block, ces, stmt)
elseif stmt.type == "Break" then
EmitBlockJump(cs, "breakLabel", stmt.label and stmt.label.string, block, ces, stmt)
elseif stmt.type == "CodeBlock" then
local cb = CodeBlock(cs, nil, block, block.localIndex)
CompileCodeBlock(cs, ces, cb, stmt)
elseif stmt.type == "Assign" then
local left = CompileExpressionList(cs, stmt.destinations, block, false)
local right = CompileExpressionList(cs, stmt.sources, block, true)
right = AdjustValueCount(cs, right, stmt, #left.vTypes)
EmitAssign(cs, left, right, block, ces, stmt)
elseif stmt.type == "IncrementalOperate" then
local right = Constant(cs, "Core.byte", "1", "Value")
EmitOperateAndAssign(cs, stmt.destination, right, stmt.operator, block, ces, stmt)
elseif stmt.type == "OperateAndAssign" then
local right = CompileExpression(cs, stmt.source, block, true)
EmitOperateAndAssign(cs, stmt.destination, right, stmt.operator, block, ces, stmt)
elseif stmt.type == "ExpressionList" then
local expr = CompileExpressionList(cs, stmt, block, true)
for _,am in ipairs(expr.accessModes) do
if am ~= "R" and am ~= "CP" then
cerror(stmt, "ExpressionStatementIsVariable")
end
end
EmitValues(cs, AdjustValueCount(cs, expr, stmt, 0, true), ces)
elseif stmt.type == "Throw" then
local expr = CompileExpression(cs, stmt.expression, block, true)
expr = AdjustValueCount(cs, expr, stmt, 1)
local exceptionType = cs.gst["Core.Exception"]
if not exceptionType then
throw(SIGNAL_UnresolvedExpression)
end
expr = ConvertExpression(cs, stmt, expr, { exceptionType }, { "R" }, false )
EmitValues(cs, expr, ces)
ces:AddInstruction( { op = "throw" } )
ces:Pop()
elseif stmt.type == "TryBlock" then
local lbl = ces:CreateLabel()
local catchLabel = lbl.."_catch"
local endLabel = lbl.."_tryend"
local finishLabel = lbl.."_tryfinish"
local guaranteeOuterBlock
local guaranteeInnerBlock
local tryCatchExternalBlock = block
if not stmt.finallyBlock and not stmt.catchBlocks then
cerror(stmt, "NoCatchOrFinally")
end
if stmt.finallyBlock then
guaranteeOuterBlock = GuaranteeOuterBlock(cs, ces, nil, block, block.localIndex)
guaranteeInnerBlock = StartGuaranteeInnerBlock(cs, ces, guaranteeOuterBlock)
tryCatchExternalBlock = guaranteeInnerBlock
end
if stmt.catchBlocks then
ces:AddInstruction( { op = "try", str1 = catchLabel, str2 = endLabel } )
ces:Discharge()
end
local tryBlock = CodeBlock(cs, nil, tryCatchExternalBlock, tryCatchExternalBlock.localIndex)
CompileCodeBlock(cs, ces, tryBlock, stmt.block)
if stmt.catchBlocks then
ces:AddInstruction( { op = "jump", str1 = finishLabel } )
ces:AddInstruction( { op = "label", str1 = endLabel } )
ces:Discharge()
local catchTypes = { }
local catchTypeLabels = { }
for cidx,blk in ipairs(stmt.catchBlocks.catchBlocks) do
local thisCatchLabel = catchLabel.."_"..cidx
local catchBlock = CodeBlock(cs, nil, tryCatchExternalBlock, tryCatchExternalBlock.localIndex)
local catchingType
local catchParam = nil
local guaranteeBlock
if blk.exceptionType then
local tr = TypeReference(cs, blk.exceptionType, tryCatchExternalBlock)
CompileTypeReference(cs, tr)
local exceptType = tr.refType
catchingType = exceptType
if not tr.isCompiled or not TypeIsException(exceptType) then
cerror(blk, "ThrowNonException")
end
catchParam = LocalVariable(BlockMethod(tryCatchExternalBlock), exceptType)
catchBlock:CreateLocal(ces, catchParam, blk.exceptionName)
ces:AddInstruction( { op = "label", str1 = thisCatchLabel } )
ces:AddInstruction( { op = "catch", res1 = catchingType.longName } )
ces:AddInstruction( { op = "createlocal", res1 = catchingType.longName, str1 = blk.exceptionName.string } )
else
catchingType = cs.gst["Core.Exception"]
assert(catchingType)
ces:AddInstruction( { op = "label", str1 = thisCatchLabel } )
ces:AddInstruction( { op = "catch", res1 = "Core.Exception" } )
ces:AddInstruction( { op = "pop" } )
end
ces:Discharge()
if catchTypeLabels[catchingType] then
cerror(blk, "DuplicateCatch")
end
catchTypeLabels[catchingType] = thisCatchLabel
catchTypes[cidx] = catchingType
CompileCodeBlock(cs, ces, catchBlock, blk.block)
ces:AddInstruction( { op = "jump", str1 = finishLabel } )
ces:Discharge()
end
ces:AddInstruction( { op = "label", str1 = catchLabel } )
ces:AddInstruction( { op = "catch", res1 = "Core.Exception" } )
assert(#catchTypes == #stmt.catchBlocks.catchBlocks)
for _,ct in ipairs(catchTypes) do
ces:AddInstruction( { op = "trycatch", str1 = catchTypeLabels[ct], res1 = ct.longName } )
end
ces:AddInstruction( { op = "throw" } )
ces:AddInstruction( { op = "label", str1 = finishLabel } )
ces:Discharge()
end
if stmt.finallyBlock then
CloseGuaranteeInnerBlock(cs, ces, guaranteeInnerBlock)
local finallyBlock = CodeBlock(cs, nil, guaranteeOuterBlock, guaranteeOuterBlock.localIndex)
CompileCodeBlock(cs, ces, finallyBlock, stmt.finallyBlock)
CloseGuaranteeOuterBlock(cs, ces, guaranteeOuterBlock)
end
elseif stmt.type == "MemberDecl" and structuredTypeDeclTypes[stmt.declType.string] then
local method = BlockMethod(block)
method.numPrivateTypes = method.numPrivateTypes + 1
local privateTypeName = method.longName.."/privatetype"..(method.numPrivateTypes)
local typeNamespace = Namespace(nil, privateTypeName)
typeNamespace.privateTypeName = privateTypeName
local uncompiledType = StructuredType(cs, Namespace(typeNamespace, stmt.name.string), block, stmt.attribTags, stmt)
block:InsertUnique(stmt.name, uncompiledType)
uncompiledType.namespace.createdBy = uncompiledType
cs.uncompiled[#cs.uncompiled+1] = uncompiledType
CompileTypeShells(cs)
uncompiledType.isPrivateType = true
else
error("Unemittable statement type "..stmt.type)
end
ces:Discharge()
end
CloseCodeBlock = function(cs, ces, block)
assert(block.closed == nil, "Block was already closed")
for i=1,#block.locals do
ces:AddInstruction( { op = "removelocal" } )
ces.localCount = ces.localCount - 1
end
block.closed = true
ces:Discharge()
ces:PopCodeLocation()
end
CompileCodeBlock = function(cs, ces, block, blockNode, holdOpen)
assert(ces)
ces:PushCodeLocation(blockNode.filename, blockNode.line)
for _,stmt in ipairs(blockNode.statements) do
ces:PushCodeLocation(stmt.filename, stmt.line)
CompileStatement(cs, stmt, block, ces)
ces:PopCodeLocation()
assert(ces.opstackIndex == 0)
end
if not holdOpen then
CloseCodeBlock(cs, ces, block)
end
end
local function CodeEmissionState()
local ces = {
type = "CCodeEmissionState",
statements = { },
temporaries = { },
instructions = { },
pendingInstructions = { },
opstackTempRefs = { },
codeLocation = nil,
localCount = 0,
opstackIndex = 0,
labelCount = 0,
Push = function(self, count, tempRef)
self.opstackIndex = self.opstackIndex + (count or 1)
if tempRef ~= nil and tempRef.isTemporary then
self.opstackTempRefs[self.opstackIndex] = tempRef
tempRef.numTempReferences = tempRef.numTempReferences + 1
end
return self.opstackIndex
end,
Clone = function(self, start, count)
if count == 0 then
return
end
while count ~= nil and count > 1 do
self:Clone(start, 1)
count = count - 1
end
self.opstackIndex = self.opstackIndex + 1
local migratedTemp = self.opstackTempRefs[self.opstackIndex - start - 1]
if migratedTemp ~= nil and migratedTemp.numTempReferences ~= nil then
self.opstackTempRefs[self.opstackIndex] = migratedTemp
migratedTemp.numTempReferences = migratedTemp.numTempReferences + 1
end
return self.opstackIndex
end,
Pop = function(self, count)
if count == 0 then
return
end
while count ~= nil and count > 1 do
self:Pop(1)
count = count - 1
end
local tempRef = self.opstackTempRefs[self.opstackIndex]
if tempRef ~= nil then
self.opstackTempRefs[self.opstackIndex] = nil
local numTempReferences = tempRef.numTempReferences - 1
tempRef.numTempReferences = numTempReferences
if numTempReferences == 0 and not tempRef.holdOpenTemp then
tempRef.tempActive = false
end
end
self.opstackIndex = self.opstackIndex - 1
return self.opstackIndex
end,
AddTemporary = function(self, st)
-- See if an existing temporary can be recycled
for _,temp in ipairs(self.temporaries) do
if temp.vTypes[1] == st and temp.tempActive == false then
temp.tempActive = true
return temp
end
end
assert(st.longName ~= "Core.nullreference")
local lv = LocalVariable(nil, st, false, false, "temp")
lv.stackIndex = self.localCount
self.localCount = self.localCount + 1
self.temporaries[#self.temporaries+1] = lv
lv.isTemporary = true
lv.numTempReferences = 0
lv.tempActive = true
return lv
end,
Discharge = function(self)
for _,temp in ipairs(self.temporaries) do
self.instructions[#self.instructions+1] = { op = "alloclocal", res1 = temp.vTypes[1].longName, str1 = "compiler temp", filename = self.codeLocation.filename, line = self.codeLocation.line }
end
for _,instr in ipairs(self.pendingInstructions) do
self.instructions[#self.instructions+1] = instr
end
self.pendingInstructions = { }
for _,temp in ipairs(self.temporaries) do
assert(temp.tempActive == false, "Internal error: Temporary was not properly disposed of")
self.instructions[#self.instructions+1] = { op = "removelocal", filename = self.codeLocation.filename, line = self.codeLocation.line }
self.localCount = self.localCount - 1
end
self.temporaries = { }
end,
AddInstruction = function(self, instruction)
instruction.opstackIndex = self.opstackIndex
if self.codeLocation then
assert(self.codeLocation.filename)
instruction.filename = self.codeLocation.filename
instruction.line = self.codeLocation.line
else
assert(false, "No code location!")
end
self.pendingInstructions[#self.pendingInstructions+1] = instruction
end,
AddConstantInstruction = function(self, typeName, constant, signal)
local opcode, int1, int2, res1, str1 = RDXC.Native.encodeConstant(typeName, constant, signal)
return self:AddInstruction( { op = opcode, res1 = res1, int1 = int1, int2 = int2, str1 = str1 } )
end,
PopCodeLocation = function(self, filename, line)
self.codeLocation = self.codeLocation.previous
end,
PushCodeLocation = function(self, filename, line)
assert(filename)
assert(line)
self.codeLocation = { previous = self.codeLocation, filename = filename, line = line }
end,
AppendEmissionState = function(self, ces)
local maxIdx = #self.instructions
for idx,instr in ipairs(ces.instructions) do
self.instructions[maxIdx+idx] = instr
end
end,
CreateLabel = function(self)
self.labelCount = self.labelCount + 1
return "label"..self.labelCount
end,
}
return ces
end
DumpCompiledInstructions = function(instrList)
--if true then return end
for iNum,instr in ipairs(instrList) do
local opDump = iNum..": "..instr.op
if instr.instructionNumber ~= nil then
opDump = opDump.." i "..(instr.instructionNumber)
end
if instr.reachable ~= nil then
opDump = opDump.." reachable: "..tostring(instr.reachable)
end
if instr.str1 then
opDump = opDump.." str1: "..instr.str1
end
if instr.str2 then
opDump = opDump.." str2: "..instr.str2
end
if instr.int1 then
opDump = opDump.." int1: "..instr.int1
end
if instr.int2 then
opDump = opDump.." int2: "..instr.int2
end
if instr.res1 then
opDump = opDump.." res1: "..instr.res1
end
print(opDump)
end
end
-- Tags instructions with real instruction numbers and barrier depths
local function TagInstructions(instrs, labels)
local instrCount = 0
local barrierCount = 0
for _,instr in ipairs(instrs) do
if instr.op == "startbarrier" then
barrierCount = barrierCount + 1
elseif instr.op == "endbarrier" then
barrierCount = barrierCount - 1
end
if instr.op == "label" then
labels[instr.str1] = instrCount + 1
end
if not nonInstructionOpcodes[instr.op] then
instrCount = instrCount + 1
instr.instructionNumber = instrCount
instr.barrierCount = barrierCount
end
end
end
-- This remaps any jumps that target other jumps so that they point to the same place.
local function RelinkJumps(instrList)
local activeLabels = { } -- List of labels targeting the current instruction
local remappedLabels = { }
local finalRemappedLabels = { }
local labelNames = { } -- Kept so that this is deterministic
for idx,instr in ipairs(instrList) do
if instr.op == "label" then
labelNames[#labelNames+1] = instr.str1
activeLabels[#activeLabels+1] = instr.str1
else
if instr.op == "jump" then
for _,labelName in ipairs(activeLabels) do
remappedLabels[labelName] = instr.str1
end
end
if #activeLabels ~= 0 then
activeLabels = { }
end
end
end
for _,labelName in ipairs(labelNames) do
if remappedLabels[labelName] then
for k,v in pairs(remappedLabels) do
-- If another remap targets this label, reroute it
if v == labelName then
remappedLabels[k] = remappedLabels[labelName]
end
end
finalRemappedLabels[labelName] = remappedLabels[labelName]
remappedLabels[labelName] = nil
end
end
-- Remap everything
for _,instr in ipairs(instrList) do
if instr.op == "jump" or optionalJumpOpcodes[instr.op] then
if finalRemappedLabels[instr.str1] then
instr.str1 = finalRemappedLabels[instr.str1]
end
if instr.str2 and finalRemappedLabels[instr.str2] then
instr.str2 = finalRemappedLabels[instr.str2]
end
end
end
end
local function PaintReachable(instrList, idx, labels)
-- These labels are by raw instruction number, not the assembly instruction number, so they need to be rebuilt
if labels == nil then
labels = { }
for idx,instr in ipairs(instrList) do
if instr.op == "label" then
labels[instr.str1] = idx
elseif instr.op == "alloclocal" or instr.op == "removelocal" then
instr.reachable = true -- Local manipulation ops are always relevant
end
end
end
while instrList[idx] do
local instr = instrList[idx]
local wasTagged = instr.reachable
instr.reachable = true
if optionalJumpOpcodes[instr.op] then
if wasTagged then
return
end
PaintReachable(instrList, labels[instr.str1], labels)
if instr.str2 and splittingJumpOpcodes[instr.op] then
-- Instruction has a false label, so fall-through isn't reachable
PaintReachable(instrList, labels[instr.str2], labels)
return
end
end
if instr.op == "return" then
while instrList[idx] and instrList[idx].op ~= "endbarrier" do
idx = idx + 1
end
elseif instr.op == "throw" or instr.op == "deadcode" then
return
elseif instr.op == "jump" then
if wasTagged then
return
end
idx = labels[instr.str1]
else
idx = idx + 1
end
end
end
local function CorrectBranches(instrList)
local labels = { }
local jumpNegations = {
["jumpif"] = "jumpifnot",
["jumpifnot"] = "jumpif",
["jumpiftrue"] = "jumpiffalse",
["jumpiffalse"] = "jumpiftrue",
["jumpifnull"] = "jumpifnotnull",
["jumpifnotnull"] = "jumpifnull",
["jumpifequal"] = "jumpifnotequal",
["jumpifnotequal"] = "jumpifequal",
["jump"] = "jump",
["iteratearray"] = "iteratearray",
}
-- Consolidate labels
RelinkJumps(instrList)
-- Remove dead code
do
local lastReachablePaths
local firstPathReachPass = true
while true do
local enabledPaths = { }
local numReachablePaths = 0
for _,instr in ipairs(instrList) do
if instr.op == "enablepath" and (firstPathReachPass or instr.reachable) then
local pathName = instr.str1
if not enabledPaths[pathName] then
enabledPaths[pathName] = true
numReachablePaths = numReachablePaths + 1
end
end
end
if firstPathReachPass == false then
if numReachablePaths == lastReachablePaths then
-- Didn't change the valid pass list, we're done
break
end
end
-- Convert path usage checks that didn't survive jumps, which will skip over code paths
-- that got optimized out from dead code elimination elsewhere
for _,instr in ipairs(instrList) do
if instr.op == "checkpathusage" and not enabledPaths[instr.str2] then
instr.op = "jump"
instr.str2 = nil
end
end
firstPathReachPass = false
lastReachablePaths = numReachablePaths
PaintReachable(instrList, 1)
if numReachablePaths == 0 then
break -- All guaranteed code paths were eliminated
end
end
end
TagInstructions(instrList, labels)
local newInstrList = { }
for _,instr in ipairs(instrList) do
local op = instr.op
if instr.reachable then
newInstrList[#newInstrList+1] = instr
elseif instr.op == "label" then
newInstrList[#newInstrList+1] = instr -- Labels need to stay alive to prevent span labels (i.e. exception handlers) from ending at orphan labels
elseif op == "deadcode" or op == "enablepath" then
-- Pseudo-ops, not actually emitted
elseif op == "createlocal" then
instr.op = "alloclocal" -- Local tracking needs to stay live. Other local manipulation ops are automatically reachable.
newInstrList[#newInstrList+1] = instr
end
end
instrList = newInstrList
-- Delete any useless jumps and locals
while true do
newInstrList = { }
local deletedJumps = false
local deletedCode = false
TagInstructions(instrList, labels)
local numInstr = #instrList
for idx,instr in ipairs(instrList) do
local op = instr.op
if op == "jump" and (labels[instr.str1] == instr.instructionNumber + 1) then
deletedJumps = true
elseif op == "alloclocal" and idx ~= numInstr and instrList[idx+1].op == "removelocal" then
deletedCode = true
elseif op == "removelocal" and idx ~= 1 and instrList[idx-1].op == "alloclocal" then
deletedCode = true
else
newInstrList[#newInstrList+1] = instr
end
end
instrList = newInstrList
if (not deletedJumps) and (not deletedCode) then
break
end
end
labels = { }
TagInstructions(instrList, labels)
-- Split jumps into single jump and fallthrough
newInstrList = { }
for _,instr in ipairs(instrList) do
if jumpNegations[instr.op] and instr.str2 then
assert(instr.str1 ~= instr.str2)
local trueInstr = labels[instr.str1]
local nextInstr = instr.instructionNumber + 1
local falseLabel
if trueInstr == nextInstr then
instr.op = jumpNegations[instr.op]
falseLabel = instr.str1
instr.str1 = instr.str2
else
falseLabel = instr.str2
end
instr.str2 = nil
newInstrList[#newInstrList+1] = instr
if labels[falseLabel] ~= nextInstr then
newInstrList[#newInstrList+1] = { op = "jump", str1 = falseLabel, filename = instr.filename, line = instr.line }
end
else
newInstrList[#newInstrList+1] = instr
end
end
instrList = newInstrList
TagInstructions(instrList, labels)
newInstrList = { }
for _,instr in ipairs(instrList) do
local op = instr.op
-- Convert cases to jumps now that they can't block execution flow
if op == "case" then
instr.op = "jump"
instr.doNotChangeOps = true
end
if nonInstructionOpcodes[op] then
-- Unemitted instructions
else
if jumpNegations[instr.op] or instr.op == "trycatch" then
instr.int1 = labels[instr.str1] - instr.instructionNumber
instr.str1 = nil
elseif instr.op == "try" then
instr.int1 = labels[instr.str1] - instr.instructionNumber
instr.int2 = labels[instr.str2] - instr.instructionNumber
instr.str1 = nil
instr.str2 = nil
end
newInstrList[#newInstrList+1] = instr
end
end
-- Remap code locations
for i=#newInstrList,2,-1 do
local instr = newInstrList[i]
local prevInstr = newInstrList[i-1]
assert(instr.filename and instr.line)
if instr.filename == prevInstr.filename then
instr.filename = nil
end
if instr.line == prevInstr.line then
instr.line = nil
end
end
return newInstrList
end
-- Remaps jumps to return instructions to return, used for methods that return no values. Assists with tail call optimization.
local function LinkReturnJumps(instrList)
for idx,instr in ipairs(instrList) do
if instr.op == "jump" and (not instr.doNotChangeOps) and instrList[idx + instr.int1].op == "return" then
instr.op = "return"
instr.int1 = 0
end
end
end
local function CompileMethodCode(cs, m, cacheState)
local ces = CodeEmissionState()
local codeBlockNode = cacheState:Decache(m.codeBlock)
local memberLookupScope = m.definedByType.internalScope
local thisLocal
if not m.isStatic then
memberLookupScope = MemberLookupScope(cs, memberLookupScope, m.definedByType)
end
local codeBlock = CodeBlock(cs, nil, memberLookupScope, 0)
codeBlock.isRootLevel = true
codeBlock.method = m
-- Create locals
for idx,param in ipairs(m.actualParameterList.parameters) do
local paramType = param.type.refType
local isPointer = false
if paramType.type == "CStructuredType" and VTypeIsRefStruct(paramType) then
isPointer = true
end
local isThis = (param.name.string == "this")
local isConstant = ((isPointer and param.isConst) or (isThis and not isPointer))
local l = LocalVariable(m, paramType, isPointer, isConstant)
if isThis then
thisLocal = l
end
codeBlock:CreateLocal(ces, l, param.name)
end
if not m.isStatic then
assert(thisLocal)
memberLookupScope.thisLocal = thisLocal
end
-- Create an interior code block so that the parameters and return values don't get discharged
codeBlock = CodeBlock(cs, nil, codeBlock, codeBlock.localIndex)
CompileCodeBlock(cs, ces, codeBlock, codeBlockNode)
ces:PushCodeLocation(m.name.filename, m.name.line)
ces:AddInstruction( { op = "terminate" } )
ces:Discharge()
ces:PopCodeLocation()
m.compiledInstructions = ces.instructions
--print("Method dump for "..m.longName)
m.compiledInstructions = CorrectBranches(m.compiledInstructions)
-- Strip local info if we're not emitting debug info
if not emitDebugInfo then
for _,instr in ipairs(m.compiledInstructions) do
if instr.op == "createlocal" or instr.op == "alloclocal" then
instr.str1 = nil
end
end
end
-- If this falls through to the end and there are no return args, return
if m.compiledInstructions[#m.compiledInstructions].op == "terminate" then
if #m.returnTypes.typeReferences == 0 then
local lastInstr = m.compiledInstructions[#m.compiledInstructions]
lastInstr.op = "return"
lastInstr.int1 = 0
LinkReturnJumps(m.compiledInstructions)
else
cerror(m.name, "OrphanControlPath")
end
end
cacheState:DropCache(m.codeBlock)
end
local function CompileCode(cs, cacheState, includedNamespaces)
local uncompiledCode = cs.uncompiledCode
cs.uncompiledCode = { }
for _,m in ipairs(uncompiledCode) do
local canCompile
if string.sub(m.longName, 1, 1) == "#" then
canCompile = true
else
for _,ns in ipairs(includedNamespaces) do
if string.sub(m.longName, 1, #ns) == ns then
canCompile = true
break
end
end
end
if canCompile then
local compileCodeBM
if benchmark then
compileCodeBM = { name = "compile method "..m.longName, start = RDXC.Native.msecTime() }
benchmarks[#benchmarks+1] = compileCodeBM
end
CompileMethodCode(cs, m, cacheState)
if benchmark then
compileCodeBM.endTime = RDXC.Native.msecTime()
end
end
end
end
local function CompileAll(self, cacheState, iNamespaces)
CompileTypeShells(self)
while #self.uncompiledCode > 0 do
CompileCode(self, cacheState, iNamespaces)
end
local gstAdditions = { }
for k,v in pairs(self.gst) do
if v.type == "CStructuredType" then
v.defaultValue = GetStructuredTypeDefault(self, v)
if v.defaultValue then
gstAdditions[v.defaultValue.longName] = v.defaultValue
end
end
end
for k,v in pairs(gstAdditions) do
self.gst[k] = v
end
end
RDXC.CompilerState = function()
return {
MergeParsedFile = MergeParsedFile,
CompileAll = CompileAll,
CompileTypeShells = CompileTypeShells,
globalNamespace = Namespace(nil),
uncompiled = { },
uncompiledCode = { },
defaultInstances = { },
gst = { }, -- Global symbol table
}
end
|
describe("get_attribute", function()
local icu_date = require "icu-date-ffi"
local attributes = icu_date.attributes
local date = icu_date.new()
local format = icu_date.formats.iso8601()
before_each(function()
date = icu_date.new()
date:set_millis(1507836727123)
assert.equal("2017-10-12T19:32:07.123Z", date:format(format))
end)
it("gets lenient", function()
assert.equal(1, date:get_attribute(attributes.LENIENT))
end)
it("gets first day of week", function()
assert.equal(1, date:get_attribute(attributes.FIRST_DAY_OF_WEEK))
end)
it("gets minimal days in first week", function()
assert.equal(1, date:get_attribute(attributes.MINIMAL_DAYS_IN_FIRST_WEEK))
end)
it("gets repeated wall time", function()
assert.equal(0, date:get_attribute(attributes.REPEATED_WALL_TIME))
end)
it("gets skipped wall time", function()
assert.equal(0, date:get_attribute(attributes.SKIPPED_WALL_TIME))
end)
end)
|
function SpawnPoints()
return {
constructionworker = {
{ worldX = -23 + 29, worldY = 2 + 33, posX = 155, posY = 160, posZ = 0 }
},
fireofficer = {
{ worldX = -23 + 29, worldY = 2 + 33, posX = 155, posY = 160, posZ = 0 }
},
parkranger = {
{ worldX = -23 + 29, worldY = 2 + 33, posX = 155, posY = 160, posZ = 0 }
},
policeofficer = {
{ worldX = -23 + 29, worldY = 2 + 33, posX = 155, posY = 160, posZ = 0 }
},
securityguard = {
{ worldX = -23 + 29, worldY = 2 + 33, posX = 155, posY = 160, posZ = 0 }
},
unemployed = {
{ worldX = -23 + 29, worldY = 2 + 33, posX = 155, posY = 160, posZ = 0 }
}
}
end
|
-- Optical Fiber
local util = require("__bzsilicon__.util");
data:extend(
{
{
type = "item",
name = "optical-fiber",
icon = "__bzsilicon__/graphics/icons/optical-fiber.png",
icon_size = 64, icon_mipmaps = 3,
subgroup = "intermediate-product",
order = "a[optical-fiber]",
stack_size = util.get_stack_size(200)
},
{
type = "recipe",
name = "optical-fiber",
normal =
{
enabled = false,
ingredients = {{"silica", 1}},
result = "optical-fiber",
result_count = 1
},
expensive =
{
enabled = false,
ingredients = {{"silica", 2}},
result = "optical-fiber",
result_count = 1
},
},
{
type = "technology",
name = "fiber-optics",
icon = "__bzsilicon__/graphics/technology/optical-fiber-tech.png",
icon_size = 256, icon_mipmaps = 4,
effects =
{
{
type = "unlock-recipe",
recipe = "optical-fiber"
}
},
unit =
{
count = 100,
ingredients =
{
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
},
time = 10
},
prerequisites = {"optics", "silica-processing"},
order = "b-b"
},
}
)
|
widgets = {}
widgets.Table = {}
function widgets.GetTable()
return widgets.Table
end
local widget_meta = {
Title = "",
Icon = nil,
_isvalid = true,
IsValid = function(self)
return self._isvalid
end,
DestroyEx = function(self)
self._isvalid = false
return self:Destroy()
end,
SetViewController = function(self, panel)
self.view = panel
end,
ReloadView = function(self)
return self.view:RequestReload()
end,
PanelOpened = function() end,
PanelClosed = function() end,
IsPanelOpened = function(self)
return self.view:IsOpened()
end,
OpenPanel = function(self)
return self.view:Open()
end,
ClosePanel = function(self)
return self.view:Close()
end,
}
widget_meta.__index = widget_meta
function widgets.Load()
local files = file.Find("lua/menu/remake/widgets/*.lua", "GAME")
for i = 1, #files do
local filename = files[i]
WIDGET = setmetatable({}, widget_meta)
WIDGET.__index = WIDGET
include("widgets/" .. filename)
if WIDGET.DevOnly then continue end
print("Widget Loaded: " .. WIDGET.Name)
filename = string.sub(filename, 1, #filename - 4)
widgets.Table[filename] = WIDGET
end
WIDGET = nil
end
|
-- Copyright (c) 2020 Trevor Redfern
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
describe("moonpie.test_helpers.number_assertions", function()
it("can check if a number is greater than", function()
assert.greater_than(5, 6)
assert.not_greater_than(6, 5)
end)
it("can check if a number is less than", function()
assert.less_than(4, 3)
assert.not_less_than(3, 4)
end)
it("can check if a number is in a range", function()
assert.in_range(3, 7, 4)
assert.in_range(3, 7, 3)
assert.in_range(3, 7, 7)
assert.not_in_range(3, 7, 2)
assert.not_in_range(3, 7, 9)
end)
end)
|
--[[ Return the maxLength, sizes, and non-zero count
of a batch of `seq`s ignoring `ignore` words.
--]]
local function getLength(seq, ignore)
local sizes = torch.IntTensor(#seq):zero()
local max = 0
for i = 1, #seq do
local len = seq[i]:size(1)
if ignore ~= nil then
len = len - ignore
end
if max == 0 or len > max then
max = len
end
sizes[i] = len
end
return max, sizes
end
--[[ Data management and batch creation.
Batch interface reference [size]:
* size: number of sentences in the batch [1]
* sourceLength: max length in source batch [1]
* sourceSize: lengths of each source [batch x 1]
* sourceInput: left-padded idx's of source (PPPPPPABCDE) [batch x max]
* sourceInputFeatures: table of source features sequences
* targetLength: max length in source batch [1]
* targetSize: lengths of each source [batch x 1]
* targetInput: input idx's of target (SABCDEPPPPPP) [batch x max]
* targetInputFeatures: table of target input features sequences
* targetOutput: expected output idx's of target (ABCDESPPPPPP) [batch x max]
* targetOutputFeatures: table of target output features sequences
TODO: change name of size => maxlen
--]]
--[[ A batch of sentences to translate and targets. Manages padding,
features, and batch alignment (for efficiency).
Used by the decoder and encoder objects.
--]]
local Batch = torch.class('Batch')
--[[ Create a batch object.
Parameters:
* `src` - 2D table of source batch indices or prebuilt source batch vectors
* `srcFeatures` - 2D table of source batch features (opt)
* `tgt` - 2D table of target batch indices
* `tgtFeatures` - 2D table of target batch features (opt)
--]]
function Batch:__init(src, srcFeatures, tgt, tgtFeatures)
src = src or {}
srcFeatures = srcFeatures or {}
tgtFeatures = tgtFeatures or {}
if tgt ~= nil then
assert(#src == #tgt, "source and target must have the same batch size")
end
self.inputVectors = #src > 0 and src[1]:dim() > 1
self.size = #src
self.totalSize = self.size -- Used for loss normalization.
self.sourceLength, self.sourceSize = getLength(src)
self.sourceInputFeatures = {}
-- Allocate source tensors.
if self.inputVectors then
self.sourceInput = torch.Tensor(self.sourceLength, self.size, src[1]:size(2)):fill(0.0)
else
self.sourceInput = torch.LongTensor(self.sourceLength, self.size):fill(onmt.Constants.PAD)
if #srcFeatures > 0 then
for _ = 1, #srcFeatures[1] do
table.insert(self.sourceInputFeatures, self.sourceInput:clone())
end
end
end
-- Allocate target tensors if defined.
if tgt ~= nil then
self.targetLength, self.targetSize = getLength(tgt, 1)
local targetSeq = torch.LongTensor(self.targetLength, self.size):fill(onmt.Constants.PAD)
self.targetInput = targetSeq:clone()
self.targetOutput = targetSeq:clone()
self.targetInputFeatures = {}
self.targetOutputFeatures = {}
if #tgtFeatures > 0 then
for _ = 1, #tgtFeatures[1] do
table.insert(self.targetInputFeatures, targetSeq:clone())
table.insert(self.targetOutputFeatures, targetSeq:clone())
end
end
end
-- Batch sequences.
for b = 1, self.size do
-- Source input is left padded [PPPPPPABCDE].
local window = {{self.sourceLength - self.sourceSize[b] + 1, self.sourceLength}, b}
self.sourceInput[window]:copy(src[b])
for i = 1, #self.sourceInputFeatures do
self.sourceInputFeatures[i][window]:copy(srcFeatures[b][i])
end
if tgt ~= nil then
local targetLength = tgt[b]:size(1) - 1
window = {{1, targetLength}, b}
self.targetInput[window]:copy(tgt[b]:narrow(1, 1, targetLength)) -- [<s>ABCDE]
self.targetOutput[window]:copy(tgt[b]:narrow(1, 2, targetLength)) -- [ABCDE</s>]
for i = 1, #self.targetInputFeatures do
self.targetInputFeatures[i][window]:copy(tgtFeatures[b][i]:narrow(1, 1, targetLength))
self.targetOutputFeatures[i][window]:copy(tgtFeatures[b][i]:narrow(1, 2, targetLength))
end
end
end
end
--[[ Set source input directly,
Parameters:
* `sourceInput` - a Tensor of size (sequence_length, batch_size, feature_dim)
,or a sequence of size (sequence_length, batch_size). Be aware that sourceInput is not cloned here.
--]]
function Batch:setSourceInput(sourceInput)
assert (sourceInput:dim() >= 2, 'The sourceInput tensor should be of size (seq_len, batch_size, ...)')
self.size = sourceInput:size(2)
self.sourceLength = sourceInput:size(1)
self.sourceInputFeatures = {}
self.sourceInput = sourceInput
return self
end
--[[ Set target input directly.
Parameters:
* `targetInput` - a tensor of size (sequence_length, batch_size). Padded with onmt.Constants.PAD. Be aware that targetInput is not cloned here.
--]]
function Batch:setTargetInput(targetInput)
assert (targetInput:dim() == 2, 'The targetInput tensor should be of size (seq_len, batch_size)')
self.targetInput = targetInput
self.size = targetInput:size(2)
self.totalSize = self.size
self.targetLength = targetInput:size(1)
self.targetInputFeatures = {}
self.targetSize = torch.sum(targetInput:transpose(1,2):ne(onmt.Constants.PAD), 2):view(-1):double()
return self
end
--[[ Set target output directly.
Parameters:
* `targetOutput` - a tensor of size (sequence_length, batch_size). Padded with onmt.Constants.PAD. Be aware that targetOutput is not cloned here.
--]]
function Batch:setTargetOutput(targetOutput)
assert (targetOutput:dim() == 2, 'The targetOutput tensor should be of size (seq_len, batch_size)')
self.targetOutput = targetOutput
self.targetOutputFeatures = {}
return self
end
local function addInputFeatures(inputs, featuresSeq, t)
local features = {}
for j = 1, #featuresSeq do
local feat
if t > featuresSeq[j]:size(1) then
feat = onmt.Constants.PAD
else
feat = featuresSeq[j][t]
end
table.insert(features, feat)
end
if #features > 1 then
table.insert(inputs, features)
else
onmt.utils.Table.append(inputs, features)
end
end
--[[ Get source input batch at timestep `t`. --]]
function Batch:getSourceInput(t)
-- If a regular input, return word id, otherwise a table with features.
local inputs = self.sourceInput[t]
if #self.sourceInputFeatures > 0 then
inputs = { inputs }
addInputFeatures(inputs, self.sourceInputFeatures, t)
end
return inputs
end
--[[ Get target input batch at timestep `t`. --]]
function Batch:getTargetInput(t)
-- If a regular input, return word id, otherwise a table with features.
local inputs = self.targetInput[t]
if #self.targetInputFeatures > 0 then
inputs = { inputs }
addInputFeatures(inputs, self.targetInputFeatures, t)
end
return inputs
end
--[[ Get target output batch at timestep `t` (values t+1). --]]
function Batch:getTargetOutput(t)
-- If a regular input, return word id, otherwise a table with features.
local outputs = { self.targetOutput[t] }
for j = 1, #self.targetOutputFeatures do
table.insert(outputs, self.targetOutputFeatures[j][t])
end
return outputs
end
--[[ Return true if the batch contains sequences of variable lengths. ]]
function Batch:variableLengths()
return torch.any(torch.ne(self.sourceSize, self.sourceLength))
end
--[[ Resize the source sequences, adding padding as needed. ]]
function Batch:resizeSource(newLength)
if newLength == self.sourceLength then
return
end
if newLength < self.sourceLength then
local lengthDelta = self.sourceLength - newLength
self.sourceInput = self.sourceInput:narrow(1, lengthDelta + 1, newLength)
if self.sourceInputFeatures then
for i = 1, #self.sourceInputFeatures do
self.sourceInputFeatures[i] = self.sourceInputFeatures[i]
:narrow(1, lengthDelta + 1, newLength)
end
end
self.sourceSize:cmin(newLength)
else
local lengthDelta = newLength - self.sourceLength
local newSourceInput
if self.inputVectors then
newSourceInput =
self.sourceInput.new(newLength, self.sourceInput:size(2), self.sourceInput:size(3)):fill(0.0)
else
newSourceInput =
self.sourceInput.new(newLength, self.sourceInput:size(2)):fill(onmt.Constants.PAD)
if self.sourceInputFeatures then
for i = 1, #self.sourceInputFeatures do
local newSourceInputFeature = self.sourceInputFeatures[i].new(newLength, self.size)
:fill(onmt.Constants.PAD)
:narrow(1, lengthDelta + 1, newLength - lengthDelta)
:copy(self.sourceInputFeatures[i])
self.sourceInputFeatures[i] = newSourceInputFeature
end
end
end
newSourceInput:narrow(1, lengthDelta + 1, newLength - lengthDelta):copy(self.sourceInput)
self.sourceInput = newSourceInput
end
self.sourceLength = newLength
end
function Batch:reverseSourceInPlace()
for b = 1, self.size do
local reversedIndices = torch.linspace(self.sourceSize[b], 1, self.sourceSize[b]):long()
local window = {{self.sourceLength - self.sourceSize[b] + 1, self.sourceLength}, b}
self.sourceInput[window]:copy(self.sourceInput[window]:index(1, reversedIndices))
if self.sourceInputFeatures then
self.sourceInputFeaturesRev = {}
for i = 1, #self.sourceInputFeatures do
self.sourceInputFeatures[i][window]
:copy(self.sourceInputFeatures[i][window]:index(1, reversedIndices))
end
end
end
end
return Batch
|
require("common/nativeEvent");
require("common/httpFileGrap");
DlcDownLoad = class();
DlcDownLoad.s_maxDownLoadCount = 5;
--下载类型
DlcDownLoad.s_types = {
audio = 1;
image = 2;
code = 3;
};
DlcDownLoad.getInstance = function()
if not DlcDownLoad.s_instance then
DlcDownLoad.s_instance = new(DlcDownLoad);
end
return DlcDownLoad.s_instance;
end
DlcDownLoad.releaseInstance = function(self)
delete(DlcDownLoad.s_instance);
DlcDownLoad.s_instance = nil;
end
DlcDownLoad.ctor = function(self)
EventDispatcher.getInstance():register(Event.Call,self,self.onNativeEvent);
end
DlcDownLoad.dtor = function(self)
EventDispatcher.getInstance():unregister(Event.Call,self,self.onNativeEvent);
end
-----------------------------------public-------------------------------
DlcDownLoad.startDownLoad = function(self)
local existTypes = {};
for _,config in pairs( DlcDownLoad.s_config ) do
if self:downLoadFileByConfig(config) then
local key = config.type;
existTypes[key] = existTypes[key] or key;
end
end
for _,key in pairs(existTypes) do
DlcDownLoad.s_typeFucMap[key](self);
end
end
DlcDownLoad.downLoadFileByConfig = function(self , config)
if not config or type(config) ~= "table" then
return;
end
--避免无限下载
config.downloadCount = config.downloadCount and (config.downloadCount+1) or 1;
if config.downloadCount > DlcDownLoad.s_maxDownLoadCount then
return false;
end
local url = config.url or "";
local fileName = config.fileName or "";
local unCompressFilePath = config.unCompressFilePath or "";
local md5 = config.md5 or "";
if self:checkIsFileExit(unCompressFilePath .. md5 ..".txt") then
--表明文件已经存在
return true;
elseif self:checkIsFileExit(fileName) then
NativeEvent.getInstance():unZipFileForLua(fileName,unCompressFilePath);
elseif NativeEvent.getInstance():getNetworkType() == 1 then
HttpFileGrap.getInstance():grapFile(
url,
fileName,
15000,
self,
self.onFileDownloadCallback);
else
--do nothing;
end
return false;
end
DlcDownLoad.onFileDownloadCallback = function(self , isSucessed, fileName, url)
local config = self:getFileConfigByFileName(fileName);
if not config then
return;
end
if isSucessed then
--应该验证MD5
NativeEvent.getInstance():unZipFileForLua(fileName , config.unCompressFilePath or "");
else
self:downLoadFileByConfig(config);
end
end
DlcDownLoad.onUnCompressFinishCallback = function(self ,status , jsonTable)
if not (status and jsonTable) then
return;
end
local fileName = GetStrFromJsonTable(jsonTable, "zipFilePath","");
local config = self:getFileConfigByFileName(fileName);
if not config then
return;
end
local result = GetNumFromJsonTable(jsonTable, "result",0);--1:成功 0:失败
local unCompressHandleFuc = config.unCompressHandleFuc or DlcDownLoad.defaultUnCompressHandle;
unCompressHandleFuc(self,tonumber(result) == 1,fileName);
end
--------------------------------------------private---------------------------------
--解压文件成功后的回调函数
DlcDownLoad.defaultUnCompressHandle = function(self,isSucessed,fileName)
local config = self:getFileConfigByFileName(fileName);
if not isSucessed then
if config then
self:downLoadFileByConfig(config);
end
else
if config then
self:createFile( config.unCompressFilePath .. config.md5 ..".txt" );
if config.type and DlcDownLoad.s_typeFucMap[config.type] then
DlcDownLoad.s_typeFucMap[config.type](self);
end
end
end
end
--下载声音前的初始化
DlcDownLoad.preDownLoadAudio = function(self)
local effectSearchPath = System.getStorageAudioPath();
System.pushFrontAudioSearchPath(effectSearchPath);
end
--下载图片前的初始化
DlcDownLoad.preDownLoadImage = function(self)
local imageSearchPath = System.getStorageImagePath();
System.pushFrontImageSearchPath(imageSearchPath);
end
--下载代码前的初始化
DlcDownLoad.preDownLoadCode = function(self)
end
-----------------------------------------------------------------------------------
--检查文件是否存在 note:不能检查文件夹
DlcDownLoad.checkIsFileExit = function(self , filePath)
local f = io.open(filePath or "");
if f then
io.close(f);
return true;
else
return false;
end
end
DlcDownLoad.createFile = function(self , filePath)
local f = io.open(filePath,'w');
if f then
io.close(f);
end
end
DlcDownLoad.getFileConfigByFileName = function(self , fileName)
for _,config in pairs( DlcDownLoad.s_config ) do
if config.fileName == fileName then
return config;
end
end
return nil;
end
DlcDownLoad.onNativeEvent = function(self,param,...)
if self.s_nativeEventFuncMap[param] then
self.s_nativeEventFuncMap[param](self,...);
end
end
DlcDownLoad.s_typeFucMap = {
[DlcDownLoad.s_types.audio] = DlcDownLoad.preDownLoadAudio;
[DlcDownLoad.s_types.image] = DlcDownLoad.preDownLoadImage;
[DlcDownLoad.s_types.code] = DlcDownLoad.preDownLoadCode;
};
DlcDownLoad.s_config = {
-- [1] = {
-- ["type"] = DlcDownLoad.s_types.audio;
-- ["url"] = ServerConfig.getInstance():getCDN() .."effect_v2/chat.zip";
-- ["fileName"] = System.getStorageUserPath() .. "audio/chat.zip";
-- ["unCompressFilePath"] = System.getStorageUserPath() .. "audio/ogg/effect/chat/";
-- ["md5"] = "5171df1c8e0058c7db4b4bbc0d711f4d";
-- --["unCompressHandleFuc"] =
-- };
};
DlcDownLoad.s_nativeEventFuncMap = {
["unZipFileForLua"] = DlcDownLoad.onUnCompressFinishCallback;
};
|
--[[
Meta Portal Slideshow - README
v0.1.0 - 2021/5/27
Developed by: Divided (META) (https://www.coregames.com/user/eaba4947069846dbb72fc5efb0f04f47)
Modified by: Morticai (META) (https://www.coregames.com/user/d1073dbcc404405cbef8ce728e53d380)
This package is a work in progress.
Description:
Meta Portal Slideshow is a simple component that allows creators to upload custom images that can
be used in their game to provide information to players, such as how to play, game updates, and item
showcasing.
Setup
=====
1. To begin adjusting how the Portal Slideshow system first selects the SlideshowSettings Client Context.
2. Once selected you'll see several options available to you:
1) Enabled - Make sure this is checked to enable the component.
2) ToggleUIKeybind - The keybind players will use to toggle the tutorial on / off. T is the default.
3) LeftJumpKeybind - Keybind players can press to move left in the slideshow. The left arrow key is the default.
4) RightJumpKeybind - Keybind players can press to move right in the slideshow. The right arrow key is the default.
5) TotalImages - The total amount of images to be shown in your slide show.
6) ImageSpacing - The width of each image in the slide show. Default is 1000, which has no spacing between images.
Increasing this to say 1200 will add a slight gap between each image in the slide show.
7) ImageZoom - Increasing this number will make the images further from the players screen. Setting this to 5 will
make the image fullscreen.
Adding Images
=============
1. To add images to your slideshow, you first must upload the images to a live Core Game. The game can be a blank
unlisted project, to better organize your images. When publishing the game, simply add your images as screenshots.
2. Once published, save the link somewhere it's easily accessible on your computer.
You should have a link such as:
https://www.coregames.com/games/1b3aa6/meta-portal-image-examples
3. Copy Game ID info in the link to your clipboard such as:
1b3aa6/meta-portal-image-examples
4. Under SlideshowSettings > ScreenGroup > Pivot
There will be five Game Portals as default. Simply click on each portal and change the Game ID to the Game ID where your images will be stored.
Note: Multiple projects can be used if your game requires more than 5 slideshow images. Simply repeat all steps above
but make sure to adjust the Screenshot Index of the new images to match up with the index of any further published
screenshot games.
]]--
|
function prerender()
end
function prerender()
local t = fbotest
glViewport(0,0,256,256)
glMatrixModeProjection()
glLoadIdentity()
glPerspective(60.0, 1, 1.0, 100.0)
glMatrixModeModelView()
glLoadIdentity()
glTranslate(0, 0, -10)
glBindFramebuffer(t.fboId)
glClearColor(255, 255, 0, 255)
glClear()
--glUseProgram(progId)
colorGL(255,0,0,255)
glPushMatrix()
--glRotatef(angle*0.5f, 1, 0, 0);
--glRotatef(angle, 0, 1, 0);
--glRotatef(angle*0.7f, 0, 0, 1);
glTranslate(0, -2, 0);
--drawTeapot()
--for i=1,18,1 do
glutWireSphere(3)
--end
enableTexturing()
glBindTexture(t.texId)
if false then
beginQuadGL()
colorGL(255,255,255,255)
local qs = 5
texGL(0,0) vectorGL(0,0,0)
texGL(1,0) vectorGL(qs,0,0)
texGL(1,1) vectorGL(qs,qs,0)
texGL(0,1) vectorGL(0,qs,0)
endGL()
end
glPopMatrix()
disableTexturing()
--glUseProgram(0);
glBindFramebuffer(0);
glBindTexture(t.texId);
glGenerateMipmap();
glBindTexture(0);
end
|
local http_ng_response = require('resty.http_ng.response')
local lrucache = require('resty.lrucache')
local configuration_store = require 'apicast.configuration_store'
local Service = require 'apicast.configuration.service'
local Usage = require 'apicast.usage'
local test_backend_client = require 'resty.http_ng.backend.test'
local errors = require 'apicast.errors'
describe('Proxy', function()
local configuration, proxy, test_backend
before_each(function()
configuration = configuration_store.new()
proxy = require('apicast.proxy').new(configuration)
test_backend = test_backend_client.new()
proxy.http_ng_backend = test_backend
end)
it('has access function', function()
assert.truthy(proxy.access)
assert.same('function', type(proxy.access))
end)
describe(':rewrite', function()
local service
before_each(function()
-- Replace original ngx.header. Openresty does not allow to modify it when
-- running busted tests.
ngx.header = {}
ngx.var = { backend_endpoint = 'http://localhost:1853', uri = '/a/uri' }
stub(ngx.req, 'get_method', function () return 'GET' end)
service = Service.new({ extract_usage = function() end })
end)
it('works with part of the credentials', function()
service.credentials = { location = 'headers' }
service.backend_version = 2
ngx.var.http_app_key = 'key'
local context = {}
assert.falsy(proxy:rewrite(service, context))
end)
end)
it('has post_action function', function()
assert.truthy(proxy.post_action)
assert.same('function', type(proxy.post_action))
end)
describe('.get_upstream', function()
local get_upstream
before_each(function() get_upstream = proxy.get_upstream end)
it('sets correct upstream port', function()
assert.same(443, get_upstream({ api_backend = 'https://example.com' }):port())
assert.same(80, get_upstream({ api_backend = 'http://example.com' }):port())
assert.same(8080, get_upstream({ api_backend = 'http://example.com:8080' }):port())
end)
end)
describe('.authorize', function()
local service = { backend_authentication = { value = 'not_baz' }, backend = { endpoint = 'http://0.0.0.0' } }
it('takes ttl value if sent', function()
local ttl = 80
ngx.var = { cached_key = 'client_id=blah', http_x_3scale_debug='baz', real_url='blah' }
local response = { status = 200 }
stub(test_backend, 'send', function() return response end)
stub(proxy, 'cache_handler').returns(true)
local usage = Usage.new()
usage:add('foo', 0)
proxy:authorize(service, usage, { client_id = 'blah' }, ttl)
assert.spy(proxy.cache_handler).was.called_with(
proxy.cache, 'client_id=blah:usage%5Bfoo%5D=0', response, ttl)
end)
it('works with no ttl', function()
ngx.var = { cached_key = "client_id=blah", http_x_3scale_debug='baz', real_url='blah' }
local response = { status = 200 }
stub(test_backend, 'send', function() return response end)
stub(proxy, 'cache_handler').returns(true)
local usage = Usage.new()
usage:add('foo', 0)
proxy:authorize(service, usage, { client_id = 'blah' })
assert.spy(proxy.cache_handler).was.called_with(
proxy.cache, 'client_id=blah:usage%5Bfoo%5D=0', response, nil)
end)
it('does not use cached auth if creds are the same but extra authrep params are not', function()
proxy.extra_params_backend_authrep = { referrer = '3scale.net' }
stub(test_backend, 'send', function() return { status = 200 } end)
local usage = Usage.new()
usage:add('hits', 1)
local cache_key = "uk:usage%5Bhits%5D=1" -- Referrer not here
proxy.cache:set(cache_key, 200)
ngx.var = { cached_key = "uk" } -- authorize() expects creds to be set up
proxy:authorize(service, usage, { user_key = 'uk' })
-- Calls backend because the call is not cached
assert.stub(test_backend.send).was_called()
end)
it('uses cached auth if creds are the same and authrep params too', function()
proxy.extra_params_backend_authrep = { referrer = '3scale.net' }
stub(test_backend, 'send', function() return { status = 200 } end)
local usage = Usage.new()
usage:add('hits', 1)
local cache_key = "uk:usage%5Bhits%5D=1:referrer=3scale.net" -- Referrer here
proxy.cache:set(cache_key, 200)
ngx.var = { cached_key = "uk" } -- authorize() expects creds to be set up
proxy:authorize(service, usage, { user_key = 'uk' })
-- Does not call backend because the call is cached
assert.stub(test_backend.send).was_not_called()
end)
it('returns "limits exceeded" with the "Retry-After" given by the 3scale backend', function()
ngx.header = {}
ngx.var = { cached_key = "uk" } -- authorize() expects creds to be set up
stub(errors, 'limits_exceeded')
local retry_after = 60
local usage = Usage.new()
usage:add('hits', 1)
test_backend.expect({}).respond_with(
{
status = 409,
headers = {
['3scale-limit-reset'] = retry_after,
['3scale-rejection-reason'] = 'limits_exceeded'
}
}
)
proxy:authorize(service, usage, { user_key = 'uk' })
assert.stub(errors.limits_exceeded).was_called_with(service, retry_after)
end)
end)
describe('.handle_backend_response', function()
it('returns a rejection reason when given', function()
local authorized, rejection_reason = proxy:handle_backend_response(
lrucache.new(1),
http_ng_response.new(nil, 403, { ['3scale-rejection-reason'] = 'some_reason' }, ''),
nil)
assert.falsy(authorized)
assert.equal('some_reason', rejection_reason)
end)
describe('when backend is unavailable', function()
local backend_unavailable_statuses = { 0, 499, 502 } -- Not exhaustive
local cache_key = 'a_cache_key'
before_each(function()
-- So we can set the value for the cached auth ensuring that the
-- handler will not modify it.
proxy.cache_handler = function() end
end)
it('returns true when the cached authorization is authorized', function()
proxy.cache:set(cache_key, 200)
for _, status in ipairs(backend_unavailable_statuses) do
local authorized = proxy:handle_backend_response(cache_key, { status = status })
assert(authorized)
end
end)
it('returns false when the authorization is not cached', function()
proxy.cache:delete(cache_key)
for _, status in ipairs(backend_unavailable_statuses) do
local authorized = proxy:handle_backend_response(cache_key, { status = status })
assert.falsy(authorized)
end
end)
it('returns false when the authorization is cached and denied', function()
proxy.cache:set(cache_key, 429)
for _, status in ipairs(backend_unavailable_statuses) do
local authorized = proxy:handle_backend_response(cache_key, { status = status })
assert.falsy(authorized)
end
end)
end)
end)
end)
|
resource_manifest_version '77731fab-63ca-442c-a67b-abc70f28dfa5'
client_script 'drift_client.lua'
|
return {
[200] = {
"HTTP/1.1 200 OK",
"Server: esp8266",
"Content-Type: text/html charset=utf8",
"Connection: Closed"
},
[301] = {
"HTTP/1.1 301 Moved Permanently",
"Server: esp8266",
"Content-Type: text/html charset=utf8",
"Location: /",
"Cache-Control: no-cache, must-revalidate",
"Pragma: no-cache",
"Connection: Closed"
},
[404] = {
"HTTP/1.1 404 Not Found",
"Server: esp8266",
"Content-Type: text/html charset=utf8",
"Cache-Control: no-cache, must-revalidate",
"Pragma: no-cache",
"Connection: Closed"
}
}
|
local View = require("reacher.view").View
local Matcher = require("reacher.core.matcher").Matcher
local messagelib = require("reacher.lib.message")
local vim = vim
local M = {}
local Command = {}
Command.__index = Command
M.Command = Command
function Command.new(name, ...)
local args = {...}
local f = function()
return Command[name](unpack(args))
end
local ok, msg = xpcall(f, debug.traceback)
if not ok then
return messagelib.error(msg)
elseif msg then
return messagelib.warn(msg)
end
end
Command.last_call = nil
function Command.start_one(raw_opts)
local msg = messagelib.validate({opts = {raw_opts, "table", true}})
if msg then
return msg
end
local old = View.current()
if old then
old:close()
end
local opts = vim.tbl_deep_extend("force", {matcher_opts = {name = "regex"}}, raw_opts or {})
local matcher, err = Matcher.new(opts.matcher_opts.name)
if err then
return err
end
local call = function(extend_opts)
return View.open_one(matcher, vim.tbl_deep_extend("force", opts, extend_opts or {}))
end
Command.last_call = call
return call()
end
function Command.start_multiple(raw_opts)
local msg = messagelib.validate({opts = {raw_opts, "table", true}})
if msg then
return msg
end
local old = View.current()
if old then
old:close()
end
local opts = vim.tbl_deep_extend("force", {matcher_opts = {name = "regex"}}, raw_opts or {})
local matcher, err = Matcher.new(opts.matcher_opts.name)
if err then
return err
end
local call = function(extend_opts)
return View.open_multiple(matcher, vim.tbl_deep_extend("force", opts, extend_opts or {}))
end
Command.last_call = call
return call()
end
function Command.again(extend_opts)
local msg = messagelib.validate({opts = {extend_opts, "table", true}})
if msg then
return msg
end
local old = View.current()
if old then
old:close()
end
if not Command.last_call then
return Command.start_one(extend_opts)
end
return Command.last_call(extend_opts)
end
function Command.move_cursor(action_name)
vim.validate({action_name = {action_name, "string"}})
local view, err = View.current()
if err then
return err
end
view:move_cursor(action_name)
end
function Command.finish()
local view, err = View.current()
if err then
return err
end
local row, column = view:finish()
if row then
messagelib.info(("jumped to (%d, %d)"):format(row, column))
end
end
function Command.recall_history(offset)
vim.validate({offset = {offset, "number"}})
local view, err = View.current()
if err then
return err
end
view:recall_history(offset)
end
function Command.cancel()
local view, err = View.current()
if err then
return
end
view:cancel()
messagelib.info("canceled")
end
function Command.close(id)
vim.validate({id = {id, "number"}})
local view = View.get(id)
if not view then
return
end
view:cancel()
end
return M
|
local combat = Combat()
combat:setParameter(COMBAT_PARAM_TYPE, COMBAT_FIREDAMAGE)
combat:setParameter(COMBAT_PARAM_DISTANCEEFFECT, CONST_ANI_FIRE)
local condition = Condition(CONDITION_FIRE)
condition:setParameter(CONDITION_PARAM_DELAYED, 1)
condition:addDamage(25, 3000, -45)
combat:setCondition(condition)
function onCastSpell(creature, var)
return combat:execute(creature, var)
end
|
local options =
{
frames =
{
{x=0,y=0,width=96,height=96,}, -- frame 1
{x=96,y=0,width=96,height=96,}, -- frame 2
{x=192,y=0,width=96,height=96,}, -- frame 3
{x=288,y=0,width=96,height=96,}, -- frame 4
{x=384,y=0,width=96,height=96,}, -- frame 5
{x=480,y=0,width=96,height=96,}, -- frame 6
{x=576,y=0,width=96,height=96,}, -- frame 7
{x=672,y=0,width=96,height=96,}, -- frame 8
{x=768,y=0,width=96,height=96,}, -- frame 9
{x=864,y=0,width=96,height=96,}, -- frame 10
{x=960,y=0,width=96,height=96,}, -- frame 11
{x=1056,y=0,width=96,height=96,}, -- frame 12
{x=1152,y=0,width=96,height=96,}, -- frame 13
{x=1248,y=0,width=96,height=96,}, -- frame 14
{x=1344,y=0,width=96,height=96,}, -- frame 15
{x=1440,y=0,width=96,height=96,}, -- frame 16
{x=0,y=96,width=96,height=96,}, -- frame 17
{x=96,y=96,width=96,height=96,}, -- frame 18
{x=192,y=96,width=96,height=96,}, -- frame 19
{x=288,y=96,width=96,height=96,}, -- frame 20
{x=384,y=96,width=96,height=96,}, -- frame 21
{x=480,y=96,width=96,height=96,}, -- frame 22
{x=576,y=96,width=96,height=96,}, -- frame 23
{x=672,y=96,width=96,height=96,}, -- frame 24
{x=768,y=96,width=96,height=96,}, -- frame 25
{x=864,y=96,width=96,height=96,}, -- frame 26
{x=960,y=96,width=96,height=96,}, -- frame 27
{x=1056,y=96,width=96,height=96,}, -- frame 28
{x=1152,y=96,width=96,height=96,}, -- frame 29
{x=1248,y=96,width=96,height=96,}, -- frame 30
{x=1344,y=96,width=96,height=96,}, -- frame 31
{x=1440,y=96,width=96,height=96,}, -- frame 32
{x=0,y=192,width=96,height=96,}, -- frame 33
{x=96,y=192,width=96,height=96,}, -- frame 34
{x=192,y=192,width=96,height=96,}, -- frame 35
{x=288,y=192,width=96,height=96,}, -- frame 36
{x=384,y=192,width=96,height=96,}, -- frame 37
{x=480,y=192,width=96,height=96,}, -- frame 38
{x=576,y=192,width=96,height=96,}, -- frame 39
{x=672,y=192,width=96,height=96,}, -- frame 40
{x=768,y=192,width=96,height=96,}, -- frame 41
{x=864,y=192,width=96,height=96,}, -- frame 42
{x=960,y=192,width=96,height=96,}, -- frame 43
{x=1056,y=192,width=96,height=96,}, -- frame 44
{x=1152,y=192,width=96,height=96,}, -- frame 45
{x=1248,y=192,width=96,height=96,}, -- frame 46
{x=1344,y=192,width=96,height=96,}, -- frame 47
{x=1440,y=192,width=96,height=96,}, -- frame 48
{x=0,y=288,width=96,height=96,}, -- frame 49
{x=96,y=288,width=96,height=96,}, -- frame 50
{x=192,y=288,width=96,height=96,}, -- frame 51
{x=288,y=288,width=96,height=96,}, -- frame 52
{x=384,y=288,width=96,height=96,}, -- frame 53
{x=480,y=288,width=96,height=96,}, -- frame 54
{x=576,y=288,width=96,height=96,}, -- frame 55
{x=672,y=288,width=96,height=96,}, -- frame 56
{x=768,y=288,width=96,height=96,}, -- frame 57
{x=864,y=288,width=96,height=96,}, -- frame 58
{x=960,y=288,width=96,height=96,}, -- frame 59
{x=1056,y=288,width=96,height=96,}, -- frame 60
{x=1152,y=288,width=96,height=96,}, -- frame 61
{x=1248,y=288,width=96,height=96,}, -- frame 62
{x=1344,y=288,width=96,height=96,}, -- frame 63
{x=1440,y=288,width=96,height=96,}, -- frame 64
{x=0,y=384,width=96,height=96,}, -- frame 65
{x=96,y=384,width=96,height=96,}, -- frame 66
{x=192,y=384,width=96,height=96,}, -- frame 67
{x=288,y=384,width=96,height=96,}, -- frame 68
{x=384,y=384,width=96,height=96,}, -- frame 69
{x=480,y=384,width=96,height=96,}, -- frame 70
{x=576,y=384,width=96,height=96,}, -- frame 71
{x=672,y=384,width=96,height=96,}, -- frame 72
{x=768,y=384,width=96,height=96,}, -- frame 73
{x=864,y=384,width=96,height=96,}, -- frame 74
{x=960,y=384,width=96,height=96,}, -- frame 75
{x=1056,y=384,width=96,height=96,}, -- frame 76
{x=1152,y=384,width=96,height=96,}, -- frame 77
{x=1248,y=384,width=96,height=96,}, -- frame 78
{x=1344,y=384,width=96,height=96,}, -- frame 79
{x=1440,y=384,width=96,height=96,}, -- frame 80
{x=0,y=480,width=96,height=96,}, -- frame 81
{x=96,y=480,width=96,height=96,}, -- frame 82
{x=192,y=480,width=96,height=96,}, -- frame 83
{x=288,y=480,width=96,height=96,}, -- frame 84
{x=384,y=480,width=96,height=96,}, -- frame 85
{x=480,y=480,width=96,height=96,}, -- frame 86
{x=576,y=480,width=96,height=96,}, -- frame 87
{x=672,y=480,width=96,height=96,}, -- frame 88
{x=768,y=480,width=96,height=96,}, -- frame 89
{x=864,y=480,width=96,height=96,}, -- frame 90
{x=960,y=480,width=96,height=96,}, -- frame 91
{x=1056,y=480,width=96,height=96,}, -- frame 92
{x=1152,y=480,width=96,height=96,}, -- frame 93
{x=1248,y=480,width=96,height=96,}, -- frame 94
{x=1344,y=480,width=96,height=96,}, -- frame 95
{x=1440,y=480,width=96,height=96,}, -- frame 96
{x=0,y=576,width=96,height=96,}, -- frame 97
{x=96,y=576,width=96,height=96,}, -- frame 98
{x=192,y=576,width=96,height=96,}, -- frame 99
{x=288,y=576,width=96,height=96,}, -- frame 100
{x=384,y=576,width=96,height=96,}, -- frame 101
{x=480,y=576,width=96,height=96,}, -- frame 102
{x=576,y=576,width=96,height=96,}, -- frame 103
{x=672,y=576,width=96,height=96,}, -- frame 104
{x=768,y=576,width=96,height=96,}, -- frame 105
{x=864,y=576,width=96,height=96,}, -- frame 106
{x=960,y=576,width=96,height=96,}, -- frame 107
{x=1056,y=576,width=96,height=96,}, -- frame 108
{x=1152,y=576,width=96,height=96,}, -- frame 109
{x=1248,y=576,width=96,height=96,}, -- frame 110
{x=1344,y=576,width=96,height=96,}, -- frame 111
{x=1440,y=576,width=96,height=96,}, -- frame 112
{x=0,y=672,width=96,height=96,}, -- frame 113
{x=96,y=672,width=96,height=96,}, -- frame 114
{x=192,y=672,width=96,height=96,}, -- frame 115
{x=288,y=672,width=96,height=96,}, -- frame 116
{x=384,y=672,width=96,height=96,}, -- frame 117
{x=480,y=672,width=96,height=96,}, -- frame 118
{x=576,y=672,width=96,height=96,}, -- frame 119
{x=672,y=672,width=96,height=96,}, -- frame 120
{x=768,y=672,width=96,height=96,}, -- frame 121
{x=864,y=672,width=96,height=96,}, -- frame 122
{x=960,y=672,width=96,height=96,}, -- frame 123
{x=1056,y=672,width=96,height=96,}, -- frame 124
{x=1152,y=672,width=96,height=96,}, -- frame 125
{x=1248,y=672,width=96,height=96,}, -- frame 126
{x=1344,y=672,width=96,height=96,}, -- frame 127
{x=1440,y=672,width=96,height=96,}, -- frame 128
{x=0,y=768,width=96,height=96,}, -- frame 129
{x=96,y=768,width=96,height=96,}, -- frame 130
{x=192,y=768,width=96,height=96,}, -- frame 131
{x=288,y=768,width=96,height=96,}, -- frame 132
{x=384,y=768,width=96,height=96,}, -- frame 133
{x=480,y=768,width=96,height=96,}, -- frame 134
{x=576,y=768,width=96,height=96,}, -- frame 135
{x=672,y=768,width=96,height=96,}, -- frame 136
{x=768,y=768,width=96,height=96,}, -- frame 137
{x=864,y=768,width=96,height=96,}, -- frame 138
{x=960,y=768,width=96,height=96,}, -- frame 139
{x=1056,y=768,width=96,height=96,}, -- frame 140
{x=1152,y=768,width=96,height=96,}, -- frame 141
{x=1248,y=768,width=96,height=96,}, -- frame 142
{x=1344,y=768,width=96,height=96,}, -- frame 143
{x=1440,y=768,width=96,height=96,}, -- frame 144
{x=0,y=864,width=96,height=96,}, -- frame 145
{x=96,y=864,width=96,height=96,}, -- frame 146
{x=192,y=864,width=96,height=96,}, -- frame 147
{x=288,y=864,width=96,height=96,}, -- frame 148
{x=384,y=864,width=96,height=96,}, -- frame 149
{x=480,y=864,width=96,height=96,}, -- frame 150
{x=576,y=864,width=96,height=96,}, -- frame 151
{x=672,y=864,width=96,height=96,}, -- frame 152
{x=768,y=864,width=96,height=96,}, -- frame 153
{x=864,y=864,width=96,height=96,}, -- frame 154
{x=960,y=864,width=96,height=96,}, -- frame 155
{x=1056,y=864,width=96,height=96,}, -- frame 156
{x=1152,y=864,width=96,height=96,}, -- frame 157
{x=1248,y=864,width=96,height=96,}, -- frame 158
{x=1344,y=864,width=96,height=96,}, -- frame 159
{x=1440,y=864,width=96,height=96,}, -- frame 160
{x=0,y=960,width=96,height=96,}, -- frame 161
{x=96,y=960,width=96,height=96,}, -- frame 162
{x=192,y=960,width=96,height=96,}, -- frame 163
{x=288,y=960,width=96,height=96,}, -- frame 164
{x=384,y=960,width=96,height=96,}, -- frame 165
{x=480,y=960,width=96,height=96,}, -- frame 166
{x=576,y=960,width=96,height=96,}, -- frame 167
{x=672,y=960,width=96,height=96,}, -- frame 168
{x=768,y=960,width=96,height=96,}, -- frame 169
{x=864,y=960,width=96,height=96,}, -- frame 170
{x=960,y=960,width=96,height=96,}, -- frame 171
{x=1056,y=960,width=96,height=96,}, -- frame 172
{x=1152,y=960,width=96,height=96,}, -- frame 173
{x=1248,y=960,width=96,height=96,}, -- frame 174
{x=1344,y=960,width=96,height=96,}, -- frame 175
{x=1440,y=960,width=96,height=96,}, -- frame 176
{x=0,y=1056,width=96,height=96,}, -- frame 177
{x=96,y=1056,width=96,height=96,}, -- frame 178
{x=192,y=1056,width=96,height=96,}, -- frame 179
{x=288,y=1056,width=96,height=96,}, -- frame 180
{x=384,y=1056,width=96,height=96,}, -- frame 181
{x=480,y=1056,width=96,height=96,}, -- frame 182
{x=576,y=1056,width=96,height=96,}, -- frame 183
{x=672,y=1056,width=96,height=96,}, -- frame 184
{x=768,y=1056,width=96,height=96,}, -- frame 185
{x=864,y=1056,width=96,height=96,}, -- frame 186
{x=960,y=1056,width=96,height=96,}, -- frame 187
{x=1056,y=1056,width=96,height=96,}, -- frame 188
{x=1152,y=1056,width=96,height=96,}, -- frame 189
{x=1248,y=1056,width=96,height=96,}, -- frame 190
{x=1344,y=1056,width=96,height=96,}, -- frame 191
{x=1440,y=1056,width=96,height=96,}, -- frame 192
{x=0,y=1152,width=96,height=96,}, -- frame 193
{x=96,y=1152,width=96,height=96,}, -- frame 194
{x=192,y=1152,width=96,height=96,}, -- frame 195
{x=288,y=1152,width=96,height=96,}, -- frame 196
{x=384,y=1152,width=96,height=96,}, -- frame 197
{x=480,y=1152,width=96,height=96,}, -- frame 198
{x=576,y=1152,width=96,height=96,}, -- frame 199
{x=672,y=1152,width=96,height=96,}, -- frame 200
{x=768,y=1152,width=96,height=96,}, -- frame 201
{x=864,y=1152,width=96,height=96,}, -- frame 202
{x=960,y=1152,width=96,height=96,}, -- frame 203
{x=1056,y=1152,width=96,height=96,}, -- frame 204
{x=1152,y=1152,width=96,height=96,}, -- frame 205
{x=1248,y=1152,width=96,height=96,}, -- frame 206
{x=1344,y=1152,width=96,height=96,}, -- frame 207
{x=1440,y=1152,width=96,height=96,}, -- frame 208
{x=0,y=1248,width=96,height=96,}, -- frame 209
{x=96,y=1248,width=96,height=96,}, -- frame 210
{x=192,y=1248,width=96,height=96,}, -- frame 211
{x=288,y=1248,width=96,height=96,}, -- frame 212
{x=384,y=1248,width=96,height=96,}, -- frame 213
{x=480,y=1248,width=96,height=96,}, -- frame 214
{x=576,y=1248,width=96,height=96,}, -- frame 215
{x=672,y=1248,width=96,height=96,}, -- frame 216
{x=768,y=1248,width=96,height=96,}, -- frame 217
{x=864,y=1248,width=96,height=96,}, -- frame 218
{x=960,y=1248,width=96,height=96,}, -- frame 219
{x=1056,y=1248,width=96,height=96,}, -- frame 220
{x=1152,y=1248,width=96,height=96,}, -- frame 221
{x=1248,y=1248,width=96,height=96,}, -- frame 222
{x=1344,y=1248,width=96,height=96,}, -- frame 223
{x=1440,y=1248,width=96,height=96,}, -- frame 224
{x=0,y=1344,width=96,height=96,}, -- frame 225
{x=96,y=1344,width=96,height=96,}, -- frame 226
{x=192,y=1344,width=96,height=96,}, -- frame 227
{x=288,y=1344,width=96,height=96,}, -- frame 228
{x=384,y=1344,width=96,height=96,}, -- frame 229
{x=480,y=1344,width=96,height=96,}, -- frame 230
{x=576,y=1344,width=96,height=96,}, -- frame 231
{x=672,y=1344,width=96,height=96,}, -- frame 232
{x=768,y=1344,width=96,height=96,}, -- frame 233
{x=864,y=1344,width=96,height=96,}, -- frame 234
{x=960,y=1344,width=96,height=96,}, -- frame 235
{x=1056,y=1344,width=96,height=96,}, -- frame 236
{x=1152,y=1344,width=96,height=96,}, -- frame 237
{x=1248,y=1344,width=96,height=96,}, -- frame 238
{x=1344,y=1344,width=96,height=96,}, -- frame 239
{x=1440,y=1344,width=96,height=96,}, -- frame 240
{x=0,y=1440,width=96,height=96,}, -- frame 241
{x=96,y=1440,width=96,height=96,}, -- frame 242
{x=192,y=1440,width=96,height=96,}, -- frame 243
{x=288,y=1440,width=96,height=96,}, -- frame 244
{x=384,y=1440,width=96,height=96,}, -- frame 245
{x=480,y=1440,width=96,height=96,}, -- frame 246
{x=576,y=1440,width=96,height=96,}, -- frame 247
{x=672,y=1440,width=96,height=96,}, -- frame 248
{x=768,y=1440,width=96,height=96,}, -- frame 249
{x=864,y=1440,width=96,height=96,}, -- frame 250
{x=960,y=1440,width=96,height=96,}, -- frame 251
{x=1056,y=1440,width=96,height=96,}, -- frame 252
{x=1152,y=1440,width=96,height=96,}, -- frame 253
{x=1248,y=1440,width=96,height=96,}, -- frame 254
{x=1344,y=1440,width=96,height=96,}, -- frame 255
{x=1440,y=1440,width=96,height=96,}, -- frame 256
}
}
return options
|
local _M = {}
local API_VERSION = 1
function _M.index()
entry({"lm", "api"}, alias({"lm", "api", "version"}))
entry({"lm", "api", "version"}, call("action_api_version"))
entry({"lm", "api", "status"}, call("action_api_status")).leaf = true
entry({"lm", "api", "config"}, call("action_api_config")).leaf = true
entry({"lm", "api", "fw"}, call("action_api_fw")).leaf = true
end
local function is_write()
return luci.http.getenv("REQUEST_METHOD") == "POST"
end
local function auth(write_access)
local http = require("luci.http")
local uci = require("uci"):cursor()
-- If API is disabled, both read and write is disabled
if uci:get("linkmeter", "api", "disabled") == "1" then
http.status(403, "Forbidden")
http.prepare_content("text/plain")
http.write("API disabled")
return nil
end
if uci:get("linkmeter", "api", "allowcors") == "1" then
http.header("Access-Control-Allow-Origin", "*")
end
-- Case 1: sysauth = api_read
if not write_access then
return true
end
-- Case 2: sysauth = api_write or { api_read, api_write } require a POST
if write_access and http.getenv("REQUEST_METHOD") ~= "POST" then
http.status(405, "Method Not Allowed")
http.header("Allow", "POST")
return nil
end
-- and check the supplied API key
local key = http.formvalue("apikey")
local apikey = uci:get("linkmeter", "api", "key")
if apikey and apikey ~= "" and key and key:lower() == apikey:lower() then
luci.dispatcher.context.authuser = "api_write"
return true
else
http.status(403, "Forbidden")
http.prepare_content("text/plain")
http.write("Invalid or missing apikey")
return nil
end
end
local function quick_json(t)
local http = require("luci.http")
http.prepare_content("application/json")
http.write('{')
local c = ""
for k,v in pairs(t) do
if type(v) == "string" then
if v == "null" then
http.write(c .. '"' .. k .. '":null')
else
http.write(c .. '"' .. k .. '":"' .. v .. '"')
end
else
http.write(c .. '"' .. k .. '":' .. v)
end
c = ","
end
http.write('}')
end
local function api_lmquery(query, tablefmt)
lmclient = require("lmclient")
local result, err = LmClient:query(query)
result = result or "{}"
-- Return the result in a parsed table instead of string
if tablefmt then
local jsonc = require("luci.jsonc")
local o = jsonc.parse(result)
return o, err
end
return result, err
end
function _M.action_api_version()
if not auth() then return end
local conf = api_lmquery("$LMCF", true)
quick_json({api = API_VERSION, ucid = conf.ucid or "null"})
end
function _M.action_api_status()
if not auth() then return end
local ctx = luci.dispatcher.context
local param = ctx.requestargs and #ctx.requestargs > 0
local status = api_lmquery("$LMSU", param)
local http = require("luci.http")
if param then
for _,k in ipairs(ctx.requestargs) do
-- if k is an integer, use it as an index
local kn = tonumber(k)
if kn and kn == math.floor(kn) then k = kn+1 end
status = status and status[k]
end
end
if type(status) == "table" then
http.prepare_content("application/json")
http.write(luci.jsonc.stringify(status))
elseif type(status) == "string" and status:sub(1,1) == "{" then
http.prepare_content("application/json")
http.write(status)
else
http.prepare_content("text/plain")
http.write(tostring(status or "null")) -- content must be a string
end
end
function _M.action_api_config()
if not auth(is_write()) then return end
-- See if just one parameter is specified, or this is a parent call
local param, value
local ctx = luci.dispatcher.context
if ctx.requestargs and #ctx.requestargs > 0 then
param = ctx.requestargs[1]
if #ctx.requestargs > 1 then
value = ctx.requestargs[2]
end
end
local http = require("luci.http")
if is_write() then
local lmadmin = require("luci.controller.linkmeter.lmadmin")
if param then
local vals = {}
vals[param] = http.formvalue(param) or http.formvalue("value")
return lmadmin.api_set(vals)
else
return lmadmin.api_set(http.formvalue())
end
else
local result = api_lmquery("$LMCF", param)
if param then
http.prepare_content("text/plain")
http.write(result[param] or "null")
else
http.prepare_content("application/json")
http.write(result)
end
end -- isRead
end
function _M.action_api_fw()
if not auth(true) then return end
if not luci.http.formvalue("hexfile") then
luci.http.status(400, "Bad Request")
luci.http.prepare_content("text/plain")
luci.http.write("Missing hexfile POST parameter")
return
end
local lmadmin = require("luci.controller.linkmeter.lmadmin")
lmadmin.api_file_handler("/tmp/hm.hex")
return lmadmin.api_post_fw("/tmp/hm.hex")
end
return _M
|
local myNumber = 99
myNumber = myNumber + 1
myNumber = math.pi
|
local NodeEntity = {}
NodeEntity.__index = NodeEntity
local json = require('json')
setmetatable(NodeEntity, {
__call = function (cls, ...)
local self = setmetatable({}, cls)
self:create(...)
return self
end,
})
function NodeEntity:className()
return "NodeEntity"
end
function NodeEntity:class()
return self
end
function NodeEntity:superClass()
return nil
end
function NodeEntity:isa(theClass)
local b_isa = false
local cur_class = theClass:class()
while ( nil ~= cur_class ) and ( false == b_isa ) do
if cur_class == theClass then
b_isa = true
else
cur_class = cur_class:superClass()
end
end
return b_isa
end
function NodeEntity:destroy()
NodeEntity.__gc(self)
end
function NodeEntity:create(init)
assert(init, "init variable is nil.")
assert(init.name, "Init variable is expecting a name value")
assert(init.states, "Init variable is expecting a states table")
assert(type(init.states) == "table", "Init variable is expecting a states table")
assert(init.physicsShape, "Init variable is expecting a physicsShape value")
assert(init.physicsBody, "Init variable is expecting a physicsBody value")
assert(init.sharedGeometry, "Init variable is expecting a sharedGeometry value")
self._init = init
self:load()
end
function NodeEntity:__gc()
self:unLoad()
end
function NodeEntity:__tostring()
return json:stringify(self)
end
function NodeEntity:_addEntityState(stateName, entityStateModule)
local init =
{
name = stateName,
entityOwner = self
}
self._stateEntityTable[stateName] = entityStateModule(init)
end
function NodeEntity:_removeEntityState(stateName)
self:_getEntityState():destroy()
self._stateEntityTable[stateName] = nil
end
function NodeEntity:_getEntityState(stateName)
assert(self._stateEntityTable[stateName], "There must be a state with name: " .. stateName)
return self._stateEntityTable[stateName]
end
function NodeEntity:_hasEntityState(stateName)
return (self._stateEntityTable[stateName] ~= nil)
end
function NodeEntity:hasState()
return self:getNode():getStateMachine():getState() ~= nil
end
function NodeEntity:getCurrentEntityState()
assert(self:getNode():getStateMachine(), "message")
assert(self:getNode():getStateMachine():getState(), "message")
assert(self:getNode():getStateMachine():getState():getName(), "message")
return self:_getEntityState(self:getNode():getStateMachine():getState():getName())
end
function NodeEntity:pushState(stateName)
self:_getEntityState(stateName):push()
end
function NodeEntity:getNode()
return self._node
end
function NodeEntity:getPhysicsShape()
return self._physicsShape
end
function NodeEntity:getPhysicsBody()
return self._physicsBody
end
function NodeEntity:getAction()
return self._action
end
function NodeEntity:getClock()
return self._clock
end
function NodeEntity:isLoaded()
if self.loaded then
return self.loaded
end
return false
end
function NodeEntity:load()
print("SceneEntity:load()")
for k,v in pairs(self._stateEntityTable) do
v:load()
end
self.loaded = true
-- self._stateEntityTable = {}
-- for k,v in pairs(self._init.states) do
-- local m = require v.module
-- self:_addEntityState(v.name, m)
-- end
-- self._node = njli.Node.create()
-- self:getNode():setName(self._init.name)
-- self._physicsShape = self._init.physicsShape
-- self._physicsBody = self._init.physicsBody
-- self._action = njli.Action.create()
-- self._clock = njli.Clock.create()
-- self._sharedGeometry = self._init.sharedGeometry
-- self.loaded = true
end
function NodeEntity:unLoad()
if self._stateEntityTable then
for k,v in pairs(self._stateEntityTable) do
self:_getEntityState(v.name):unLoad()
self:_removeEntityState(k)
end
self._stateEntityTable = nil
end
self.loaded = false
print("SceneEntity:unLoad()")
if self:getClock() then
njli.Clock.destroy(self:getClock())
self._clock = nil
end
if self:getAction() then
njli.Action.destroy(self:getAction())
self._action = nil
end
if self:getPhysicsBody() then
njli.PhysicsBody.destroy(self:getPhysicsBody())
self._physicsBody = nil
end
if self:getPhysicsShape() then
njli.PhysicsShape.destroy(self:getPhysicsShape())
self._physicsShape = nil
end
if self:getNode() then
njli.Node.destroy(self:getNode())
self._node = nil
end
if self._stateEntityTable then
for k,v in pairs(self._stateEntityTable) do
self:_removeEntityState(k)
end
self._stateEntityTable = nil
end
self.loaded = false
end
function NodeEntity:startStateMachine()
end
function NodeEntity:enter()
assert(self:hasState(), "NodeEntity must be in a state")
self:getCurrentEntityState():enter()
end
function NodeEntity:update(timeStep)
assert(self:hasState(), "NodeEntity must be in a state")
self:getCurrentEntityState():update(timeStep)
end
function NodeEntity:exit()
assert(self:hasState(), "NodeEntity must be in a state")
self:getCurrentEntityState():exit()
end
function NodeEntity:onMessage(message)
assert(self:hasState(), "NodeEntity must be in a state")
self:getCurrentEntityState():onMessage(message)
end
function NodeEntity:touchDown(touches)
assert(self:hasState(), "NodeEntity must be in a state")
self:getCurrentEntityState():touchDown(touches)
end
function NodeEntity:touchUp(touches)
assert(self:hasState(), "NodeEntity must be in a state")
self:getCurrentEntityState():touchUp(touches)
end
function NodeEntity:touchMove(touches)
assert(self:hasState(), "NodeEntity must be in a state")
self:getCurrentEntityState():touchMove(touches)
end
function NodeEntity:touchCancelled(touches)
assert(self:hasState(), "NodeEntity must be in a state")
self:getCurrentEntityState():touchCancelled(touches)
end
function NodeEntity:render()
assert(self:hasState(), "NodeEntity must be in a state")
self:getCurrentEntityState():render()
end
function NodeEntity:actionUpdate(action, timeStep)
assert(self:hasState(), "NodeEntity must be in a state")
self:getCurrentEntityState():actionUpdate(action, timeStep)
end
function NodeEntity:actionComplete(action)
assert(self:hasState(), "NodeEntity must be in a state")
self:getCurrentEntityState():actionComplete(action)
end
function NodeEntity:collide(otherNode, collisionPoint)
assert(self:hasState(), "NodeEntity must be in a state")
self:getCurrentEntityState():collide(otherNode, collisionPoint)
end
function NodeEntity:near(otherNode)
assert(self:hasState(), "NodeEntity must be in a state")
self:getCurrentEntityState():near(otherNode)
end
function NodeEntity:rayTouchDown(rayContact)
assert(self:hasState(), "NodeEntity must be in a state")
self:getCurrentEntityState():rayTouchDown(rayContact)
end
function NodeEntity:rayTouchUp(rayContact)
assert(self:hasState(), "NodeEntity must be in a state")
self:getCurrentEntityState():rayTouchUp(rayContact)
end
function NodeEntity:rayTouchMove(rayContact)
assert(self:hasState(), "NodeEntity must be in a state")
self:getCurrentEntityState():rayTouchMove(rayContact)
end
function NodeEntity:rayTouchCancelled(rayContact)
assert(self:hasState(), "NodeEntity must be in a state")
self:getCurrentEntityState():rayTouchCancelled(rayContact)
end
function NodeEntity:pause()
assert(self:hasState(), "NodeEntity must be in a state")
self:getCurrentEntityState():pause()
end
function NodeEntity:unPause()
assert(self:hasState(), "NodeEntity must be in a state")
self:getCurrentEntityState():unPause()
end
return NodeEntity
|
-------------------------------------
-- lxi-tools --
-- https://lxi-tools.github.io --
-------------------------------------
-- Number chart test
-- Init
clock0 = clock_new()
chart0 = chart_new("number", -- chart type
"PSU Voltage", -- title
"[ V ]", -- label
800) -- window width
-- Manipulate number for 10 seconds
clock = 0
while (clock < 10)
do
clock = clock_read(clock0)
chart_set_value(chart0, clock)
msleep(100)
end
-- Cleanup
clock_free(clock0)
--chart_close(chart0)
print("Done")
|
local PLUGIN = PLUGIN
DEFINE_BASECLASS("DPanel")
local PANEL = {}
function PANEL:Init()
if (IsValid(PLUGIN.panel)) then
return
end
local character = LocalPlayer():GetCharacter()
self:SetTitle(L("mynotes", character:GetName()))
self:SetBackgroundBlur(true)
self:SetDeleteOnClose(true)
self:SetSize(400, 400)
self.textEntry = self:Add("DTextEntry")
self.textEntry:SetMultiline(true)
self.textEntry:Dock(FILL)
self.textEntry.SetRealValue = function(this, text)
this:SetValue(text)
this:SetCaretPos(text:len())
end
self.textEntry.Think = function(this)
local text = this:GetValue()
if (text:len() > PLUGIN.maxLength) then
this:SetRealValue(text:sub(1, PLUGIN.maxLength))
surface.PlaySound("common/talk.wav")
end
end
self.button = self:Add("DButton")
self.button:SetText(L("save"))
self.button:Dock(BOTTOM)
self.button.DoClick = function(this)
net.Start("ixEditMyNotes")
net.WriteString(self.textEntry:GetValue():sub(1, PLUGIN.maxLength))
net.SendToServer()
end
self:MakePopup()
self:Center()
PLUGIN.panel = self
end
function PANEL:Populate(text)
self.textEntry:SetText(text)
end
vgui.Register("ixMyNotes", PANEL, "DFrame")
|
local ffi = require('ffi')
local class = require('class')
local Buffer = class('Buffer')
local C = ffi.os == 'Windows' and ffi.load('msvcrt') or ffi.C
local concat = table.concat
local lshift, rshift = bit.lshift, bit.rshift
local tohex = bit.tohex
local gc, cast, copy, fill = ffi.gc, ffi.cast, ffi.copy, ffi.fill
local ffi_string = ffi.string
local min = math.min
ffi.cdef [[
void* malloc(size_t size);
void* calloc(size_t num, size_t size);
void free(void *ptr);
]]
function Buffer:__init(str)
if type(str) == 'string' then
self._len = #str
self._cdata = gc(cast('unsigned char*', C.calloc(self._len, 1)), C.free)
copy(self._cdata, str, self._len)
else
self._len = tonumber(str) or 0
self._cdata = gc(cast('unsigned char*', C.calloc(self._len, 1)), C.free)
end
end
function Buffer:__len()
return self._len
end
function Buffer:__tostring()
return ffi_string(self._cdata, self._len)
end
local function get(self, k)
if k < 0 or k > self._len then
return error('buffer index out of bounds')
end
return self._cdata[k]
end
local function set(self, k, v)
if k < 0 or k > self._len then
return error('buffer index out of bounds')
end
self._cdata[k] = v
end
local function complement8(value)
return value < 0x80 and value or value - 0x100
end
local function complement16(value)
return value < 0x8000 and value or value - 0x10000
end
function Buffer:readUInt8(k)
return get(self, k)
end
function Buffer:readUInt16BE(k)
return lshift(get(self, k), 8) + get(self, k + 1)
end
function Buffer:readUInt16LE(k)
return get(self, k) + lshift(get(self, k + 1), 8)
end
function Buffer:readUInt32BE(k)
return get(self, k) * 0x1000000 + lshift(get(self, k + 1), 16) + lshift(get(self, k + 2), 8) + get(self, k + 3)
end
function Buffer:readUInt32LE(k)
return get(self, k) + lshift(get(self, k + 1), 8) + lshift(get(self, k + 2), 16) + get(self, k + 3) * 0x1000000
end
function Buffer:readInt8(k)
return complement8(self:readUInt8(k))
end
function Buffer:readInt16BE(k)
return complement16(self:readUInt16BE(k))
end
function Buffer:readInt16LE(k)
return complement16(self:readUInt16LE(k))
end
function Buffer:readInt32BE(k)
return lshift(get(self, k), 24) + lshift(get(self, k + 1), 16) + lshift(get(self, k + 2), 8) + get(self, k + 3)
end
function Buffer:readInt32LE(k)
return get(self, k) + lshift(get(self, k + 1), 8) + lshift(get(self, k + 2), 16) + lshift(get(self, k + 3), 24)
end
function Buffer:writeUInt8(k, v)
set(self, k, rshift(v, 0))
end
function Buffer:writeUInt16BE(k, v)
set(self, k, rshift(v, 8))
set(self, k + 1, rshift(v, 0))
end
function Buffer:writeUInt16LE(k, v)
set(self, k, rshift(v, 0))
set(self, k + 1, rshift(v, 8))
end
function Buffer:writeUInt32BE(k, v)
set(self, k, rshift(v, 24))
set(self, k + 1, rshift(v, 16))
set(self, k + 2, rshift(v, 8))
set(self, k + 3, rshift(v, 0))
end
function Buffer:writeUInt32LE(k, v)
set(self, k, rshift(v, 0))
set(self, k + 1, rshift(v, 8))
set(self, k + 2, rshift(v, 16))
set(self, k + 3, rshift(v, 24))
end
Buffer.writeInt8 = Buffer.writeUInt8
Buffer.writeInt16BE = Buffer.writeUInt16BE
Buffer.writeInt16LE = Buffer.writeUInt16LE
Buffer.writeInt32BE = Buffer.writeUInt32BE
Buffer.writeInt32LE = Buffer.writeUInt32LE
function Buffer:read(offset, len)
offset = offset or 0
len = len or self._len
return ffi_string(self._cdata + offset, min(len, self._len - offset))
end
function Buffer:write(str, offset, len)
offset = offset or 0
len = len or #str
return copy(self._cdata + offset, str, min(len, self._len - offset))
end
function Buffer:fill(v)
return fill(self._cdata, self._len, v)
end
function Buffer:toHex(i, j)
local str = {}
i = i or 0
j = j or self._len
for n = i, j - 1 do
str[n + 1] = tohex(get(self, n), 2)
end
return concat(str, ' ')
end
function Buffer:toArray(i, j)
local tbl = {}
i = i or 0
j = j or self._len
for n = i, j - 1 do
tbl[n + 1] = get(self, n)
end
return tbl
end
return Buffer
|
---
-- @module PlayerInfo
--
-- ------------------------------------------------
-- Required Modules
-- ------------------------------------------------
local ScreenManager = require( 'lib.screenmanager.ScreenManager' )
local Screen = require( 'src.ui.screens.Screen' )
local Translator = require( 'src.util.Translator' )
local UIOutlines = require( 'src.ui.elements.UIOutlines' )
local UIBackground = require( 'src.ui.elements.UIBackground' )
local TexturePacks = require( 'src.ui.texturepacks.TexturePacks' )
local GridHelper = require( 'src.util.GridHelper' )
-- ------------------------------------------------
-- Module
-- ------------------------------------------------
local PlayerInfo = Screen:subclass( 'PlayerInfo' )
-- ------------------------------------------------
-- Constants
-- ------------------------------------------------
local UI_GRID_WIDTH = 30
local UI_GRID_HEIGHT = 16
local NAME_POSITION = 0
local CLASS_POSITION = 16
local TYPE_POSITION = 32
local AP_POSITION = { X = 0, Y = 2 }
local HP_POSITION = { X = 16, Y = 2 }
local STATUS_POSITION = { X = 0, Y = 4 }
-- ------------------------------------------------
-- Private Methods
-- ------------------------------------------------
---
-- Generates the outlines for this screen.
-- @tparam number x The origin of the screen along the x-axis.
-- @tparam number y The origin of the screen along the y-axis.
-- @treturn UIOutlines The newly created UIOutlines instance.
--
local function generateOutlines( x, y )
local outlines = UIOutlines( x, y, 0, 0, UI_GRID_WIDTH, UI_GRID_HEIGHT )
-- Horizontal borders.
for ox = 0, UI_GRID_WIDTH-1 do
outlines:add( ox, 0 ) -- Top
outlines:add( ox, 2 ) -- Header
outlines:add( ox, UI_GRID_HEIGHT-1 ) -- Bottom
end
-- Vertical outlines.
for oy = 0, UI_GRID_HEIGHT-1 do
outlines:add( 0, oy ) -- Left
outlines:add( UI_GRID_WIDTH-1, oy ) -- Right
end
outlines:refresh()
return outlines
end
---
-- Adds colored text to the text object and returns the width of the added item.
-- @tparam Text textObject The Text object to modify.
-- @tparam table colorTable The table to use for adding colored text.
-- @tparam number y The position at which to add the text along the x-axis.
-- @tparam number x The position at which to add the text along the y-axis.
-- @tparam table color A table containing RGBA values.
-- @tparam string text The text string to add.
-- @treturn number The width of the added text item.
--
local function addToTextObject( textObject, colorTable, x, y, color, text )
colorTable[1], colorTable[2] = color, text
textObject:add( colorTable, x, y )
return textObject:getDimensions()
end
---
-- @tparam Text textObject The Text object to modify.
-- @tparam table colorTable The table to use for adding colored text.
-- @tparam number gw The glyph width to use for modifying the text offset.
-- @tparam number gh The glyph height to use for modifying the text offset.
-- @tparam Character character The currently active character.
--
local function drawCharacterInfo( textObject, colorTable, gw, _, character )
local x, y = NAME_POSITION * gw, 0
x = x + addToTextObject( textObject, colorTable, x, y, TexturePacks.getColor( 'ui_text_dark' ), Translator.getText( 'ui_healthscreen_name' ))
addToTextObject( textObject, colorTable, x, y, TexturePacks.getColor( 'ui_character_name' ), character:getName() )
x, y = CLASS_POSITION * gw, 0
x = x + addToTextObject( textObject, colorTable, x, y, TexturePacks.getColor( 'ui_text_dark' ), Translator.getText( 'ui_class' ))
addToTextObject( textObject, colorTable, x, y, TexturePacks.getColor( 'ui_character_name' ), Translator.getText( character:getCreatureClass() ))
x, y = TYPE_POSITION * gw, 0
x = x + addToTextObject( textObject, colorTable, x, y, TexturePacks.getColor( 'ui_text_dark' ), Translator.getText( 'ui_healthscreen_type' ))
addToTextObject( textObject, colorTable, x, y, TexturePacks.getColor( 'ui_character_name' ), Translator.getText( character:getBody():getID() ))
end
---
-- Adjusts colors based on how close a value is compared to its total.
-- @tparam number value The value to compare.
-- @tparam number total The maxium value.
-- @treturn table A table containing RGBA values.
--
local function adjustColors( value, total )
local fraction = value / total
if fraction < 0 then
return TexturePacks.getColor( 'ui_path_ap_low' )
elseif fraction <= 0.2 then
return TexturePacks.getColor( 'ui_path_ap_med' )
elseif fraction <= 0.6 then
return TexturePacks.getColor( 'ui_path_ap_high' )
elseif fraction <= 1.0 then
return TexturePacks.getColor( 'ui_path_ap_full' )
end
end
---
-- @tparam Text textObject The Text object to modify.
-- @tparam table colorTable The table to use for adding colored text.
-- @tparam number gw The glyph width to use for modifying the text offset.
-- @tparam number gh The glyph height to use for modifying the text offset.
-- @tparam Character character The currently active character.
--
local function drawActionPoints( textObject, colorTable, gw, gh, character )
local currentActionPoints = character:getCurrentAP()
local maximumActionPoints = character:getMaximumAP()
local x, y = AP_POSITION.X * gw, AP_POSITION.Y * gh
-- AP:
x = x + addToTextObject( textObject, colorTable, x, y, TexturePacks.getColor( 'ui_text_dark' ), Translator.getText( 'ui_ap' ))
-- AP: xx
x = x + addToTextObject( textObject, colorTable, x, y, adjustColors( currentActionPoints, maximumActionPoints ), currentActionPoints )
-- AP: xx/
x = x + addToTextObject( textObject, colorTable, x, y, TexturePacks.getColor( 'ui_text' ), '/' )
-- AP: xx/yy
addToTextObject( textObject, colorTable, x, y, TexturePacks.getColor( 'ui_text' ), maximumActionPoints )
end
---
-- @tparam Text textObject The Text object to modify.
-- @tparam table colorTable The table to use for adding colored text.
-- @tparam number gw The glyph width to use for modifying the text offset.
-- @tparam number gh The glyph height to use for modifying the text offset.
-- @tparam Character character The currently active character.
--
local function drawHealthPoints( textObject, colorTable, gw, gh, character )
local currentHealthPoints = character:getCurrentHP()
local maximumHealthPoints = character:getMaximumHP()
local x, y = HP_POSITION.X * gw, HP_POSITION.Y * gh
-- HP:
x = x + addToTextObject( textObject, colorTable, x, y, TexturePacks.getColor( 'ui_text_dark' ), Translator.getText( 'ui_hp' ))
-- HP: xx
x = x + addToTextObject( textObject, colorTable, x, y, adjustColors( currentHealthPoints, maximumHealthPoints ), currentHealthPoints )
-- HP: xx/
x = x + addToTextObject( textObject, colorTable, x, y, TexturePacks.getColor( 'ui_text' ), '/' )
-- HP: xx/yy
addToTextObject( textObject, colorTable, x, y, TexturePacks.getColor( 'ui_text' ), maximumHealthPoints )
end
---
-- @tparam Text textObject The Text object to modify.
-- @tparam table colorTable The table to use for adding colored text.
-- @tparam number gw The glyph width to use for modifying the text offset.
-- @tparam number gh The glyph height to use for modifying the text offset.
-- @tparam Character character The currently active character.
--
local function drawStatusEffects( textObject, colorTable, gw, gh, character )
local str = ''
for status, _ in pairs( character:getBody():getStatusEffects():getActiveEffects() ) do
str = str .. Translator.getText( status ) .. ', '
end
-- Remove last comma.
str = str:sub( 1, -3 )
local x, y = STATUS_POSITION.X * gw, STATUS_POSITION.Y * gh
x = x + addToTextObject( textObject, colorTable, x, y, TexturePacks.getColor( 'ui_text_dark' ), Translator.getText( 'ui_healthscreen_status' ))
addToTextObject( textObject, colorTable, x, y, TexturePacks.getColor( 'ui_text' ), str )
end
-- ------------------------------------------------
-- Public Methods
-- ------------------------------------------------
function PlayerInfo:initialize( character )
self.x, self.y = GridHelper.centerElement( UI_GRID_WIDTH, UI_GRID_HEIGHT )
self.background = UIBackground( self.x, self.y, 0, 0, UI_GRID_WIDTH, UI_GRID_HEIGHT )
self.outlines = generateOutlines( self.x, self.y )
self.textObject = love.graphics.newText( TexturePacks.getFont():get() )
self.colorTable = {}
self.character = character
end
function PlayerInfo:draw()
self.background:draw()
self.outlines:draw()
local tw, th = TexturePacks.getTileDimensions()
love.graphics.draw( self.textObject, (self.x+1) * tw, (self.y+1) * th )
TexturePacks.resetColor()
end
function PlayerInfo:update()
self.textObject:clear()
local gw, gh = TexturePacks.getGlyphDimensions()
drawCharacterInfo( self.textObject, self.colorTable, gw, gh, self.character )
drawActionPoints( self.textObject, self.colorTable, gw, gh, self.character )
drawHealthPoints( self.textObject, self.colorTable, gw, gh, self.character )
drawStatusEffects( self.textObject, self.colorTable, gw, gh, self.character )
end
function PlayerInfo:keypressed( key )
if key == 'escape' or key == 'h' then
ScreenManager.pop()
end
end
return PlayerInfo
|
-----------------------------------------
-- ID: 5306
-- Item: Bottle of Hallowed Water
-- Item Effect: Removes curse. Better chance to remove doom.
-----------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/msg")
function onItemCheck(target)
return 0
end
function onItemUse(target)
local curse = target:getStatusEffect(tpz.effect.CURSE_I)
local curse2 = target:getStatusEffect(tpz.effect.CURSE_II)
local bane = target:getStatusEffect(tpz.effect.BANE)
local power = 33 + target:getMod(tpz.mod.ENHANCES_HOLYWATER)
if (target:hasStatusEffect(tpz.effect.DOOM) and power > math.random(1, 100)) then
target:delStatusEffect(tpz.effect.DOOM)
target:messageBasic(tpz.msg.basic.NARROWLY_ESCAPE)
elseif (curse ~= nil and curse2 ~= nil and bane ~= nil) then
target:delStatusEffect(tpz.effect.CURSE_I)
target:delStatusEffect(tpz.effect.CURSE_II)
target:delStatusEffect(tpz.effect.BANE)
elseif (curse ~= nil and bane ~= nil) then
target:delStatusEffect(tpz.effect.CURSE_I)
target:delStatusEffect(tpz.effect.BANE)
elseif (curse2 ~= nil and bane ~= nil) then
target:delStatusEffect(tpz.effect.CURSE_II)
target:delStatusEffect(tpz.effect.BANE)
elseif (curse ~= nil) then
target:delStatusEffect(tpz.effect.CURSE_I)
elseif (curse2 ~= nil) then
target:delStatusEffect(tpz.effect.CURSE_II)
elseif (bane ~= nil) then
target:delStatusEffect(tpz.effect.BANE)
else
target:messageBasic(tpz.msg.basic.NO_EFFECT)
end
end
|
local id = ID("showhalionreference.showhalionreferencemenu")
local ident = "([a-zA-Z_][a-zA-Z_0-9%.]*)"
local func = {['addLayerPassword'] = "addLayerPassword", ['addQCAssignment'] = "addQCAssignment", ['afterTouch'] = "afterTouch", ['analyzePitch'] = "analyzePitch", ['appendBus'] = "appendBus", ['appendEffect'] = "appendEffect", ['appendLayer'] = "appendLayer", ['appendLayerAsync'] = "appendLayerAsync", ['appendMidiModule'] = "appendMidiModule", ['appendZone'] = "appendZone", ['assignAutomation'] = "assignAutomation", ['AudioFile.open'] = "AudioFile.open", ['beat2ms'] = "beat2ms", ['Bus'] = "Bus+Constructor", ['calcModulation'] = "calcModulation", ['cancelPitchAnalysis'] = "cancelPitchAnalysis", ['changeNoteExpression'] = "changeNoteExpression", ['changePan'] = "changePan", ['changeTune'] = "changeTune", ['changeVolume'] = "changeVolume", ['changeVolumedB'] = "changeVolumedB", ['clone'] = "clone", ['controlChange'] = "controlChange", ['defineModulation'] = "defineModulation", ['defineParameter'] = "defineParameter", ['defineSlotLocal'] = "defineSlotLocal", ['Effect'] = "Effect+Constructor", ['endUndoBlock'] = "endUndoBlock", ['Event'] = "Event+Constructor", ['fade'] = "fade", ['findBusses'] = "findBusses", ['findChildren'] = "findChildren", ['findEffects'] = "findEffects", ['findLayers'] = "findLayers", ['findMidiModules'] = "findMidiModules", ['findSlots'] = "findSlots", ['findZones'] = "findZones", ['forgetAutomation'] = "forgetAutomation", ['getAllocatedMemory'] = "getAllocatedMemory", ['getAutomationIndex'] = "getAutomationIndex", ['getBarDuration'] = "getBarDuration", ['getBeatDuration'] = "getBeatDuration", ['getBeatTime'] = "getBeatTime", ['getBeatTimeInBar'] = "getBeatTimeInBar", ['getBus'] = "getBus", ['getCC'] = "getCC", ['getChild'] = "getChild", ['getContext'] = "getContext", ['getDisplayString'] = "getDisplayString", ['getEffect'] = "getEffect", ['getElement'] = "getElement", ['getFreeVoices'] = "getFreeVoices", ['getHostName'] = "getHostName", ['getHostVersion'] = "getHostVersion", ['getKeyProperties'] = "getKeyProperties", ['getKeySwitches'] = "getKeySwitches", ['getLayer'] = "getLayer", ['getMidiModule'] = "getMidiModule", ['getModulationMatrixRow'] = "getModulationMatrixRow", ['getMsTime'] = "getMsTime", ['getNoteDuration'] = "getNoteDuration", ['getNoteExpression'] = "getNoteExpression", ['getNoteExpressionProperties'] = "getNoteExpressionProperties", ['getNumQCAssignments'] = "getNumQCAssignments", ['getOnsets'] = "getOnsets", ['getOutputBus'] = "getOutputBus", ['getParameter'] = "getParameter", ['getParameterDefinition'] = "getParameterDefinition", ['getParameterNormalized'] = "getParameterNormalized", ['getPeak'] = "getPeak", ['getPitch'] = "getPitch", ['getPitchAnalysisProgress'] = "getPitchAnalysisProgress", ['getProductName'] = "getProductName", ['getProductVersion'] = "getProductVersion", ['getProgram'] = "getProgram", ['getQCAssignmentBypass'] = "getQCAssignmentBypass", ['getQCAssignmentCurve'] = "getQCAssignmentCurve", ['getQCAssignmentMax'] = "getQCAssignmentMax", ['getQCAssignmentMin'] = "getQCAssignmentMin", ['getQCAssignmentMode'] = "getQCAssignmentMode", ['getQCAssignmentParamId'] = "getQCAssignmentParamId", ['getQCAssignmentScope'] = "getQCAssignmentScope", ['getSamplingRate'] = "getSamplingRate", ['getScriptExecTimeOut'] = "getScriptExecTimeOut", ['getScriptVersion'] = "getScriptVersion", ['getSlot'] = "getSlot", ['getSlotIndex'] = "getSlotIndex", ['getSource1'] = "getSource1", ['getSource2'] = "getSource2", ['getTempo'] = "getTempo", ['getTime'] = "getTime", ['getTimeSignature'] = "getTimeSignature", ['getUndoContext'] = "getUndoContext", ['getUsedMemory'] = "getUsedMemory", ['getUsedVoices'] = "getUsedVoices", ['getUsedVoicesOfSlot'] = "getUsedVoicesOfSlot", ['getUserPresetPath'] = "getUserPresetPath", ['getVoices'] = "getVoices", ['getZone'] = "getZone", ['hasParameter'] = "hasParameter", ['insertBus'] = "insertBus", ['insertEffect'] = "insertEffect", ['insertEnvelopePoint'] = "insertEnvelopePoint", ['insertEvent'] = "insertEvent", ['insertLayer'] = "insertLayer", ['insertLayerAsync'] = "insertLayerAsync", ['insertMidiModule'] = "insertMidiModule", ['insertZone'] = "insertZone", ['isKeyDown'] = "isKeyDown", ['isNoteHeld'] = "isNoteHeld", ['isOctaveKeyDown'] = "isOctaveKeyDown", ['isPlaying'] = "isPlaying", ['Layer'] = "Layer+Constructor", ['loadPreset'] = "loadPreset", ['loadPresetAsync'] = "loadPresetAsync", ['messageBox'] = "messageBox", ['MidiModule'] = "MidiModule+Constructor", ['ms2beat'] = "ms2beat", ['ms2samples'] = "ms2samples", ['onAfterTouch'] = "onAfterTouch", ['onController'] = "onController", ['onIdle'] = "onIdle", ['onInit'] = "onInit", ['onLoad'] = "onLoad", ['onLoadIntoSlot'] = "onLoadIntoSlot", ['onLoadSubPreset'] = "onLoadSubPreset", ['onNote'] = "onNote", ['onNoteExpression'] = "onNoteExpression", ['onPitchBend'] = "onPitchBend", ['onRelease'] = "onRelease", ['onRemoveFromSlot'] = "onRemoveFromSlot", ['onSave'] = "onSave", ['onSaveSubPreset'] = "onSaveSubPreset", ['onTriggerPad'] = "onTriggerPad", ['onUnhandledEvent'] = "onUnhandledEvent", ['openURL'] = "openURL", ['pitchBend'] = "pitchBend", ['playNote'] = "playNote", ['playTriggerPad'] = "playTriggerPad", ['postEvent'] = "postEvent", ['printRaw'] = "printRaw", ['Program'] = "Program+Constructor", ['readMidiFile'] = "readMidiFile", ['releaseVoice'] = "releaseVoice", ['removeBus'] = "removeBus", ['removeEffect'] = "removeEffect", ['removeEnvelopePoint'] = "removeEnvelopePoint", ['removeFromParent'] = "removeFromParent", ['removeLayer'] = "removeLayer", ['removeMidiModule'] = "removeMidiModule", ['removeQCAssignment'] = "removeQCAssignment", ['removeZone'] = "removeZone", ['runAsync'] = "runAsync", ['runSync'] = "runSync", ['samples2ms'] = "samples2ms", ['setName'] = "setName", ['setOutputBus'] = "setOutputBus", ['setParameter'] = "setParameter", ['setParameterNormalized'] = "setParameterNormalized", ['setProgram'] = "setProgram", ['setQCAssignmentBypass'] = "setQCAssignmentBypass", ['setQCAssignmentCurve'] = "setQCAssignmentCurve", ['setQCAssignmentMax'] = "setQCAssignmentMax", ['setQCAssignmentMin'] = "setQCAssignmentMin", ['setQCAssignmentMode'] = "setQCAssignmentMode", ['setQCAssignmentParamId'] = "setQCAssignmentParamId", ['setQCAssignmentScope'] = "setQCAssignmentScope", ['setScriptExecTimeOut'] = "setScriptExecTimeOut", ['setSource1'] = "setSource1", ['setSource2'] = "setSource2", ['sortEvents'] = "sortEvents", ['spawn'] = "spawn", ['startUndoBlock'] = "startUndoBlock", ['wait'] = "wait", ['waitBeat'] = "waitBeat", ['waitForRelease'] = "waitForRelease", ['writeMidiFile']= "writeMidiFile", ['Zone'] = "Zone+Constructor"}
return {
name = "Show halion reference",
description = "Adds 'show halion reference' option to the editor menu.",
author = "..",
version = 0.2,
dependencies = "1.30",
onMenuEditor = function(self, menu, editor, event)
local point = editor:ScreenToClient(event:GetPosition())
local pos = editor:PositionFromPointClose(point.x, point.y)
if not pos then return end
local line = editor:LineFromPosition(pos)
local linetx = editor:GetLine(line)
local localpos = pos-editor:PositionFromLine(line)
local selected = editor:GetSelectionStart() ~= editor:GetSelectionEnd()
and pos >= editor:GetSelectionStart() and pos <= editor:GetSelectionEnd()
local start = linetx:sub(1,localpos):find(ident.."$")
local right = linetx:sub(localpos+1,#linetx):match("^([a-zA-Z_0-9%.%:]*)%s*['\"{%(]?")
local ref = selected
and editor:GetTextRange(editor:GetSelectionStart(), editor:GetSelectionEnd())
or (start and linetx:sub(start,localpos)..right or nil)
if ref and func[ref] then
menu:Append(id, ("Show Reference: %s"):format(ref))
menu:Connect(id, wx.wxEVT_COMMAND_MENU_SELECTED,
function() wx.wxLaunchDefaultBrowser('https://developer.steinberg.help/display/HSD/'..func[ref], 0) end)
end
end
}
|
--[[
A simple class that allows roblox developers to easily send messages to discord
@author tomspell
@author https://www.roblox.com/users/9345226/profile
@version 1.0
@version Last Updated: 6/20/2020
]]
local HttpService = game:GetService("HttpService")
local MessageEmbed = {}
MessageEmbed.__index = MessageEmbed
MessageEmbed.package = {
embeds = {}
}
--[[
Creates a message embed object
@param webhook The webhook of the channel you want the message to be sent to
@return message embed object
]]
function MessageEmbed.new(webhook)
assert(typeof(webhook) == "string", "webhook must be a string")
local object = {}
object.__index = object
object.webhook = webhook
object.embed = { fields = {} }
setmetatable(object, MessageEmbed)
return object
end
--[[
Adds a field to the embed (max 25).
@param name [String] The name of the field
@param value [String] The description of the field
@param inline? [Boolean] A boolean of if the field should be inline with the other fields, defaults to false
]]
function MessageEmbed:AddField(name, value, inline)
assert(typeof(name) == "string", "name must be a string")
assert(typeof(value) == "string", "value must be a string")
if inline == nil then
inline = false
else
assert(typeof(inline) == "boolean", "inline must be a boolean")
end
table.insert(self.embed.fields, {
name = name,
value = value,
inline = inline
})
end
--[[
Adds multiple fields at a time (max 25)
@param fields [Table] takes in a table of fields, example:
local fieldsToAdd = {
{"testing", "other testing"},
{"more testing", "even more testing"}
}
]]
function MessageEmbed:AddFields(fields)
assert(typeof(fields) == "table", "fields must be a table")
for _, field in pairs(fields) do
assert(typeof(field) == "table", "the individual fields within the fields table must be tables")
self:AddField(field[1], field[2], field[3])
end
end
--[[
Sets the title of the embed
@param title [String] the title of the embed
]]
function MessageEmbed:SetTitle(title)
assert(typeof(title) == "string", "title must be a string")
self.embed.title = title
end
--[[
Sets the description of the embed
@param description [String] the description of the embed
]]
function MessageEmbed:SetDescription(description)
assert(typeof(description) == "string", "description must be a string")
self.embed.description = description
end
--[[
Sets the url of the embed
@param url [String] the url of the embed
]]
function MessageEmbed:SetUrl(url)
assert(typeof(url) == "string", "url must be a string")
self.embed.url = url
end
--[[
Sets the color of the embed
@param color [Number] the color of the embed (must be a decimal code, you can find them here: https://convertingcolors.com/)
]]
function MessageEmbed:SetColor(color)
assert(typeof(color) == "number", "color must be a number")
self.embed.color = color
end
--[[
Sets the footer of the embed
@param text [String] the text of the footer
@param icon_url? [String] the url of the icon of the footer
]]
function MessageEmbed:SetFooter(text, icon_url)
assert(typeof(text) == "string", "text must be a string")
if icon_url ~= nil then
assert(typeof(icon_url) == "string", "icon_url must be a string")
end
self.embed.footer = {
text = text,
icon_url = icon_url
}
end
--[[
Sets the image of the embed
@param url [String] the url of the image
@param proxy_icon_url? [String] The optional proxy_icon_url of the image
@param height? [Number] the height of the image
@param width? [Number] the width of the image
]]
function MessageEmbed:SetImage(url, proxy_icon_url, height, width)
assert(typeof(url) == "string", "url must be a string")
if proxy_icon_url ~= nil then
assert(typeof(proxy_icon_url) == "string", "proxy_icon_url must be a string")
end
if height ~= nil then
assert(typeof(height) == "number", "height must be a number")
end
if width ~= nil then
assert(typeof(width) == "number", "width must be a number")
end
self.embed.image = {
url = url,
proxy_icon_url = proxy_icon_url,
height = height,
width = width
}
end
--[[
Sets the thumbnail of the embed
@param url [String] the url of the thumbnail
@param proxy_icon_url? [String] The optional proxy_icon_url of the thumbnail
@param height? [Number] the height of the thumbnail
@param width? [Number] the width of the thumbnail
]]
function MessageEmbed:SetThumbnail(url, proxy_icon_url, height, width)
assert(typeof(url) == "string", "url must be a string")
if proxy_icon_url ~= nil then
assert(typeof(proxy_icon_url) == "string", "proxy_icon_url must be a string")
end
if height ~= nil then
assert(typeof(height) == "number", "height must be a number")
end
if width ~= nil then
assert(typeof(width) == "number", "width must be a number")
end
self.embed.thumbnail = {
url = url,
proxy_icon_url = proxy_icon_url,
height = height,
width = width
}
end
--[[
Sends the message asynchronously
]]
function MessageEmbed:PostAsync()
table.insert(self.package.embeds, self.embed)
coroutine.wrap(function()
HttpService:PostAsync(self.webhook, HttpService:JSONEncode(self.package))
end)()
end
return MessageEmbed
|
require "IrrLua"
require "CAnimSprite"
function main()
local irrDevice = irr.createDevice(irr.video.EDT_OPENGL,irr.core.dimension2d(640,480),32,false,false,false,nil)
local irrVideo = irrDevice:getVideoDriver()
local irrSceneMgr = irrDevice:getSceneManager()
local mf = "../media/images/"
local files = {mf .. "red.bmp", mf .. "blue.bmp", mf .. "orange.bmp", mf .. "yellow.bmp", mf .. "star.bmp"}
local Sprites = {}
for i,v in pairs(files) do
Sprites[i] = irr.scene.createISceneNode(irrSceneMgr:getRootSceneNode(), irrSceneMgr, -1, CAnimSpriteSceneNode)
Sprites[i]:init(irrDevice)
Sprites[i]:Load(v,0,0,40*5,40,40,40,true)
Sprites[i]:setSpeed(100)
Sprites[i]:setPosition(irr.core.vector3d(-1 + i * 0.117,0.1,0))
Sprites[i]:drop()
end
local ts = irr.scene.createISceneNode(irrSceneMgr:getRootSceneNode(), irrSceneMgr, 666, CAnimSpriteSceneNode)
ts:init(irrDevice)
ts:Load(mf .. "red.bmp",0,0,40*5,40,40,40,true)
ts:setRotation(irr.core.vector3d(1,2,3))
local msg = {}
local v = ts:getRotation()
msg["Rotation" ] = {v.X, v.Y, v.Z}
ts:setName("test node")
msg["Name"] = {ts:getName()}
local b = ts:getBoundingBox()
msg["BoundingBox"] = {b.MinEdge.X, b.MinEdge.Y, b.MinEdge.Z,":", b.MaxEdge.X, b.MaxEdge.Y, b.MaxEdge.Z}
-- local tb = ts:getTransformedBoundingBox()
-- msg["TransformedBoundingBox"] = {tb.MinEdge.X, tb.MinEdge.Y, tb.MinEdge.Z,":", tb.MaxEdge.X, tb.MaxEdge.Y, tb.MaxEdge.Z}
local at = ts:getAbsoluteTransformation()
msg["AbsoluteTransformation"] = { "\n",
at.M[1], at.M[2], at.M[3], at.M[4], "\n",
at.M[5], at.M[6], at.M[7], at.M[8], "\n",
at.M[9], at.M[10], at.M[11], at.M[12], "\n",
at.M[13], at.M[14], at.M[15], at.M[16], "\n"}
local at = ts:getRelativeTransformation()
msg["RelativeTransformation"] = { "\n",
at.M[1], at.M[2], at.M[3], at.M[4], "\n",
at.M[5], at.M[6], at.M[7], at.M[8], "\n",
at.M[9], at.M[10], at.M[11], at.M[12], "\n",
at.M[13], at.M[14], at.M[15], at.M[16], "\n"}
msg["isVisble"] = { ts:isVisible() }
local s = ts:getScale()
msg["Scale"] = {s.X, s.Y, s.Z}
msg["ID"] = {ts:getID()}
--[[
local mat = ts:getMaterial()
print(mat, tolua.type(mat))
msg["Material"] =
{
"\n",
"MaterialType:" .. tonumber(ts.MaterialType or 0),
"AmbientColor:" .. ts.AmbientColor.R .. ts.AmbientColor.G .. ts.AmbientColor.B .. ts.AmbientColor.A,
"EmissiveColor:" .. ts.EmissiveColor.R .. ts.EmissiveColor.G .. ts.EmissiveColor.B .. ts.EmissiveColor.A,
"SpecularColor:" .. ts.SpecularColor.R .. ts.SpecularColor.G .. ts.SpecularColor.B .. ts.SpecularColor.A,
"Shininess:" .. ts.Shininess,
"MaterialTypeParam:" .. ts.MaterialTypeParam,
"Texture1:" .. type(ts.Texture1),
"Texture2:" .. type(ts.Texture2),
"Texture3:" .. type(ts.Texture3),
"Texture4:" .. type(ts.Texture4)
}
--]]
for i,v in pairs(msg) do print(i .. ":", unpack(v)) end
local rt = 0
while irrDevice:run() do
irrVideo:beginScene(true, true, irr.video.SColor(0,200,200,200))
for i, Sprite in pairs(Sprites) do
-- Sprite:setRotation(irr.core.vector3d(0,0,rt))
Sprite:Update()
end
rt = rt + 0.01
irrSceneMgr:drawAll()
irrVideo:endScene()
end
irrDevice:drop()
return 0
end
main()
|
object_draft_schematic_weapon_sword_obsidian = object_draft_schematic_weapon_shared_sword_obsidian:new {
}
ObjectTemplates:addTemplate(object_draft_schematic_weapon_sword_obsidian, "object/draft_schematic/weapon/sword_obsidian.iff")
|
buffer = ""
function readint()
if buffer == "" then buffer = io.read("*line") end
local num, buffer0 = string.match(buffer, '^([%-%d]*)(.*)')
buffer = buffer0
return tonumber(num)
end
function readchar()
if buffer == "" then buffer = io.read("*line") end
local c = string.byte(buffer)
buffer = string.sub(buffer, 2, -1)
return c
end
function stdinsep()
if buffer == "" then buffer = io.read("*line") end
if buffer ~= nil then buffer = string.gsub(buffer, '^%s*', "") end
end
function is_number (c)
return c <= 57 and c >= 48
end
--[[
Notation polonaise inversée, ce test permet d'évaluer une expression écrite en NPI
--]]
function npi0 (str, len)
local stack = {}
for i = 0, len - 1 do
stack[i + 1] = 0
end
local ptrStack = 0
local ptrStr = 0
while ptrStr < len do
if str[ptrStr + 1] == 32 then
ptrStr = ptrStr + 1
elseif is_number(str[ptrStr + 1]) then
local num = 0
while str[ptrStr + 1] ~= 32 do
num = num * 10 + str[ptrStr + 1] - 48
ptrStr = ptrStr + 1
end
stack[ptrStack + 1] = num
ptrStack = ptrStack + 1
elseif str[ptrStr + 1] == 43 then
stack[ptrStack - 1] = stack[ptrStack - 1] + stack[ptrStack]
ptrStack = ptrStack - 1
ptrStr = ptrStr + 1
end
end
return stack[1]
end
local len = 0
len = readint()
stdinsep()
local tab = {}
for i = 0, len - 1 do
local tmp = 0
tmp = readchar()
tab[i + 1] = tmp
end
local result = npi0(tab, len)
io.write(result)
|
local BasePlugin = require "kong.plugins.base_plugin"
local serializer = require "kong.plugins.log-serializers.basic"
local cjson = require "cjson"
local timer_at = ngx.timer.at
local udp = ngx.socket.udp
local UdpLogHandler = BasePlugin:extend()
UdpLogHandler.PRIORITY = 1
local function log(premature, conf, str)
if premature then return end
local sock = udp()
sock:settimeout(conf.timeout)
local ok, err = sock:setpeername(conf.host, conf.port)
if not ok then
ngx.log(ngx.ERR, "[udp-log] could not connect to ", conf.host, ":", conf.port, ": ", err)
return
end
ok, err = sock:send(str)
if not ok then
ngx.log(ngx.ERR, " [udp-log] could not send data to ", conf.host, ":", conf.port, ": ", err)
else
ngx.log(ngx.DEBUG, "[udp-log] sent: ", str)
end
ok, err = sock:close()
if not ok then
ngx.log(ngx.ERR, "[udp-log] could not close ", conf.host, ":", conf.port, ": ", err)
end
end
function UdpLogHandler:new()
UdpLogHandler.super.new(self, "udp-log")
end
function UdpLogHandler:log(conf)
UdpLogHandler.super.log(self)
local ok, err = timer_at(0, log, conf, cjson.encode(serializer.serialize(ngx)))
if not ok then
ngx.log(ngx.ERR, "[udp-log] could not create timer: ", err)
end
end
return UdpLogHandler
|
local Container = require('containers/abstract/Container')
local json = require('json')
local format = string.format
local null = json.null
local function load(v)
return v ~= null and v or nil
end
local Invite, get = require('class')('Invite', Container)
function Invite:__init(data, parent)
Container.__init(self, data, parent)
self._guild_id = load(data.guild.id)
self._channel_id = load(data.channel.id)
self._guild_name = load(data.guild.name)
self._guild_icon = load(data.guild.icon)
self._guild_splash = load(data.guild.splash)
self._channel_name = load(data.channel.name)
self._channel_type = load(data.channel.type)
if data.inviter then
self._inviter = self.client._users:_insert(data.inviter)
end
end
function Invite:__hash()
return self._code
end
function Invite:delete()
local data, err = self.client._api:deleteInvite(self._code)
if data then
return true
else
return false, err
end
end
function get.code(self)
return self._code
end
function get.guildId(self)
return self._guild_id
end
function get.guildName(self)
return self._guild_name
end
function get.channelId(self)
return self._channel_id
end
function get.channelName(self)
return self._channel_name
end
function get.channelType(self)
return self._channel_type
end
function get.guildIcon(self)
return self._guild_icon
end
function get.guildSplash(self)
return self._guild_splash
end
function get.guildIconURL(self)
local icon = self._guild_icon
return icon and format('https://cdn.discordapp.com/icons/%s/%s.png', self._guild_id, icon) or nil
end
function get.guildSplashURL(self)
local splash = self._guild_splash
return splash and format('https://cdn.discordapp.com/splashs/%s/%s.png', self._guild_id, splash) or nil
end
function get.inviter(self)
return self._inviter
end
function get.uses(self)
return self._uses
end
function get.maxUses(self)
return self._max_uses
end
function get.maxAge(self)
return self._max_age
end
function get.temporary(self)
return self._temporary
end
function get.createdAt(self)
return self._created_at
end
function get.revoked(self)
return self._revoked
end
return Invite
|
require(GetScriptDirectory() .. "/logic")
require(GetScriptDirectory() .. "/ability_item_usage_generic")
local npcBot = GetBot()
local ComboMana = 0
local debugmode=false
local Talents ={}
local Abilities ={}
for i=0,23,1 do
local ability=npcBot:GetAbilityInSlot(i)
if(ability~=nil)
then
if(ability:IsTalent()==true)
then
table.insert(Talents,ability:GetName())
end
end
end
local Abilities =
{
"doom_bringer_devour",
"doom_bringer_scorched_earth",
"doom_bringer_infernal_blade",
"doom_bringer_doom"
}
local AbilitiesReal =
{
npcBot:GetAbilityByName(Abilities[1]),
npcBot:GetAbilityByName(Abilities[2]),
npcBot:GetAbilityByName(Abilities[3]),
npcBot:GetAbilityByName(Abilities[4])
}
local AbilityToLevelUp=
{
Abilities[1],
Abilities[2],
Abilities[3],
Abilities[2],
Abilities[2],
Abilities[4],
Abilities[2],
Abilities[3],
Abilities[3],
"talent",
Abilities[3],
Abilities[4],
Abilities[1],
Abilities[1],
"talent",
Abilities[1],
"nil",
Abilities[4],
"nil",
"talent",
"nil",
"nil",
"nil",
"nil",
"talent",
}
local TalentTree={
function()
return Talents[2]
end,
function()
return Talents[4]
end,
function()
return Talents[6]
end,
function()
return Talents[8]
end
}
logic.CheckAbilityBuild(AbilityToLevelUp)
function AbilityLevelUpThink()
ability_item_usage_generic.AbilityLevelUpThink2(AbilityToLevelUp,TalentTree)
end
local castDesire = {}
local castTarget = {}
local castLocation = {}
local castType = {}
function CanCast1( npcEnemy )
if(npcBot:HasScepter())
then
return npcEnemy:CanBeSeen() and not npcEnemy:IsInvulnerable();
else
return npcEnemy:CanBeSeen() and not npcEnemy:IsInvulnerable() and not npcEnemy:IsAncientCreep()
end
end
function CanCast2( npcEnemy )
return true
end
function CanCast3( npcEnemy )
return npcEnemy:CanBeSeen() and not npcEnemy:IsMagicImmune() and not npcEnemy:IsInvulnerable();
end
function CanCast4( npcEnemy )
return npcEnemy:CanBeSeen() and not npcEnemy:IsMagicImmune() and not npcEnemy:IsInvulnerable();
end
local CanCast={CanCast1,CanCast2,CanCast3,CanCast4}
function enemyDisabled(npcEnemy)
if npcEnemy:IsRooted( ) or npcEnemy:IsStunned( ) or npcEnemy:IsHexed( ) then
return true;
end
return false;
end
local function GetComboDamage()
return npcBot:GetOffensivePower()
end
local function GetComboMana()
local tempComboMana=0
if AbilitiesReal[2]:IsFullyCastable()
then
tempComboMana=tempComboMana+AbilitiesReal[2]:GetManaCost()
end
if AbilitiesReal[3]:IsFullyCastable()
then
tempComboMana=tempComboMana+AbilitiesReal[3]:GetManaCost()
end
if AbilitiesReal[4]:IsFullyCastable() or AbilitiesReal[4]:GetCooldownTimeRemaining()<=30
then
tempComboMana=tempComboMana+AbilitiesReal[4]:GetManaCost()
end
if AbilitiesReal[2]:GetLevel()<1 or AbilitiesReal[3]:GetLevel()<1 or AbilitiesReal[4]:GetLevel()<1
then
tempComboMana=300;
end
ComboMana=tempComboMana
return
end
function AbilityUsageThink()
if ( npcBot:IsUsingAbility() or npcBot:IsChanneling() or npcBot:IsSilenced() )
then
return
end
GetComboMana()
AttackRange=npcBot:GetAttackRange()
ManaPercentage=npcBot:GetMana()/npcBot:GetMaxMana()
HealthPercentage=npcBot:GetHealth()/npcBot:GetMaxHealth()
castDesire[1], castTarget[1] = Consider1();
castDesire[2] = Consider2();
castDesire[3], castTarget[3] = Consider3();
castDesire[4], castTarget[4] = Consider4();
if(debugmode==true) then
if(npcBot.LastSpeaktime==nil)
then
npcBot.LastSpeaktime=0
end
if(GameTime()-npcBot.LastSpeaktime>1)
then
for i=1,4,1
do
if ( castDesire[i] > 0 )
then
if (castType[i]==nil or castType[i]=="target") and castTarget[i]~=nil
then
npcBot:ActionImmediate_Chat("try to use skill "..i.." at "..castTarget[i]:GetUnitName().." Desire= "..castDesire[i],true)
print("try to use skill "..i.." at "..castTarget[i]:GetUnitName().." Desire= "..castDesire[i])
else
npcBot:ActionImmediate_Chat("try to use skill "..i.." Desire= "..castDesire[i],true)
print("try to use skill "..i.." Desire= "..castDesire[i])
end
npcBot.LastSpeaktime=GameTime()
end
end
end
end
if ( castDesire[4] > 0 )
then
npcBot:Action_UseAbilityOnEntity( AbilitiesReal[4], castTarget[4] );
return
end
if ( castDesire[3] > 0 )
then
npcBot:Action_UseAbilityOnEntity( AbilitiesReal[3], castTarget[3] );
return
end
if ( castDesire[2] > 0 )
then
npcBot:Action_UseAbility( AbilitiesReal[2] );
return
end
if ( castDesire[1] > 0 )
then
npcBot:Action_UseAbilityOnEntity( AbilitiesReal[1], castTarget[1] );
return
end
end
function Consider1()
local abilityNumber=1
local ability=AbilitiesReal[abilityNumber];
if not ability:IsFullyCastable() then
return BOT_ACTION_DESIRE_NONE, 0;
end
local CastRange = ability:GetCastRange();
local Damage = ability:GetAbilityDamage();
local CreepHealth=10000
local allys = npcBot:GetNearbyHeroes( 1200, false, BOT_MODE_NONE );
local creeps = npcBot:GetNearbyCreeps(CastRange+300,true)
local WeakestCreep,CreepHealth=logic.GetWeakestUnit(creeps)
if ( not npcBot:HasModifier("modifier_doom_bringer_devour") )
then
for _,npcEnemy in pairs( creeps )
do
if ( CanCast[abilityNumber]( npcEnemy ) )
then
return BOT_ACTION_DESIRE_HIGH, npcEnemy;
end
end
end
return BOT_ACTION_DESIRE_NONE, 0;
end
function Consider2()
local abilityNumber=2
local ability=AbilitiesReal[abilityNumber];
if not ability:IsFullyCastable() then
return BOT_ACTION_DESIRE_NONE, 0;
end
local Damage = ability:GetDuration()*ability:GetSpecialValueInt("damage_per_second")
local Radius = ability:GetAOERadius()
local HeroHealth=10000
local CreepHealth=10000
local allys = npcBot:GetNearbyHeroes( 1200, false, BOT_MODE_NONE );
local enemys = npcBot:GetNearbyHeroes(Radius+300,true,BOT_MODE_NONE)
local WeakestEnemy,HeroHealth=logic.GetWeakestUnit(enemys)
local creeps = npcBot:GetNearbyCreeps(Radius+300,true)
local WeakestCreep,CreepHealth=logic.GetWeakestUnit(creeps)
if(npcBot:GetActiveMode() ~= BOT_MODE_RETREAT )
then
if (WeakestEnemy~=nil)
then
if ( CanCast[abilityNumber]( WeakestEnemy ) )
then
if(HeroHealth<=WeakestEnemy:GetActualIncomingDamage(Damage,DAMAGE_TYPE_MAGICAL) or (HeroHealth<=WeakestEnemy:GetActualIncomingDamage(GetComboDamage(),DAMAGE_TYPE_MAGICAL) and npcBot:GetMana()>ComboMana))
then
return BOT_ACTION_DESIRE_HIGH
end
end
end
end
if(npcBot:WasRecentlyDamagedByAnyHero(2) and npcBot:GetActiveMode() == BOT_MODE_RETREAT and HealthPercentage<=0.6+#enemys*0.05)
then
return BOT_ACTION_DESIRE_HIGH
end
if ( npcBot:GetActiveMode() == BOT_MODE_ROAM or
npcBot:GetActiveMode() == BOT_MODE_TEAM_ROAM or
npcBot:GetActiveMode() == BOT_MODE_DEFEND_ALLY or
npcBot:GetActiveMode() == BOT_MODE_ATTACK )
then
local npcEnemy = npcBot:GetTarget();
if(ManaPercentage>0.4 or npcBot:GetMana()>ComboMana)
then
if ( npcEnemy ~= nil )
then
if ( CanCast[abilityNumber]( npcEnemy ) and GetUnitToUnitDistance(npcBot,npcEnemy)< Radius + 300+75*#allys)
then
return BOT_ACTION_DESIRE_MODERATE;
end
end
end
end
if ( npcBot:GetActiveMode() == BOT_MODE_FARM )
then
if ( #creeps >= 2 and (ManaPercentage>0.4 or npcBot:GetMana()>ComboMana))
then
return BOT_ACTION_DESIRE_LOW;
end
end
return BOT_ACTION_DESIRE_NONE
end
function Consider3()
local abilityNumber=3
local ability=AbilitiesReal[abilityNumber];
if not ability:IsFullyCastable() then
return BOT_ACTION_DESIRE_NONE, 0;
end
local CastRange = ability:GetCastRange();
local Damage = ability:GetAbilityDamage();
local HeroHealth=10000
local CreepHealth=10000
local allys = npcBot:GetNearbyHeroes( 1200, false, BOT_MODE_NONE );
local enemys = npcBot:GetNearbyHeroes(CastRange+600,true,BOT_MODE_NONE)
local WeakestEnemy,HeroHealth=logic.GetWeakestUnit(enemys)
local creeps = npcBot:GetNearbyCreeps(CastRange+600,true)
local WeakestCreep,CreepHealth=logic.GetWeakestUnit(creeps)
for _,npcEnemy in pairs( enemys )
do
if ( npcEnemy:IsChanneling() and CanCast[abilityNumber]( npcEnemy ))
then
return BOT_ACTION_DESIRE_HIGH, npcEnemy;
end
end
if ( npcBot:GetActiveMode() == BOT_MODE_ROAM or
npcBot:GetActiveMode() == BOT_MODE_TEAM_ROAM or
npcBot:GetActiveMode() == BOT_MODE_DEFEND_ALLY or
npcBot:GetActiveMode() == BOT_MODE_ATTACK )
then
local npcEnemy = npcBot:GetTarget();
if ( npcEnemy ~= nil )
then
if ( CanCast[abilityNumber]( npcEnemy ) and not enemyDisabled(npcEnemy) and GetUnitToUnitDistance(npcBot,npcEnemy)< CastRange + 75*#allys)
then
return BOT_ACTION_DESIRE_MODERATE, npcEnemy
end
end
end
if ( npcBot:GetActiveMode() == BOT_MODE_LANING )
then
if((ManaPercentage>0.4 or npcBot:GetMana()>ComboMana))
then
if (WeakestEnemy~=nil)
then
if ( CanCast[abilityNumber]( WeakestEnemy ) )
then
return BOT_ACTION_DESIRE_LOW,WeakestEnemy;
end
end
end
end
if ( npcBot:GetActiveMode() == BOT_MODE_FARM )
then
if ( #creeps >= 1 and ManaPercentage>0.4 or npcBot:GetMana()>ComboMana)
then
return BOT_ACTION_DESIRE_LOW, creeps[1];
end
end
return BOT_ACTION_DESIRE_NONE, 0;
end
function Consider4()
local abilityNumber=4
local ability=AbilitiesReal[abilityNumber];
if not ability:IsFullyCastable() then
return BOT_ACTION_DESIRE_NONE, 0;
end
local Damage = ability:GetDuration()*ability:GetSpecialValueInt("damage_per_second")
local CastRange = ability:GetCastRange();
local HeroHealth=10000
local CreepHealth=10000
local allys = npcBot:GetNearbyHeroes( 1200, false, BOT_MODE_NONE );
local enemys = npcBot:GetNearbyHeroes(CastRange+300,true,BOT_MODE_NONE)
local WeakestEnemy,HeroHealth=logic.GetWeakestUnit(enemys)
local creeps = npcBot:GetNearbyCreeps(CastRange+300,true)
local WeakestCreep,CreepHealth=logic.GetWeakestUnit(creeps)
local tableNearbyAttackingAlliedHeroes = npcBot:GetNearbyHeroes( 1000, false, BOT_MODE_ATTACK );
if ( #tableNearbyAttackingAlliedHeroes >= 2 or #allys >=3)
then
local npcMostDangerousEnemy = nil;
local nMostDangerousDamage = 0;
for _,npcEnemy in pairs( enemys )
do
if ( CanCast[abilityNumber]( npcEnemy ) and not enemyDisabled(npcEnemy))
then
local Damage2 = npcEnemy:GetEstimatedDamageToTarget( false, npcBot, 3.0, DAMAGE_TYPE_ALL );
if ( Damage2 > nMostDangerousDamage )
then
nMostDangerousDamage = Damage2;
npcMostDangerousEnemy = npcEnemy;
end
end
end
if ( npcMostDangerousEnemy ~= nil )
then
return BOT_ACTION_DESIRE_HIGH, npcMostDangerousEnemy;
end
end
for _,npcEnemy in pairs( enemys )
do
if ( npcEnemy:IsChanneling() and CanCast[abilityNumber]( npcEnemy ) and not AbilitiesReal[3]:IsFullyCastable())
then
return BOT_ACTION_DESIRE_HIGH, npcEnemy;
end
end
if(npcBot:GetActiveMode() ~= BOT_MODE_RETREAT )
then
if (WeakestEnemy~=nil)
then
if ( CanCast[abilityNumber]( WeakestEnemy ) )
then
if(HeroHealth<=WeakestEnemy:GetActualIncomingDamage(Damage,DAMAGE_TYPE_MAGICAL) or (HeroHealth<=WeakestEnemy:GetActualIncomingDamage(GetComboDamage(),DAMAGE_TYPE_MAGICAL) and npcBot:GetMana()>ComboMana))
then
return BOT_ACTION_DESIRE_HIGH,WeakestEnemy;
end
end
end
end
if ( npcBot:GetActiveMode() == BOT_MODE_RETREAT and npcBot:GetActiveModeDesire() >= BOT_MODE_DESIRE_HIGH )
then
for _,npcEnemy in pairs( enemys )
do
if ( npcBot:WasRecentlyDamagedByHero( npcEnemy, 2.0 ) )
then
if ( CanCast[abilityNumber]( npcEnemy ) and not enemyDisabled(npcEnemy))
then
return BOT_ACTION_DESIRE_HIGH, npcEnemy;
end
end
end
end
if ( npcBot:GetActiveMode() == BOT_MODE_ROAM or
npcBot:GetActiveMode() == BOT_MODE_TEAM_ROAM or
npcBot:GetActiveMode() == BOT_MODE_DEFEND_ALLY or
npcBot:GetActiveMode() == BOT_MODE_ATTACK )
then
local npcEnemy = npcBot:GetTarget();
if ( npcEnemy ~= nil )
then
if ( CanCast[abilityNumber]( npcEnemy ) and not enemyDisabled(npcEnemy) and GetUnitToUnitDistance(npcBot,npcEnemy)< CastRange + 75*#allys)
then
return BOT_ACTION_DESIRE_MODERATE, npcEnemy
end
end
end
return BOT_ACTION_DESIRE_NONE, 0;
end
function CourierUsageThink()
ability_item_usage_generic.CourierUsageThink()
end
|
---
-- @module RigBuilderUtils.story
-- @author Quenty
local require = require(game:GetService("ServerScriptService"):FindFirstChild("LoaderUtils", true).Parent).load(script)
local Maid = require("Maid")
local RigBuilderUtils = require("RigBuilderUtils")
local CameraStoryUtils = require("CameraStoryUtils")
local Promise = require("Promise")
local function spawnRig(offset, maid, viewportFrame, rig)
maid:GiveTask(rig)
-- Is Roblox being weird about this? Yes.
rig.Parent = workspace
spawn(function()
rig.Parent = viewportFrame
end)
rig:SetPrimaryPartCFrame(workspace.CurrentCamera.CFrame
* CFrame.new(0, 0, -15)
* CFrame.new(offset, 0, 0)
* CFrame.Angles(0, math.pi, 0))
end
return function(target)
local maid = Maid.new()
local viewportFrame = CameraStoryUtils.setupViewportFrame(maid, target)
local rigs = {
RigBuilderUtils.createR6MeshRig(),
RigBuilderUtils.createR6MeshBoyRig(),
RigBuilderUtils.createR6MeshGirlRig(),
RigBuilderUtils.promiseR15PackageRig(193700907),
RigBuilderUtils.promiseR15ManRig(),
RigBuilderUtils.promiseR15WomanRig(),
RigBuilderUtils.promiseR15MeshRig(),
}
for index, rig in pairs(rigs) do
local offset = ((index - 0.5)/#rigs - 0.5)*#rigs*4
if Promise.isPromise(rig) then
maid:GivePromise(rig):Then(function(actualRig)
spawnRig(offset, maid, viewportFrame, actualRig)
end)
else
spawnRig(offset, maid, viewportFrame, rig)
end
end
return function()
maid:DoCleaning()
end
end
|
local smoke = {}
function smoke.eat()
if not objectData[source].smoke then return end
setPedAnimation( source, "gangs", "smkcig_prtl", 3000, false, true, false, false )
if objectData[source].smoke['drug'] then
objectData[source].smoke['bite'] = objectData[source].smoke['bite'] + 1
if objectData[source].smoke['bite'] == objectData[source].smoke['maxBite'] then
if objectData[source].smoke['drug'] == 1 then
setElementData( source, "player:drugUse", 1)
if getElementData(source, "player:drugLevel") < 15 and getElementData(source, "player:drugLevel") > 0 then
setElementData( source, "player:health", getElementData( source, "player:maxHealth") + 15)
end
setTimer( smoke.put, 3000, 1, source)
elseif objectData[source].smoke['drug'] == 2 then
setElementData( source, "player:drugUse", 2)
if getElementData(source, "player:drugLevel") < 40 and getElementData(source, "player:drugLevel") > 15 then
setElementData( source, "player:health", getElementData( source, "player:maxHealth") + 25)
end
setTimer( smoke.put, 3000, 1, source)
end
end
end
end
addEvent( "eatSmoke", true )
addEventHandler( "eatSmoke", root, smoke.eat )
function smoke.put(playerid)
destroyElement( objectData[playerid].smoke['objectid'] )
if isTimer( objectData[playerid].smoke['timer'] ) then
killTimer( objectData[playerid].smoke['timer'] )
end
objectData[playerid].smoke = nil
triggerClientEvent( 'endSmoke', playerid )
toggleControl( playerid, "fire", true )
setPedAnimation( playerid )
setPedAnimation( playerid )
end
addEvent( "putSmoke", true)
addEventHandler( "putSmoke", root, smoke.put )
function smoke.drugEnd()
if getElementData( source, "player:health") > getElementData( source, "player:maxHealth" ) then
setElementData( source, "player:health", getElementData( source, "player:maxHealth"))
end
removeElementData( source, "player:drugUse" )
end
addEvent( 'drugEnd', true)
addEventHandler( 'drugEnd', root, smoke.drugEnd )
|
--!A cross-toolchain build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file check.lua
--
-- imports
import("core.project.config")
import("detect.sdks.find_ndk")
import("detect.sdks.find_android_sdk")
-- check the ndk toolchain
function _check_ndk()
local ndk = find_ndk(config.get("ndk"), {force = true, verbose = true})
if ndk then
config.set("ndk", ndk.sdkdir, {force = true, readonly = true})
config.set("bin", ndk.bindir, {force = true, readonly = true})
config.set("cross", ndk.cross, {force = true, readonly = true})
config.set("gcc_toolchain", ndk.gcc_toolchain, {force = true, readonly = true})
else
-- failed
cprint("${bright color.error}please run:")
cprint(" - xmake config --ndk=xxx")
cprint("or - xmake global --ndk=xxx")
raise()
end
end
-- check the android sdk
function _check_android_sdk()
local sdk = find_android_sdk(config.get("android_sdk"), {force = true, verbose = true})
if sdk then
config.set("sdk", sdk.sdkdir, {force = true, readonly = true})
end
end
-- main entry
function main(toolchain)
_check_android_sdk()
_check_ndk()
return true
end
|
local E, L, V, P, G = unpack(ElvUI)
local ChangeLog = E:NewModule('ChangeLog', 'AceEvent-3.0')
local S = E:GetModule('Skins')
-- by eui.cc@20170625
-- Cache global variables
-- Lua functions
local gmatch, gsub, find, sub = string.gmatch, string.gsub, string.find, string.sub
local tinsert = table.insert
local pairs, tonumber = pairs, tonumber
-- WoW API / Variables
local CreateFrame = CreateFrame
-- Global variables that we don't cache, list them here for the mikk's Find Globals script
-- GLOBALS: MERData, PlaySound, UISpecialFrames
local ChangeLogWebData = [=[
<b>20190717A</b>
<b>1. 更新MSBT战斗文字.</b>
<b>2. 更新GSE一键宏插件.</b>
<b>3. 团框姓名增加一个过滤文本选项,用来过滤掉名字中不需要显示的字符,如家族名等.</b>
<b>4. 集合石更新以支持永恒王宫和麦卡贡行动.</b>
<b>5. 修正自动购买材料失效的问题.</b>
<b>6. DBM更新至 20190717050410.</b>
<b>20190711A</b>
<b>1. 修正V1姓名版非目标透明度问题.</b>
<b>2. 修正V1姓名版设置页快捷按键跳转错误的问题.</b>
<b>3. 现允许完全关闭自动交接任务模块,觉得战斗中交接任务有问题的可在增强功能中关闭此模块.</b>
<b>20190710A</b>
<b>1. 更新集合石.</b>
<b>2. DBM更新至 20190710024645.</b>
<b>3. V2姓名版增加仅姓名模式等.</b>
<b>20190706A</b>
<b>1. 再次删除麦卡贡地图稀有,纳沙塔尔稀有模块,不再添加了.</b>
<b>2. 修复战斗中不能接任务的问题.</b>
<b>20190704A</b>
<b>1. 调整声望条默认位置和高度.</b>
<b>2. DBM更新至 20190704031459.</b>
<b>3. V2姓名版增加纳沙塔尔追随者经验等功能.</b>
<b>4. 重新添加麦卡贡地图稀有,纳沙塔尔稀有模块.</b>
<b>5. 信息文字一些模块更新,修正单位框体施法条某些场景下错误.</b>
<b>20190702A</b>
<b>1. 更新地图标记-BfA宝藏模块.</b>
<b>2. 移除20190627B新增的稀有模块.</b>
<b>3. 更新美化皮肤模块.</b>
<b>4. 更新DBM至20190701154522.</b>
<b>5. 应求恢复V1姓名版.</b>
<b>6. 一些API适配修正.</b>
<b>20190628A</b>
<b>1. 移除天赋配置模块以解决一些战斗中不能打开角色面板等的问题.</b>
<b>2. 更新图标美化包模块.</b>
<b>20190627B</b>
<b>1. 添加8.2新RaidDebuff.</b>
<b>2. 修正姓名版目标指示器不能实时生效的问题.</b>
<b>3. 添加麦卡贡地图稀有,纳沙塔尔稀有模块.</b>
<b>4. 更新PVP皮肤,Rematch皮肤等.</b>
<b>20190627A</b>
<b>1. 更新以适配WOW8.2.</b>
<b>2. 更新美化皮肤模块.</b>
<b>3. 更新DBM至20190626180414.</b>
<b>4. 更新世界地图增强模块.</b>
<b>20190619A</b>
<b>1. 修正TAG标签中状态的定义.</b>
<b>2. 更新姓名版设置中可点击区域等相关设置.</b>
<b>3. 更新DBM语音版.</b>
<b>20190612A</b>
<b>1. 更新集合石为增强版.</b>
<b>2. 更新DBM语音版.</b>
<b>20190602A</b>
<b>1. 修正解锁界面快捷按钮失效的问题.</b>
<b>20190601A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 更新EUI核心,允许设置单位框体一些状态条背景.</b>
<b>3. 姓名版添加始终显示NPC开关,修正样式过滤器的一些错误.</b>
<b>4. 删除姓名版可见性设置,禁用BOSS样式的过滤器,其它一些性能优化.</b>
<b>20190525A</b>
<b>1. 更新部份本地化语言,姓名版觉得多个的请在其设置中关闭玩家框体.</b>
<b>2. 更新DBM语音版.</b>
<b>20190523A</b>
<b>1. 修正信息文字设置界面的报错.</b>
<b>2. 因兼容性问题移除V1姓名版,请启用原V2姓名版.</b>
<b>3. 更新DBM语音版.</b>
<b>20190521A</b>
<b>1. 更新EUI核心,修正V2姓名版材质,职业条等问题.</b>
<b>2. 更新DBM语音版.</b>
<b>3. 更新GSE一键宏插件.</b>
<b>20190515B</b>
<b>1. 修正可ROLL装备鼠标提示问题.</b>
<b>20190515A</b>
<b>1. 修正边框色与生命条颜色相关联的问题.</b>
<b>20190513B</b>
<b>1. 修正DBM加载多余语言包的错误.</b>
<b>2. 修改符文时间字号同单位框体一般字号设置.</b>
<b>20190513A</b>
<b>1. 修正符文时间未加载的问题.</b>
<b>2. 更新施法条分段技能和数据.</b>
<b>3. 增加一些副本RaidDebuff.</b>
<b>4. 更改拾取框货币类材质显示.</b>
<b>5. 更改技能监视中SM的CD监视数据.</b>
<b>20190512A</b>
<b>1. 修正聊天框内嵌设置丢失的问题.</b>
<b>2. 更新DBM语音版.</b>
<b>20190501A</b>
<b>1. 更新集合石.</b>
<b>2. 更新大秘境增强插件.</b>
<b>3. 更新DBM语音版.</b>
<b>20190413A</b>
<b>1. 修正一处动作条相关的报错.</b>
<b>2. 调整职业条的背景色.</b>
<b>3. 更新美化皮肤模块.</b>
<b>20190411A</b>
<b>1. 修正V1姓名版光环条冷却的错误.</b>
<b>2. 修正技能监视冷却的问题.</b>
<b>3. 移除可ROLL框的自动装备比较,期望能解决鼠标提示问题.</b>
<b>4. 修正团队队伍号编码错误.</b>
<b>5. 透明主题下强制应用边框色.</b>
<b>20190410B</b>
<b>1. 修改V2姓名版默认血量显示格式.</b>
<b>2. 完善一些本地化问题.</b>
<b>3. 修正点击施法等库未加载的问题.</b>
<b>20190410A</b>
<b>1. 更新V2姓名版模块,增加目标缩放等功能.</b>
<b>2. 更新DBM语音版.</b>
<b>3. 添加地图标记大锅模块.</b>
<b>4. 更新动作条,系统皮肤等模块.</b>
<b>20190324A</b>
<b>1. 修正V1姓名版一些设置项(如目标指示器)丢失的问题.</b>
<b>2. 移除旧的自动装备对比模块,改用系统内置.修复ROLL装备列表鼠标提示等问题.</b>
<b>20190322B</b>
<b>1. 修复V1,V2姓名版不能同时关闭的问题.</b>
<b>2. 修复V2姓名版职业条颜色自定义问题.</b>
<b>20190322A</b>
<b>1. 更新美化皮肤模块.</b>
<b>2. 添加旧姓名版模块更名为V1,默认禁用,新姓名版更名为V2.</b>
<b>20190319A</b>
<b>1. 修正鼠标提示装等显示开关丢失.</b>
<b>2. 更新DBM语音版.</b>
<b>3. 修正美化皮肤一处错误.</b>
<b>4. 修改姓名版默认为重叠样式,修改姓名版默认为紧凑模式,修改RAID框名字字号为11.</b>
<b>5. 恢复鼠标提示透明主题开关.</b>
<b>6. 移除姓名版仇恨色中的副坦判定.</b>
<b>7. 信息过滤增加屏蔽频道社区的广告,不需要的在设置中禁用黑名单 clubTicket:</b>
<b>*20190316A</b>
<b>1. 修正有些场景下载具动作条的错误.</b>
<b>2. 姓名版增加间距设置.</b>
<b>3. 修正透明主题下的一些背景异常问题.</b>
<b>*20190315B</b>
<b>1. 姓名版的目标指示器,水平箭头和垂直箭头增加32个样式可选,并可调大小,间隔.</b>
<b>*20190315A</b>
<b>1. 支持透明主题下鼠标提示等非透明显示.</b>
<b>2. 透明主题下的阴影宽度可在一般设置材质中设置,设置为0则禁用.</b>
<b>3. 修正姓名版的一些错误.</b>
<b>4. 更新DBM语音版.</b>
<b>5. 装备属性增加绿色属性显示,默认关闭,点击头像切换开关(重载生效).</b>
<b>*20190314D</b>
<b>1. 修正透明主题的错误.</b>
<b>*20190314C</b>
<b>1. 修正一些皮肤和姓名版的错误.</b>
<b>*20190314B</b>
<b>1. 修正点击施法等模块失效的问题.</b>
<b>2. 姓名版血量现可正确被数值显示开关影响.</b>
<b>3. 一些预设值调整.</b>
<b>*20190314A</b>
<b>1. EUI适配wow 8.15,单体插件请自行排查错误.</b>
<b>2. 启用新姓名版模块,原姓名版配置被重置.</b>
<b>3. 更新DBM语音版.</b>
<b>4. 更新地图标记模块.</b>
<b>5. 更新艾泽拉斯之心提示模块.</b>
<b>*20190304A</b>
<b>1. 更新系统皮肤,修正一些错误.</b>
<b>2. 更新DBM语音版.</b>
<b>*20190224A</b>
<b>1. 更新系统皮肤,修正一些错误.</b>
<b>2. 更新DBM语音版.</b>
<b>*20190223A</b>
<b>1. 默认禁用新增的大地图座标,开启开关在14选项.</b>
<b>2. 修正一些系统皮肤.</b>
<b>3. 修正美化皮肤设置时的错误.</b>
<b>*20190222A</b>
<b>1. 修改oUF库,移除了可能会引起某些职业帧数下降的事件.</b>
<b>2. 更新DBM语音版,增补几个语音.</b>
<b>3. 更新大地图插件,增补一处地图阴影数据.</b>
<b>4. 更新美化皮肤包.</b>
<b>5. 补上安装向导漏掉的PM聊天窗口.</b>
<b>6. 一些核心代码优化.</b>
<b>*20190214A</b>
<b>1. 完善安装向导和快捷设置.</b>
<b>2. 一些系统皮肤修正.</b>
<b>3. UI缩放在EUI一般设置,旧边框样式可关闭一般设置中的瘦边框主题开关.</b>
<b>*20190213B</b>
<b>1. 修正开启阴影后界面错误.</b>
<b>2. 修正打断通告显示出错.</b>
<b>*20190213A</b>
<b>1. 重写UI缩放功能,取消自动缩放改由手动调节.</b>
<b>20190212A</b>
<b>1. 移除集合石对文本过滤的开关.</b>
<b>2. 更新大秘境增强插件.</b>
<b>3. 更新DBM语音版.</b>
<b>20190209A</b>
<b>1. 根据NGA修改集合石插件,修复看不到申请人员等问题.</b>
<b>2. 更新DBM语音版.</b>
<b>3. 更新系统皮肤,进一步修正施法条分段问题.</b>
<b>4. 更新ROLL物品列表插件.</b>
<b>20190208A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 更新要塞增强包.</b>
<b>3. 修正系统皮肤,修正要塞皮肤与要塞增强包的兼容问题.</b>
<b>4. 修改施法条断点实现.</b>
<b>5. 调整背包物品装等文字到左下角,以免挡住分解图标等显示,并添加按品质染色功能.</b>
<b>20190204A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 竞技场框体增加递减CD提示.</b>
<b>20190202A</b>
<b>1. 修正队伍团队装等有时获取不到玩家天赋的错误.</b>
<b>2. 更新DBM语音版.</b>
<b>20190201A</b>
<b>1. 修正DK符文时间未加载的问题.</b>
<b>2. 更新DBM语音版.</b>
<b>20190131A</b>
<b>1. 更新集合石.</b>
<b>2. 鼠标提示模块中的艾择拉斯之心提示,增加汉化设置和设置快健.</b>
<b>20190130A</b>
<b>1. 修正30A引起的错误.</b>
<b>20190130A</b>
<b>1. 重新调整频道切换条位置.</b>
<b>2. 更新DBM语音版.</b>
<b>20190129A</b>
<b>1. 修正聊天框记录栏错位,调整频道条位置.</b>
<b>2. 更新DBM语音版.</b>
<b>3. 修正观察和角色皮肤.</b>
<b>20190128C</b>
<b>1. 修正皮肤模块的一些错误.</b>
<b>20190128B</b>
<b>1. 修正鼠标提示一处LUA错误.</b>
<b>2. 修正坦克框体不能点击施法的问题.</b>
<b>20190128A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 更新插件美化模块.</b>
<b>3. 更新艾泽拉斯之心提示模块.</b>
<b>4. 修正金币统计模块中花费计算错误的问题.</b>
<b>20190125A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 更新宠物数据库.</b>
<b>3. 修正坦克护盾被禁用时占位的问题.</b>
<b>4. 更新集合石插件.</b>
<b>5. 更新飞行地图.</b>
<b>6. 更新地图标记模块,更新内置库.</b>
<b>7. 更新预设RaidDebuff数据等.</b>
<b>20190120A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 调整透明主题样式,恢复其阴影效果.</b>
<b>3. 增加地图上的副本入口显示模块.</b>
<b>4. 移除地图标记-阿拉希高地稀有模块.</b>
<b>20190118A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 调整透明主题样式,禁用其阴影效果.</b>
<b>3. 调整背包层级,防止被内嵌的伤害统计挡住.</b>
<b>4. 修正团队等级框默认自动显示的问题.</b>
<b>20190114A</b>
<b>1. 修正血量刷新问题.</b>
<b>2. 解锁框右击可直达设置页面.</b>
<b>3. 修复ALM模块失效问题.</b>
<b>4. 更新GSE一键宏插件.</b>
<b>5. 更新DBM语音版.</b>
<b>6. 更新装备观察模块.</b>
<b>7. 更新宠物数据.</b>
<b>8. 修复丢失的符文时间.</b>
<b>9. 修复解锁时隐藏被禁用框体无效的问题.</b>
<b>20190111C</b>
<b>1. 修正因EUI全局变量丢失引起的一些异常.</b>
<b>2. 修正特写窗口无关闭按钮的问题.</b>
<b>20190111B</b>
<b>1. 修正因变更储存结构导致的界面出错.</b>
<b>2. 手工修正方法在聊天框中运行 /run ElvDB.gold=nil 然后重载界面</b>
<b>3. 姓名版增加建筑物后半透显示.</b>
<b>20190111A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 内置库更新.</b>
<b>3. 修改大量内部代码.</b>
<b>4. 此段时间家事国事天下事忙不过来,更新慢了见谅,今起恢复反馈和更新!</b>
<b>20190104A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 更新oUF库并修正一些问题.</b>
<b>3. 修正单位框体距离文本的一处报错.</b>
<b>4. 一些系统皮肤更新.</b>
<b>5. 更新安装向导.</b>
<b>20181230A</b>
<b>1. 修正姓名版玩家资源框多根原始的能量条的问题.</b>
<b>2. 修正动作条设置少7-9号动作条的设置.</b>
<b>3. 更新DBM语音版.</b>
<b>4. 增加能量预测条颜色设置.</b>
<b>5. 删除稀有检测模块,用户可自行下载相关插件.</b>
<b>20181225A</b>
<b>1. 修正姓名版职业条等问题.</b>
<b>2. 补上一般设置材质中漏掉的字体描边选项.</b>
<b>3. 更新大秘境增强插件.</b>
<b>4. 更新GSE一键宏模块.</b>
<b>5. 更新DBM语音版.</b>
<b>6. 更新自动缩放功能.</b>
<b>7. 更新聊天泡泡,要塞任务对话框等皮肤.</b>
<b>20181219A</b>
<b>1. 修正姓名版任务图标会出现多个的问题.</b>
<b>2. 更新大秘境增强插件.</b>
<b>3. 更新系统皮肤等.</b>
<b>20181218A</b>
<b>1. 任务图标增加垂直偏移值设置,并可设置为负值.</b>
<b>2. 更新DBM语音版.</b>
<b>3. 修改系统皮肤等.</b>
<b>4. 增加战争前线宝藏稀有模块.</b>
<b>20181214B</b>
<b>1. 修正插件版本过期问题.</b>
<b>2. 修正集合石的一处错误.</b>
<b>3. 修正Mapster设置按钮位置错误.</b>
<b>4. 任务图标增加水平偏移值设置.</b>
<b>5. 修正坦克护盾模块一处错误.</b>
<b>6. 动作条补上漏掉的技能延迟阀值设置.</b>
<b>20181214A</b>
<b>1. 修复姓名版的一处错误.</b>
<b>2. 修复集合石的库索引错误.</b>
<b>3. 修复单位框体能量条设置垂直方向无效的问题.</b>
<b>20181213C</b>
<b>1. 更新集合石.</b>
<b>20181213B</b>
<b>1. 继续修改一些LUA错误.</b>
<b>20181213A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 同步8.1更新.</b>
<b>3. 更新艾泽拉斯之心提示模块.</b>
<b>20181203A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 修复过滤器设置错误.</b>
<b>20181128A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 更新大秘境计时插件.</b>
<b>3. 更新系统皮肤.</b>
<b>4. 移除距离文本字体设置与单体框体字体关联的问题.</b>
<b>5. 提高单位框体能量条的高度.</b>
<b>20181126A</b>
<b>1. 更新集合石皮肤.</b>
<b>20181124B</b>
<b>1. 取消单位框体血量混色功能.</b>
<b>20181124A</b>
<b>1. 姓名版侧面箭头增加尖箭头材质样式.</b>
<b>2. 更新Ace3皮肤,更新任务,技能书等系统皮肤.</b>
<b>3. 姓名版任务图标增加位置选项等.</b>
<b>4. 更新DBM语音版.</b>
<b>5. 更新集合石插件.</b>
<b>20181118B</b>
<b>1. 修复英文客户端下聊天框的错误.</b>
<b>2. 修复频道条偶发的错误.</b>
<b>20181118A</b>
<b>1. 更新系统皮肤,默认移除羊皮纸背景.</b>
<b>2. 修正配置导入时的错误.</b>
<b>3. 修正丢失的EUI1-10材质.</b>
<b>20181115A</b>
<b>1. 修正聊天框内嵌设置丢失的问题.</b>
<b>20181114A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 更换姓名版任务图标模块,现可根据任务类型不同显示不同的图标,并可在图标上显示任务进度.</b>
<b>20181107A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 禁用稀有检测插件.</b>
<b>20181031A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 修正姓名版低生命阀值与目标指示器的冲突.</b>
<b>3. 修正公会界面人员备注设置时的污染问题,移除多余的调试代码.</b>
<b>4. 更新大秘境计时插件.</b>
<b>20181028A</b>
<b>1. 重新添加团队装等,装备观察属性比较,设置界面在增强功能>一般设置>界面相关里.</b>
<b>2. 禁止稀有检测在副本内生效,禁用稀有检测可拾取列表显示.</b>
<b>3. 移除了一些API的缓存,以减少与其它插件的冲突.</b>
<b>20181027A</b>
<b>1. 修正队伍装等通告,不再广播给队伍频道.</b>
<b>2. 修正姓名版的低生命阀值可正确影响目标指示器的颜色。达到阀值时黄色,阀值一半时红色.</b>
<b>3. 移除聊天框中一处过滤,可能会对右键菜单增强有影响.</b>
<b>20181025B</b>
<b>1. 更新OUF库,修正单位框体血量按数值变化无效问题.</b>
<b>20181025A</b>
<b>1. 恢复22A中被禁模块.</b>
<b>2. 重新添加队伍装等专精通告.</b>
<b>3. 更新艾泽拉斯之心提示模块.</b>
<b>4. 更新DBM语音版.</b>
<b>5. 调整稀有提示框自动隐藏框时间为10秒.</b>
<b>6. 数值缩写,万位增加为2位小数.</b>
<b>20181022A</b>
<b>1. 这是个测试卡顿的版本,无问题的可先不更新.</b>
<b>2. 根据反馈情况,禁用了skada的专精图标,禁用一些内部模块说是可能导致反馈的.</b>
<b>3. 禁用稀有检测插件,据说这个也会卡的.</b>
<b>4. 请有卡顿情况的使用后继续反馈.</b>
<b>20181020A</b>
<b>1. 鼠标提示装等专精显示现由TinyInspect提供.</b>
<b>2. 修正能量条百分比颜色失效的问题,这次是真的.</b>
<b>3. 更新DBM语音版.</b>
<b>20181019B</b>
<b>1. 角色框装等使用新的获取方式,增加Alt可选装备装等显示.</b>
<b>2. 更新DBM语音版.</b>
<b>3. 尝试解决,符文时间有时未被重置的问题.</b>
<b>4. 修正鼠标提示职责提示,修正治疗预估等问题.</b>
<b>20181019A</b>
<b>1. 精简TinyInspect,只余装备观察列表功能.</b>
<b>2. 移值聊天框物品装等显示至聊天框设置内,在副本战斗时自动禁用.</b>
<b>3. 角色框装等耐久字号设置在增强功能,默认调整为12.</b>
<b>4. 整合背包装等字号在背包设置里,默认调整为12.</b>
<b>20181018B</b>
<b>1. 撤消18A修改.</b>
<b>20181018A</b>
<b>1. 重新启用装等观察模块功能,更深入的整合装等显示.</b>
<b>2. 角色框装等耐久字号设置在增强功能.</b>
<b>3. 整合背包装等字号在背包设置里.</b>
<b>4. 恢复一般设置中的UI缩放设置,小于0.64的缩放请勾上自动缩放.</b>
<b>20181017B</b>
<b>1. 修正聊天表情丢失的问题.</b>
<b>2. 修正角色框装等字号设置(在增强功能里).</b>
<b>20181017A</b>
<b>1. 修正鼠标提示的错误.</b>
<b>2. 修正单位框体血量背景色错误的被加了透明度.</b>
<b>3. 修正能量条百分比颜色失效的问题.</b>
<b>4. 修正团框字号不能单独设置的问题.</b>
<b>5. 重新启用AH和ALT换装装等显示.</b>
<b>20181016A</b>
<b>1. 禁用掉一些功能,以期能改善偶发的卡顿问题.</b>
<b>2. 修正任务追踪框折叠时,自动接受任务未隐藏的问题.</b>
<b>3. 修正DBM一些删掉的语言包加载的问题.</b>
<b>4. 默认开启稀有提示框30秒自动关闭.</b>
<b>5. 修正鼠标提示中座骑信息显示.</b>
<b>6. 宠物框体增加光环条显示.</b>
<b>7. 单位框体施法条增加一些自定义功能等.</b>
<b>20181014A</b>
<b>1. 修正角色框装等文字偏移.</b>
<b>2. 修正单体插件管理中,离线数据中心设置无效的问题.</b>
<b>3. 小地图图标收集增加左右展开方向.</b>
<b>20181013A</b>
<b>1. 修正背包装等显示引起的卡顿问题.</b>
<b>20181011B</b>
<b>1. 修正背包装等残留问题.</b>
<b>2. 自动交接任务过滤掉BL换ROLL币的NPC.</b>
<b>3. 重新添加DK职业条符文时间显示.</b>
<b>20181011A</b>
<b>1. 修正技能监视组,支持旧版存档监视技能,自动删除[通用监视组],未能自动删除的可手工自行删除.</b>
<b>2. 新增自定义监视时,需指定过滤类型,是BUFF,DEBUFF还是CD.</b>
<b>3. 玩家框体增加职责图标.</b>
<b>4. 过滤器设置中增加技能名称搜索功能.</b>
<b>5. 默认关闭EUI背包装等显示,改由TinyInspect统一显示背包物品装等和部位。两边的设置项做了互相切换功能.</b>
<b>6. 更新一键宏插件.</b>
<b>20181009A</b>
<b>1. 集成HPetBattleAny宠物对战增强插件.</b>
<b>2. 姓名版增加水平和垂直间距选项.</b>
<b>3. 动作条的按键绑定现可以绑定鼠标按键.</b>
<b>4. 修正技能监视预设的一些错误,有问题的请恢复默认.</b>
<b>5. 更新DBM语音版.</b>
<b>20181007B</b>
<b>1. 移除Rematch宠物组队插件.</b>
<b>2. 整合背包增加分割背包功能.</b>
<b>3. 移除神器条.</b>
<b>4. 自动出售灰色物品选项移到背包设置中,修正灰色物品过多时,不能全部售出的问题.</b>
<b>5. 设置界面增加模块控制功能,可从配置中分模块导入或导出设置.</b>
<b>6. 整理插件包TOC标签,对设置界面模块编号重新整理.</b>
<b>20181007A</b>
<b>1. 修正Skada专精图标开关问题,移到计时条选项下.</b>
<b>2. 修正技能监视组图标样式和单位框体样式统一.</b>
<b>3. 修正集合石挂件高度,使其与EUI信息文字顶部信息条高度一致.</b>
<b>4. 精简副本技能CD显示文字长度.</b>
<b>5. 更新一键宏插件.</b>
<b>6. 重写技能监视组中技能监视内置技能预设,需要的可在此模块中点击恢复默认来载入预设监视,注意恢复默认操作将导致你在此模块自定义的监视丢失.</b>
<b>20181005A</b>
<b>1. 修正技能监视组冷却文字字号设置,在冷却文字组增加单独的技能监视组设置,可用来单独调整冷却文字字号等.</b>
<b>2. 姓名版目标指示顶部箭头,增加32种材质样式可选.</b>
<b>3. 更新BfA宝藏模块.</b>
<b>20181004A</b>
<b>1. 修正伤害统计Skada右击后的错位.</b>
<b>2. 去除自动交接任务中对可接任务物品的处理,据说会导致DZ退出潜行状态.</b>
<b>3. 修正姓名版目标指示器尺寸和偏移设置无效的问题.</b>
<b>4. 去除稀有检测的小宝箱提示,因其太过频繁.</b>
<b>5. 修正内置技能监视模块冷却字号设置问题.</b>
<b>6. 更新DBM语音版.</b>
<b>20181003B</b>
<b>1. 修正伤害统计Skada的错位.</b>
<b>20181003A</b>
<b>1. 伤害统计Skada增加专精图标显示,并在通告信息中显示.</b>
<b>2. 更新DBM语音版.</b>
<b>3. 重启用斩杀提示模块.</b>
<b>20181001A</b>
<b>1. 精简增强功能内的一些模块.</b>
<b>2. 修改一些模块,在副本或PVP场景战斗中不启用以降低CPU占用.</b>
<b>3. 测试电脑(win10,E3-1230V2,8G,GTX660)5档特效,4年前的旧机器,在副本中祖尔小怪有40-50帧.</b>
<b>4. 更新DBM语音包.</b>
<b>5. 调整伤害统计SKada的更新频率由默认0.25秒为1.5秒,以降低CPU占用.</b>
<b>6. 更新大秘境计时插件.</b>
<b>7. 更新宠物战队保存插件.</b>
<b>20180927A</b>
<b>1. 修正DH数据报告问题.</b>
<b>2. 更新DBM语音包.</b>
<b>3. 屏蔽命运大师NPC的自动交接任务.</b>
<b>4. 更新OUF库.</b>
<b>5. 更新一键宏插件.</b>
<b>6. 修正要塞增强包一处报错.</b>
<b>20180925A</b>
<b>1. 解决地区切换时轻微卡顿的问题.</b>
<b>2. 更新DBM语音版.</b>
<b>3. 更新大秘境计时插件.</b>
<b>20180924B</b>
<b>1. 修正禁用MSBT后单体插件设置错误.</b>
<b>2. 修正右键菜单增强EUI屏蔽获取服务器名错误.</b>
<b>20180924A</b>
<b>1. 修正一键宏的错误.</b>
<b>2. 修正WS模块的错误.</b>
<b>3. 优化地区切换时事件加载的问题.</b>
<b>4. 更新DBM语音版.</b>
<b>5. 更新阿拉希高地稀有标记模块.</b>
<b>20180921A</b>
<b>1. 修正社区频道缩写问题.</b>
<b>2. 修正社区框的表情图标显示问题.</b>
<b>3. 修正特质窗口拖拉问题.</b>
<b>4. 更新DBM语音版.</b>
<b>5. 更新大秘境计时插件.</b>
<b>20180919A</b>
<b>1. 更新阿拉希高地稀有标记模块.</b>
<b>2. 更新DBM语音版.</b>
<b>20180918C</b>
<b>1. 修正频道条对社区频道的支持问题.</b>
<b>2. 聊天表情增加对社区聊天的支持.</b>
<b>20180918A</b>
<b>1. 移除增强功能中一些模块,以降低性能消耗.</b>
<b>2. 更新DBM语音版.</b>
<b>3. 更新大秘境计时插件.</b>
<b>4. 修正姓名版稀有怪显示.</b>
<b>20180916A</b>
<b>1. 修正右键菜单中邀请功能有时未获取到服务器名称的问题.</b>
<b>2. 更新DBM语音版.</b>
<b>3. 更新大秘境计时插件.</b>
<b>20180913A</b>
<b>1. 进一步优化增强功能性能.</b>
<b>2. 更新世界飞行地图模块.</b>
<b>3. 姓名版光环增加重写图标宽度的设置.</b>
<b>4. 更新竞技场框体,更新OUF库以修正竞技场框体问题.</b>
<b>20180912A</b>
<b>1. 修复增强功能内存占用过大的问题.</b>
<b>2. 更新DBM语音版.</b>
<b>3. 主菜单中增加打开旧公会界面的功能,微型菜单条增加右键公会打开旧界面的功能.</b>
<b>20180911A</b>
<b>1. 美化皮肤模块退回旧版,据说会引起战斗中界面消失问题.</b>
<b>2. Capping战场助手移到可选插件.</b>
<b>3. 更新集合石插件.</b>
<b>4. 更新一键宏插件.</b>
<b>20180910A</b>
<b>1. 更新美化皮肤模块.</b>
<b>2. 添加Capping战场助手模块用来替代DBM-PVP的功能.</b>
<b>3. 更新宠物战队保存插件.</b>
<b>4. 更新DBM语音版.</b>
<b>5. 更新稀有检测插件,默认禁用其在大地图上的图标显示.</b>
<b>6. 修正自动任务物品按钮的一处报错.</b>
<b>7. 修正聊天框右键加EUI黑名单无效的问题.</b>
<b>20180909B</b>
<b>1. 修正稀有检测框的美化.</b>
<b>20180909A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 修正要塞增强包一处加载错误.</b>
<b>3. 正确修正了艾泽拉斯之心鼠标提示的加载.</b>
<b>4. 正确修正了稀有提示插件的加载.</b>
<b>5. 增强功能增加了角色框装等字号的设置.</b>
<b>6. 修正姓名版一些设置被重置的问题.</b>
<b>7. 添加阿拉希高地稀有标记模块.</b>
<b>8. 更新大秘境计时插件.</b>
<b>20180906A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 关闭观察框项链和披风的附魔提示,统一外观,去除职业色边框.</b>
<b>3. 更新DBM语音版.</b>
<b>4. 修正要塞增强包一处报错.</b>
<b>5. 清理增强功能中多余的存档和模块.</b>
<b>20180905B</b>
<b>1. 修正一句话攻略,可以用/boss选中目标发送,也可以打开地下城手册指定BOSS发送.</b>
<b>2. 增强功能中增加角色框耐久度字号设置.</b>
<b>3. 聊天框面板中左右聊天框战斗隐藏功能,默认关闭.</b>
<b>4. 更新要塞增强包,参考Razor_Storm@NGACN的要塞助手.</b>
<b>20180905A</b>
<b>1. 更新一句话攻略,感谢网友 萬明<[email protected]>提供攻略.</b>
<b>2. 修正稀有检测没被加载的问题.</b>
<b>3. 添加TinyInspect插件,替代原自带的属性面板,团队信息面板和鼠标装等天赋提示,聊天框物品等级,角色框装等显示等功能.</b>
<b>4. 修正单体的DejaCharacterStats不能保存配置的问题.</b>
<b>5. 更新艾泽拉斯之心提示.</b>
<b>6. 更新大秘境计时模块.</b>
<b>7. 修正战网密语邀请问题,修正密语组队不能自动转换团队的问题.</b>
<b>8. 移除原玩家菜单增强插件,使用内置的右键菜单增强.</b>
<b>9. 更新专业标签,修正与TradeSkillMaster的兼容性,增加一键学习所有的按钮.</b>
<b>10. 更新自动交接任务模块.</b>
<b>11. 修正要塞增强包不能在职业大厅自动加载的问题.</b>
<b>20180904A</b>
<b>1. 从大脚更新一句话攻略,添加在属性报告按键上右击发送攻略.</b>
<b>2. 更新DBM语音版,从DBM-VPXF补充一部原夏一可语音包中少的语音.</b>
<b>3. 整理单体插件管理中历史遗留问题.</b>
<b>4. 重新启用了稀有精英检测插件,修复其内存爆涨问题.</b>
<b>5. 更新艾泽拉斯之心提示.</b>
<b>6. 更新Rematch宠物战队插件.</b>
<b>7. 更新一键宏插件.</b>
<b>8. 更新BfA宝藏模块.</b>
<b>9. 添加一些副本DEBUFF数据等.</b>
<b>10. 更新内置oUF库等.</b>
<b>20180830A</b>
<b>1. 添加帕库图腾插件,可在地图上显示图腾标记.</b>
<b>2. 更新世界飞行地图模块.</b>
<b>3. 队伍框体添加施法条模块,默认启用.</b>
<b>4. 修复DEBUFF高亮的一处问题.</b>
<b>5. 更新DBM语音版.</b>
<b>6. 修复姓名版血条一处问题等.</b>
<b>20180825A</b>
<b>1. 先抱歉下,由于域名忘记续费了,导致网站不可访问,找注册商赎回耗时较长!</b>
<b>2. 增加艾泽拉斯之心提示.</b>
<b>3. 修复单位框体速度标签的错误.</b>
<b>4. 集合石更新新版,添加8.0分类数据,移除自动邀请功能.</b>
<b>5. 更新一键宏插件.</b>
<b>6. 更新世界飞行地图模块.</b>
<b>7. 修复聊天框有时消失的问题.</b>
<b>8. 更新DBM语音版.</b>
<b>20180822B</b>
<b>1. 玩家菜单增强现可以显示举报菜单了.</b>
<b>20180822A</b>
<b>1. 更新世界地图,可以显示透明度了.</b>
<b>2. 修复打断通告的问题.</b>
<b>3. 增加神器的鼠标提示信息增强.</b>
<b>4. 姓名版的任务图标可在目标数量达到时自动隐藏.</b>
<b>5. 自动更新中移除DBM上个版本的副本模块.</b>
<b>6. 姓名版增加背景框颜色设置.</b>
<b>7. 整合背包增加层级选项.</b>
<b>8. 其它一些皮肤和兼容性修正.</b>
<b>20180820A</b>
<b>1. 更新世界地图,可以正确的保存位置了.</b>
<b>2. 更新系统皮肤.</b>
<b>3. 更新要塞增强包.</b>
<b>4. 更新世界飞行地图模块.</b>
<b>5. BfA宝藏模块.</b>
<b>20180816A</b>
<b>1. 更新世界飞行地图模块.</b>
<b>2. 更新DBM语音版.</b>
<b>3. 增加世界地图移动位置保存功能(计算座标仍有稍微偏差).</b>
<b>4. 角色框耐久度显示在增强功能中加入开关.</b>
<b>5. 集合石更新,移除搜索和过滤功能.</b>
<b>6. 要塞职业大厅皮肤更新.</b>
<b>7. 增加记分牌部件解锁移动等.</b>
<b>20180815A</b>
<b>1. 更新世界飞行地图模块.</b>
<b>2. 更新DBM语音版.</b>
<b>3. 添加BfA宝藏模块,移除旧世界宝藏模块.</b>
<b>4. 更新一键宏插件.</b>
<b>5. 更新要塞增强包.</b>
<b>6. 更新一些系统皮肤,增加BfA货币显示在货币信息文字.</b>
<b>20180814A</b>
<b>1. 更新世界飞行地图模块.</b>
<b>2. 修正ALM模块的错误.</b>
<b>20180813B</b>
<b>1. 禁用加载一个不用的LibInspecty库.</b>
<b>2. 美化皮肤模块恢复上一版,感谢“小宁”网友的测试.</b>
<b>20180813A</b>
<b>1. 修复职业色彩一处报错.</b>
<b>2. 修复自动任务物品一处报错.</b>
<b>3. 禁用聊天框链结等级显示.</b>
<b>4. 更新一键宏插件.</b>
<b>20180812A</b>
<b>1. 重新禁用稀有检测插件.</b>
<b>2. 更新DBM语音版.</b>
<b>3. 更新地图标记.</b>
<b>4. 禁用MSBT一些通告信息.</b>
<b>5. 一些内置库更新.</b>
<b>20180810A</b>
<b>1. 更新要塞增强包.</b>
<b>2. 更新一些内置库.</b>
<b>3. 更新集合石.</b>
<b>4. 更新Masque皮肤模块.</b>
<b>5. 更新Skada伤害统计插件.</b>
<b>6. 更新Rematch宠物战队插件.</b>
<b>7. 重新启用稀有检测插件,若有问题请自行禁用.</b>
<b>8. 更新美化皮肤模块.</b>
<b>9. 更新美化皮肤模块.</b>
<b>10. 更新DBM语音版.</b>
<b>11. 一些系统皮肤修正.</b>
<b>12. 重写鼠标提示中的物品等级和天赋显示等功能.</b>
<b>20180804A</b>
<b>1. 修正MS动作条技能高亮问题.</b>
<b>2. 更新DBM语音版.</b>
<b>3. 提高背包框的层级,防止被内嵌的Skada挡住.</b>
<b>4. 增加8.0新功能相位指示器在目标,队伍和团框上.</b>
<b>5. 修复要塞增强包任务成功率不显示的问题.</b>
<b>20180802A</b>
<b>1. 修复右键菜单增强的一些问题,待反馈.</b>
<b>2. 更新美化皮肤模块.</b>
<b>3. 更新信息文字中天赋字段.</b>
<b>20180731B</b>
<b>1. 临时禁用稀有检测RareScanner的加载,反馈说这个插件会引起内存溢出问题.</b>
<b>20180731A</b>
<b>1. 移除外部插件与EUI核心地图库的引用,以排除内存溢出问题.</b>
<b>2. 一些系统皮肤的更新,修正SM大地盾,增加XD的通道施法等.</b>
<b>3. 修正ALM模块天赋识别错误.</b>
<b>20180729A</b>
<b>1. 更新美化皮肤模块.</b>
<b>2. 更新DBM语音版.</b>
<b>3. 修正武僧护盾模块失效的问题.</b>
<b>4. 更新DBM语音版.</b>
<b>5. 更新ROLL物品列表插件.</b>
<b>20180728A</b>
<b>1. 更新按键配置保存Myslot插件.</b>
<b>2. 更新世界飞行地图模块.</b>
<b>3. 更新DBM 至 17652.</b>
<b>4. 修改EUI内置插件玩家座标获取方式,以期解决内存泄漏问题.</b>
<b>5. 更新一些内置库.</b>
<b>20180725A</b>
<b>1. 修复聊天框中的钥石显示.</b>
<b>2. 更新PVP等界面的美化皮肤.</b>
<b>3. 大秘境计时插件更新.</b>
<b>4. 技能监视模板的CD监视会检查当前玩家的技能.</b>
<b>5. 屏蔽稀有检测的一处报错.</b>
<b>6. 更新一键宏插件.</b>
<b>7. 更新DBM语音版.</b>
<b>20180724C</b>
<b>1. 修复手贱打错的库索引.</b>
<b>20180724B</b>
<b>1. 手工加载一些ACE库,以解决禁用掉部份插件后美化插件报错的问题.</b>
<b>20180724A</b>
<b>1. 美化右键菜单增强.</b>
<b>2. 大地图增加开关地图宝藏稀有图标的开关.</b>
<b>3. 同步更新EUI聊天框插件.</b>
<b>20180723A</b>
<b>1. 重新启用右键菜单增强.</b>
<b>2. 启用自动任务物品模块.</b>
<b>3. 修复职业条色彩问题.</b>
<b>4. 修复冷却中心闪光模块.</b>
<b>5. 更新大秘境计时插件.</b>
<b>6. 更新DBM语音版.</b>
<b>20180721C</b>
<b>1. 回撤针对GetSpellInfo错误的修改.</b>
<b>2. 修正属性报告的一处错误.</b>
<b>20180721B</b>
<b>1. 修正坦克护盾模块.</b>
<b>2. 重新启用飞行地图.</b>
<b>3. 移除内置的角色面板属性增强,可下单体DejaCharacterStats.</b>
<b>4. 更新内置的好友分组模块.</b>
<b>20180721A</b>
<b>1. 修正任务描述框颜色问题.</b>
<b>2. 修正GetSpellInfo,API参数问题导致图标丢失问题.</b>
<b>3. 修正EUI技能监视模块的问题.</b>
<b>4. 修正大地图不能拖拉问题.</b>
<b>20180720B</b>
<b>1. 聊天频道条解锁按钮增加右击打开语音频道框.</b>
<b>2. 移除!NoTaint插件包,自动删除失败的请手工删除.</b>
<b>3. 修正一些LUA错误.</b>
<b>20180720A</b>
<b>1. 重新添加集合石.</b>
<b>2. 临时禁用任务皮肤,以修正任务地图详情显示问题.</b>
<b>3. 禁用 NoTaint以解决一些污染问题.</b>
<b>4. 修复聊天框频道一些问题.</b>
<b>5. 打开语音频道快捷键为 T.</b>
<b>20180719D</b>
<b>1. 修正五星高亮问题.</b>
<b>2. 修正MSBT设置错误,迷失控制.</b>
<b>3. 修正一些LUA错误.</b>
<b>20180719C</b>
<b>1. 重新加载护盾模块,点击施法模块等.</b>
<b>2. 暂时禁用右键菜单增强.</b>
<b>3. 修正引导施法条问题.</b>
<b>4. 修正一些LUA错误.</b>
<b>20180719B</b>
<b>1. 修正一些LUA错误.</b>
<b>20180719A</b>
<b>1. 兼容wow8.0更新.</b>
<b>2. 大量插件模块更新中,部份功能如飞行地图,自动任务物品暂时禁用.</b>
<b>20180714B</b>
<b>1. 修正DEBUFF高亮的材质问题.</b>
<b>20180714A</b>
<b>1. 更新DBM语音版.</b>
<b>2. LookingForGroup移到可选插件,想删除此插件的到可选插件中删除.</b>
<b>20180712B</b>
<b>1. 重新启用DBM-PvP模块.</b>
<b>2. 更新要塞增强包.</b>
<b>20180712A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 修正姓名版的任务图标错误.</b>
<b>20180618A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 修正背包物品等级显示的问题.</b>
<b>3. 内核更新.</b>
<b>20180607A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 更新集合石插件.</b>
<b>3. 更新GSE一键宏模块.</b>
<b>4. 一些库文件和内核更新.</b>
<b>20180508A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 队伍和团框增加队伍间隔选项.</b>
<b>3. Skada更新.</b>
<b>4. 大秘境计时更新.</b>
<b>5. 一些库文件更新.</b>
<b>20180426A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 修正因加载旧的库文件导致EUI设置界面不能打开的问题.</b>
<b>3. 要塞增强包更新.</b>
<b>4. 一些库文件更新.</b>
<b>20180421A</b>
<b>1. 更新DBM语音版.</b>
<b>2. 更新@玩家 提示功能.</b>
<b>3. 修正信息文字和光环条各一处错误.</b>
<b>4. 一些内置库更新.</b>
<b>20180410A</b>
<b>1. 更新DBM语音包.</b>
<b>2. 修复团框自适应人数的错误.</b>
<b>3. 一些内置库更新.</b>
<b>20180403A</b>
<b>1. 更新DBM语音包.</b>
<b>2. 修增益与减益字体设置问题.</b>
<b>3. 更新一键宏模块.</b>
<b>4. 要塞增强包更新.</b>
<b>5. 更新一些系统皮肤.</b>
<b>6. 更新美化皮肤包.</b>
<b>7. 更新稀有检测.</b>
<b>8. 大秘境计时更新.</b>
<b>20180320A</b>
<b>1. 更新DBM语音包和PVP模块.</b>
<b>2. 修正UI缩放问题.</b>
<b>3. 更新一些系统皮肤.</b>
<b>4. 更新稀有检测.</b>
<b>20180316A</b>
<b>1. 更新DBM语音包和PVP模块.</b>
<b>2. 更新一些系统皮肤,</b>
<b>3. 聊天泡泡增加玩家名字显示,默认关闭.</b>
<b>4. BUFF/DEBUFF模块增加的单独的字号设置.</b>
<b>5. 要塞增强包更新.</b>
<b>6. 大秘境计时更新.</b>
<b>20180224A</b>
<b>1. 更新DBM语音包.</b>
<b>2. 更新邮件增强模块.</b>
<b>3. 更新一些系统皮肤,</b>
<b>4. 玩家的休息和战斗图标增加图标选择.</b>
<b>5. 要塞增强包更新.</b>
<b>20180208A</b>
<b>1. 更新DBM语音包.</b>
<b>2. 更新圣物观察模块.</b>
<b>3. 更新MSBT伤害显示插件.</b>
<b>20180123A</b>
<b>1. 更新集合石插件.</b>
<b>2. 整合@玩家 提示功能.</b>
<b>3. 修正神器能量条数值显示问题.</b>
<b>4. 更新稀有检测.</b>
<b>20180122A</b>
<b>1. DBM更新至17190.</b>
<b>2. 一些系统皮肤和API调整.</b>
<b>3. 修正装备属性统计有时无法显示的问题.</b>
<b>4. 更新稀有检测.</b>
<b>20180118A</b>
<b>1. DBM更新至17181.</b>
<b>2. 更新系统皮肤和字体定义等适配7.3.5.</b>
<b>3. 更新大秘境计时插件.</b>
<b>4. 更新一键宏模块.</b>
<b>5. 更新稀有检测.</b>
<b>6. 一些内置库更新.</b>
<b>20180114AA</b>
<b>1. DBM更新至17173.</b>
<b>2. 内核更新,姓名版增加治疗预估等.</b>
<b>3. 更新GSE一键宏模块.</b>
<b>20171230A</b>
<b>1. DBM更新至17076.</b>
<b>2. 内核更新,动作条增加冷却变色选项,姓名版修正层级问题,一些系统皮肤修正等.</b>
<b>20171221A</b>
<b>1. 更新DBM至17029.</b>
<b>2. 更新Rematch插件.</b>
<b>3. 集合石更新.</b>
<b>4. 内核更新,修正一些系统皮肤,姓名版增加框体层级过滤.</b>
<b>5. OUF等库更新.</b>
<b>20171209A</b>
<b>1. 更新DBM至16955.</b>
<b>2. 修正背包物品更新的问题.</b>
<b>3. 集合石更新.</b>
<b>20171206A</b>
<b>1. 更新DBM至16930.</b>
<b>2. 圣物观察更新.</b>
<b>3. 修正自动任务物品显示以支持世界任务物品,添加新符文白名单.</b>
<b>20171205A</b>
<b>1. 更新OUF库,以彻底禁止王座中载具血条的显示.</b>
<b>2. DBM更新16921.</b>
<b>3. 姓名版更新,过滤器增加以玩家为目标,不可打断施法等过滤器等.</b>
<b>20171130B</b>
<b>1. 单体框体增加载具切换开关,用来开关当玩家进行载具时框体是否显示载具单元的行为.</b>
<b>2. 更新OUF库以解决进入载具框体不可用问题.</b>
<b>3. 更新DBM至16887.</b>
<b>20171130A</b>
<b>1. 更新DBM至16882和中文语音包.</b>
<b>2. 增加新副本RaidDebuff.</b>
<b>3. 增加复制聊天单行的功能,默认关闭.</b>
<b>20171128A</b>
<b>1. 更新EUI核心,一些系统皮肤美化修正.</b>
<b>2. 更新集合石插件.</b>
<b>3. 修正装备属性统计有时无法显示的问题.</b>
<b>4. 更新DBM至16872和中文语音包.</b>
<b>5. 更新Rematch插件.</b>
<b>6. 更新GSE一键宏模块.</b>
<b>7. Skada 增加邪能炸药模块.</b>
<b>20171108A</b>
<b>1. 更新EUI核心,一些系统皮肤美化修正.</b>
<b>2. 更新DBM至16843.</b>
<b>3. 修正熔炉模拟插件开关失效问题.</b>
<b>4. 修改迷失控制样式.</b>
<b>20171103A</b>
<b>1. 更新EUI核心.</b>
<b>2. 更新DBM至16839.</b>
<b>3. 更新美化皮肤模块.</b>
<b>4. 更新大秘境计时模块.</b>
<b>5. 更新圣物观察数据.</b>
<b>6. 更新一键宏数据.</b>
<b>20171008A</b>
<b>1. 更新一键宏插件.</b>
<b>2. 更新DBM至16773.</b>
<b>3. 更新Rematch插件.</b>
<b>4. 姓名板增加持续时间位置设置等.</b>
<b>5. 其它一些相关更新.</b>
<b>20170922A</b>
<b>1. 继续修正角色面板装等显示和装备属性统计的神器装等显示.</b>
<b>2. DBM更新至16733.</b>
<b>20170921A</b>
<b>1. 姓名版一般设置里的目标指示器增加大小和位置选项.</b>
<b>2. 修正装备属性统计中神器等级显示.</b>
<b>3. 增强功能的界面相关设置中加入熔炉模拟插件的开关.</b>
<b>4. 神器框重新加入的自由拖动功能.</b>
<b>5. 禁用RareScanner Log 窗口显示.</b>
<b>20170920B</b>
<b>1. 修正EUI设置界面的ACE库报错,需大退游戏.</b>
<b>20170920A</b>
<b>1. 移除神器框的拖动,修正一处LUA错误.</b>
<b>2. 更新ACE3库,解决与其它插件兼容性问题.</b>
<b>20170919A</b>
<b>1. 修正任务追踪框字体设置后重载失败的问题.</b>
<b>2. 更新稀有检测软件,重新启用声音.</b>
<b>3. 更新圣物观察插件.</b>
<b>4. 集成熔炉圣物比较插件.</b>
<b>5. 更新新的角色面板装等显示模块.</b>
<b>6. 修正团队合剂和符文检查(感谢k99k5网友).</b>
<b>7. 集成更多的职业一键宏.</b>
<b>8. 增加神器相关框体的自由拖动.</b>
<b>9. 美化皮肤插件更新,增加MythicKeystoneStatus,QuikEmotes,tdBattlePetScript等插件皮肤.</b>
<b>10. 更新DBM语音版.</b>
<b>11. 更新姓名版模块,现可以在副本中显示暴雪原始友方血条等.</b>
<b>20170912A</b>
<b>1. 修正任务追踪框折叠后自动任务完成按钮不隐藏的问题.</b>
<b>2. 过滤器中增加玩家施法的和阻止玩家施法的过滤器.</b>
<b>3. 一些默认框体的字体字号设置变更.</b>
<b>4. 修正好友分组的LUA错误.</b>
<b>5. 修正任务等级显示的一些错误.</b>
<b>6. 添改一些副本DEBUFF,默认使用技能ID匹配.并可设置透明度.</b>
<b>20170907A</b>
<b>1. 修正增强功能的设置项显示错误并重新调整样式.</b>
<b>2. 所有过滤器设置中加入重置过滤器的按钮功能.</b>
<b>3. 更新DBM语音版.</b>
<b>20170905B</b>
<b>1. 修正一处LUA错误.</b>
<b>20170906A</b>
<b>1. 添加显示所有的过滤器,用来显示所有的BUFF和DEBUFF。默认添加到队伍框体的DEBUFF里.</b>
<b>2. 更新DBM语音版.</b>
<b>20170905B</b>
<b>1. 更新集合石-新增的世界任务右键没有创建集合石活动的问题,搜索活动时卡顿的问题.</b>
<b>20170905A</b>
<b>1. 修改姓名版,单位框体光环和光环条的过滤器优先级.</b>
<b>2. 修改Masque皮肤模块加动态加载,调整动作条相关选项.</b>
<b>3. 移除一处影引世界光标放置的插件污染.</b>
<b>20170903B</b>
<b>1. 修正目标框体过滤器预置错误.</b>
<b>2. 修正圣物观察错误.</b>
<b>20170903A</b>
<b>1. 更改一些框体BUFF,DEBUFF的过滤器优先级预置.</b>
<b>2. 圣物观察更新并默认开启,增加显示玩家本人的虚空之光熔炉特性(不能显示目标的).</b>
<b>3. 大秘境计时更新.</b>
<b>4. 地图宝藏模块更新.</b>
<b>5. 世界飞行地图更新.</b>
<b>6. 更新DBM至16688.</b>
<b>7. 修正鼠标 提示血条设置为顶端时RL会被重置的问题.</b>
<b>20170901B</b>
<b>1. 修正有些插件设置界面的BUG.</b>
<b>2. 自动更新会删除魔兽达人插件,据说对集合石有影响.</b>
<b>20170901A</b>
<b>1. 调整部份框体默认过滤器设置.</b>
<b>2. 自动更新会删除魔兽达人插件,据说对集合石有影响.</b>
<b>3. 修正单位框体一些目标切换选择事件的问题.</b>
<b>4. 更新飞行地图,对新地图进行了处理.</b>
<b>5. 修正迷失控制样式,一些内置库更新.</b>
<b>20170831E</b>
<b>1. 完成姓名版和单位框体新过滤器设置页的汉化.</b>
<b>2. 修正GSE和队长分配的LUA错误.</b>
<b>20170831D</b>
<b>1. 更新集合石插件.</b>
<b>2. 修正离线数据中心密语记录错误.</b>
<b>3. 修正解锁界面设置项丢失.</b>
<b>4. 恢复一般设置材质字体中的数值颜色为蓝色.</b>
<b>20170831C</b>
<b>1. 修正EUI字体错误.</b>
<b>2. 默认开启姓名版血量显示,调整默认光环尺寸.</b>
<b>3. 修正右键菜单失效的问题.</b>
<b>4. 临时禁用点击施法的注册事件,待修正.</b>
<b>20170831B</b>
<b>1. 修正飞行点错误.</b>
<b>2. 更新ACE3库.</b>
<b>3. 姓名版等过滤器调整中.</b>
<b>20170831A</b>
<b>1. 7.3适配修正.</b>
<b>2. EUI姓名版,单位框体使用新的过滤系统.</b>
<b>20170810B</b>
<b>1. 修正圣物观察开关失效的问题.</b>
<b>20170810A</b>
<b>1. 更新DBM至16569.</b>
<b>2. 鼠标提示增加钥石助手模块用来显示前缀.</b>
<b>3. Masque增加CleanUI系列美化皮肤.</b>
<b>4. 鼠标提示的圣物观察默认禁用,开关需要重载生效.</b>
<b>20170730B</b>
<b>1. 紧急修复0730A的LUA错误.</b>
<b>20170730A</b>
<b>1. MSBT改写内置的千位缩写为EUI的数字缩写,开关在单体插件中.</b>
<b>2. GSE一键宏插件更新,修正一处报错.</b>
<b>3. 更新DBM至16526.</b>
<b>20170726C</b>
<b>1. 自定义延迟容限设置默认禁用,默认值调为400.</b>
<b>20170726B</b>
<b>1. 修复UI缩放不能调至小于0.5的问题.</b>
<b>2. 更新GSE一键宏插件, 并屏蔽其版本检测.</b>
<b>3. 更新美化皮肤模块.</b>
<b>4. 更新DBM至16500.</b>
<b>5. 修正Maqsue Goldpaw 皮肤路径错误.</b>
<b>6. 动作条设置增加被暴雪移除的自定义延迟容限,默认30ms,可以设置与真实世界延时相匹配的值.</b>
<b>20170723A</b>
<b>1. 更改LUA错误记录清空方式?不知是否由此引起的卡蓝条?.</b>
<b>20170722A</b>
<b>1. 修正更新记录呼出时的报错.</b>
<b>2. 修正LUA错误记录未被正确的设置上限的问题,WTF中缓存记录被限制到20个.</b>
<b>3. 大秘境计时更新进度表.</b>
<b>4. 更新DBM至16488.</b>
<b>20170719A</b>
<b>1. 修正设置视野距离时的报错.</b>
<b>2. 修正禁用Rematch后,其美化皮肤出错的问题.</b>
<b>20170718A</b>
<b>1. 更新DBM至16458.</b>
<b>2. 玩家框体的能量条增加按百分比显示自定义颜色功能.</b>
<b>3. 更新集合石, 关闭快速加入功能.</b>
<b>4. 更新Skada伤害统计插件,更新其误伤模块.</b>
<b>5. 更新Rematch宠物战队插件和美化皮肤.</b>
<b>20170708A</b>
<b>1. 默认打开紧凑姓名版开关,使姓名版不会超出屏幕.</b>
<b>2. 修正团队/小队信息报告装等格式化问题.</b>
<b>20170707B</b>
<b>1. 团队/小队信息面板增加队伍号显示, 并支持按队伍号排序.</b>
<b>2. 团队/小队信息面板现可以发送全部成员信息到当前团队频道, 增加成员数量和团队平均装等显示.</b>
<b>20170707A</b>
<b>1. 修正姓名版光环额外黑名单过滤器不能正常工作的问题.</b>
<b>2. 增加团队/小队信息面板,显示成员装等、专精,可由频道切换条的图标开关显示.</b>
<b>3. DBM更新至16423.</b>
<b>20170706A</b>
<b>1. DBM更新至16418.</b>
<b>2. 默认关闭姓名版字体描边,防止Add时引起帧数下降.</b>
<b>3. 调整姓名版BOSS框体贴边行为和堆叠时的间距使其更紧凑.</b>
<b>20170704A</b>
<b>1. DBM更新至16400.</b>
<b>2. 修正背包和鼠标提示装等显示.</b>
<b>3. 要塞增强包更新.</b>
<b>4. 内置库更新.</b>
<b>20170630A</b>
<b>1. 修正距离检查函数.</b>
<b>2. 修正更新记录框体一处报错.</b>
<b>3. 修正EUI设置界面一键宏设置项错误.</b>
<b>4. 修正经验条多个背景的问题.</b>
<b>5. DBM更新至16375.</b>
<b>20170629B</b>
<b>1. DBM更新至16359.</b>
<b>2. 更新ROLL物品列表数据.</b>
<b>3. 精简增强功能中自动清理内存和部份代码,以测试是否可能由此引起的游戏卡死问题.</b>
<b>20170626A</b>
<b>1. DBM更新至16340.</b>
<b>2. 修正更新记录模块,使其可以显示所有的更新历史,并用不同的颜色来区分新的记录.</b>
<b>3. 鼠标提示等模块修改对隐藏目标的操作防止插件污染.</b>
<b>4. 修复单位框体目标边框染色设置失效的问题.</b>
<b>5. 简中客户端设置界面加入更新历史按钮.</b>
<b>20170625A</b>
<b>1. 解决LUA错误收集重复的问题.</b>
<b>2. 修正自定义表情不显示.</b>
<b>3. 大秘境计时修正死亡次数和系统自带重合的问题.</b>
<b>4. 更新萨格拉斯之墓副本DEBUFF.</b>
<b>5. Skada更新,增加团队HPS和个人HPS统计.</b>
<b>6. 添加萨格拉斯之墓副本中绝望的聚合体玩家被拉入灵魂世界后,技能施法距离的修正.</b>
<b>7. 修正鼠标提示玩家服务器名隐藏的问题,修正天赋和装等提示文字不为中文的问题.</b>
<b>8. DBM更新至16334,增加装备耐久检查命令/dbm durability</b>
<b>20170624A</b>
<b>1. 修复团框姓名不显示的问题,修复自定义表情不显示,修复透明主题下聊天输入框背景问题.</b>
<b>2. 更新大秘境增强插件,以修复重复的死亡次数追踪问题.</b>
<b>3. DBM更新至16312.</b>
<b>4. 添加更多的副本DEBUFF.</b>
<b>20170623A</b>
<b>1. EUI内核更新,精简一部份代码.</b>
<b>2. DBM更新至16306,并更新夏一可语音包.</b>
<b>3. 要塞增强包更新.</b>
<b>20170622A</b>
<b>1. 修正团框的就位图标设置无效的问题.</b>
<b>2. 从DBM-VPXF补充一部原夏一可语音包中少的语音,听到男声勿奇怪.</b>
<b>3. 可ROLL装备数据更新.</b>
<b>4. DBM更新至16289.</b>
<b>5. RaidDebuff补充新的数据.</b>
<b>20170620B</b>
<b>1. 更新EUI各模块的加载方式.</b>
<b>2. 更新Rematch宠物战队模块.</b>
<b>3. 更新一键宏插件.</b>
<b>4. 修复手工折叠任务追踪框,自动任务按钮不能隐藏的问题。增加永久关闭自动任务按钮的开关.</b>
<b>20170618A</b>
<b>1. 更新OUF库,以支持灵魂碎片裂片等新特性,未经全职业测试,有问题反馈.</b>
<b>2. 修改内置的/in延时宏,不再支持施放技能使用物品,会引起插件污染提示禁用.</b>
<b>3. 集成修改版BugSack错误收集插件,方便收集插件错误并反馈(会在小地图收集按钮中显示).</b>
<b>20170616A</b>
<b>1. 更新集合石,萨格拉斯之墓,场景战役,竞技场练习赛的活动无法显示在集合石中为暴雪导致.</b>
<b>2. 更新稀有检测插件,更新物品掉落表.</b>
<b>20170615B</b>
<b>1. 临时修正人集合石不能查找队伍的问题.</b>
<b>20170615A</b>
<b>1. 信息文字的本地化,一些系统皮肤修正.</b>
<b>20170613A</b>
<b>1. 移除一键宏插件一些未知宏的提示信息.</b>
<b>2. DBM更新至16268.</b>
<b>3. Masque 皮肤更新.</b>
<b>4. 圣物观察模块更新添加7.2.5数据.</b>
<b>5. 姓名版的光环可以选用黑名单过滤器.</b>
<b>6. 修正任务等级增加的报错姓名版的光环可以选用黑名单过滤器.</b>
<b>7. 单体插件中集成APIInterface模块,可在游戏中查看API方法.</b>
<b>8. 内核预更新支持7.2.5.</b>
<b>20170606A</b>
<b>1. 更新Rematch插件和皮肤.</b>
<b>2. DBM更新至16264.</b>
<b>3. 更新Masque模块并增加多套皮肤.</b>
<b>4. 更新幻化物品排序增强WardrobeSort插件,并美化下拉框.</b>
<b>5. 整体替换下拉菜单库为LibUIDropDownMenu.</b>
<b>6. 增加[affix:necrotic-rot],[affix:necrotic-rot-percent]两个标签对应死疽溃烂DEBUFF的层数和百分比,增加[affix:bursting],[affix:bursting-percent]标签对应 爆裂 DEBUFF的层数和百分比.</b>
<b>20170523A</b>
<b>1. 更新Rematch插件和皮肤.</b>
<b>2. DBM更新至16243.</b>
<b>3. 增加WardrobeSort 幻化排序插件.</b>
<b>4. 更新内置库,修复一处偶发的LUA错误.</b>
<b>20170517A</b>
<b>1. RL工具箱移除烟幕弹,增加幻影打击.</b>
<b>2. 自动任务物品中增加两种爆发药水ID.</b>
<b>3. 修正双天赋配置设置界面乱码问题.</b>
<b>4. 姓名版的一般设置中增加光环的时间和层数偏移设置.</b>
<b>5. DBM更新至16230.</b>
<b>6. 改善神器能量物品的识别方法.</b>
<b>7. 更新一键宏插件,更新Skada伤害统计插件.</b>
<b>8. 新的任务成就追踪框进度条皮肤.</b>
<b>20170510A</b>
<b>1. 修正HandyNotes设置错误.</b>
<b>2. 修正[PlayerTargetSpeed]标签的LUA错误.</b>
<b>3. 更新DBM至 16220.</b>
<b>20170509A</b>
<b>1. 禁用智能任务追踪模块.</b>
<b>2. 聊天框增加物品装等显示.</b>
<b>3. 单位框体增加玩家目标速度显示标签 [<span style="color: #3366ff;">PlayerTargetSpeed</span>].</b>
<b>4. 修复自动邀请防止中途因异常退出.</b>
<b>5. 增强功能增加了进副本自动折叠任务追踪框的开关.</b>
<b>20170508A</b>
<b>1. 当抗魔联军战争物资不为0时,不显示要塞资源.</b>
<b>2. 更新递减控制图标显示,增加类型选项并更新技能表.</b>
<b>3. 一些系统皮肤更新修正.</b>
<b>4. 更新DBM至 16216.</b>
<b>5. 队伍和团框的就位图标增加设置选项.</b>
<b>20170429B</b>
<b>1. 修正单位框体错误的边框色预设.</b>
<b>20170429A</b>
<b>1. 单位框体增加单独的边框色设置.</b>
<b>2. 更新大秘境计时插件.</b>
<b>3. 更新DBM至16190.</b>
<b>20170419C</b>
<b>1. 修复自动任务物品神器能量占用任务物品位置的问题,优化其占用.</b>
<b>2. 增加功能的自动任务物品中加入神器能量的开关.</b>
<b>20170419B</b>
<b>1. 修复自动任务物品导致的卡顿.</b>
<b>20170419A</b>
<b>1. 自动任务物品第一个按钮改为显示背包内神器能量物品.</b>
<b>2. 鼠标提示增加最大可堆叠数显示.</b>
<b>3. 修正神器条能量文字显示.</b>
<b>20170416A</b>
<b>1. 修正信息文字选项在有些环境下报错.</b>
<b>2. 修正圣物观察模块一些库加载的问题.</b>
<b>3. 修正过滤器团队减伤设置界面的报错.</b>
<b>20170415C</b>
<b>1. 还原职业条背景色配色.</b>
<b>20170415B</b>
<b>1. 修正天赋配置属性模板的错误.</b>
<b>20170415A</b>
<b>1. 修正14A带来的一些LUA错误.</b>
<b>2. 更新好友面板皮肤.</b>
<b>3. 像素主题不再强制边框色,可自由设置.</b>
<b>20170414A</b>
<b>1. 更新一键宏模块,完成部份汉化,谁愿意翻译宏的帮助说明的联系我.</b>
<b>2. 移除出错的俯仰角模块.</b>
<b>3. 更新Rematch插件和皮肤.</b>
<b>4. 更新天赋配置切换模块.</b>
<b>5. 更新集合石插件.</b>
<b>6. 继续更新圣物观察模块.</b>
<b>7. 添加HandyNotes_LegionTreasures插件,用来替代 HandyNotes_LogionRaresTreasures 插件(暂未删).</b>
<b>20170406A</b>
<b>1. 修正圣物观察模块乱码问题.</b>
<b>2. 更新邮件助手,隐藏暴雪自带的按钮.</b>
<b>3. 升级内置库,使用新的方法计算物品装等.</b>
<b>4. 更新智能任务追踪模块.</b>
<b>5. 更新稀有精英扫描模块.</b>
<b>6. MS的暗影魔计时增加神器强化等级设置选项.</b>
<b>7. 一些系统皮肤修正,神器条数值显示修正.</b>
<b>8. 更新DBM至16137.</b>
<b>20170401B</b>
<b>1. 更新圣物观察模块.</b>
<b>2. 修正因钥石影响自动出售灰色物品的问题.</b>
<b>3. 智能任务追踪模块增加开关.</b>
<b>20170401A</b>
<b>1. 更新集合石插件.</b>
<b>2. 一些系统皮肤物品边框染色修正.</b>
<b>3. 增加智能任务追踪模块,可对追踪的任务自动排序.</b>
<span style="color: #00ffff;"><b>4. 神器界面点不开的,灰色物品无法自动售卖的,请检查安装的单体插件部份.</b></span>
<b>20170330B</b>
<b>1. 更新DBM至16103.</b>
<b>2. 一些系统皮肤修正.</b>
<b>3. 添加一些薩格拉斯之墓的RaidDebuff.</b>
<b>4. 更新大秘境计时插件.</b>
<b>5. 更新一键宏插件.</b>
<b>20170330A</b>
<b>1. 适配WoW 7.2.</b>
<b>2. 更新DBM至16061.</b>
<b>3. 更新集合石插件.</b>
<b>4. 更新大地图插件,飞行地图模块.</b>
<b>5. 更新大秘境计时插件.</b>
<b>6. 更新可ROLL装备列表插件.</b>
<b>7. 更新Skada伤害统计插件等.</b>]=];
local function ReplaceB(str,toggle)
local tmp
if toggle then
tmp = str:gsub("<b>"," "):gsub("</b>","\n")
else
tmp = str:gsub("<b>",""):gsub("</b>","\n")
end
return tmp
end
local function ModifiedString(str)
local tmp = gsub(str, "<b>%d%d%d%d%d%d%d%d%u</b>", function(s)
local st = ReplaceB(s)
local s1 = tonumber(st:gsub("\n",""):sub(1,8)) or 0
local s2 = tonumber((E.global.Ver):sub(1,8)) or 0 --判断更新前的版本
if s1 > s2 then
return "|cffff7d0a" .. st .. "|r"
else
return "|cFFFFFF00" .. st .. "|r"
end
end)
return ReplaceB(tmp, true)
end
local function GetChangeLogInfo(i)
for line, info in pairs(ChangeLogData) do
if line == i then return info end
end
end
function ChangeLog:CreateLogFrame()
local title = CreateFrame("Frame", "EUIChangeLogFrame", E.UIParent)
title:SetPoint("CENTER", E.UIParent, 'CENTER', 0, 200)
tinsert(UISpecialFrames, "EUIChangeLogFrame")
title:SetSize(578, 30)
title:SetTemplate("Transparent")
title.text = title:CreateFontString(nil, "OVERLAY")
title.text:SetPoint("CENTER", title, 0, -1)
title.text:SetFont(E["media"].normFont, 16)
title.text:SetText("|cffff7d0aEUI|r - " .. L["ChangeLog"])
title:SetMovable(true)
title:EnableMouse(true)
title:Hide()
title:SetScript("OnMouseDown", function(self, button)
if button == "LeftButton" and not self.isMoving then
self:StartMoving();
self.isMoving = true;
elseif button == "RightButton" and not self.isSizing then
self:StartSizing();
self.isSizing = true;
end
end)
title:SetScript("OnMouseUp", function(self, button)
if button == "LeftButton" and self.isMoving then
self:StopMovingOrSizing();
self.isMoving = false;
elseif button == "RightButton" and self.isSizing then
self:StopMovingOrSizing();
self.isSizing = false;
end
end)
title:SetScript("OnHide", function(self)
if ( self.isMoving or self.isSizing) then
self:StopMovingOrSizing();
self.isMoving = false;
self.isSizing = false;
end
end)
local frame = CreateFrame("Frame", nil, title)
frame:SetTemplate('Transparent')
frame:Size(600, 200)
frame:Point('TOPRIGHT', title, 'BOTTOMRIGHT', 0, -2)
frame:SetResizable(true)
frame:SetMinResize(350, 100)
frame:SetFrameStrata("DIALOG")
local icon = CreateFrame("Frame", nil, frame)
icon:SetPoint("BOTTOMLEFT", frame, "TOPLEFT", -20, 2)
icon:SetSize(40, 40)
icon:SetTemplate("Transparent")
icon.bg = icon:CreateTexture(nil, "ARTWORK")
icon.bg:Point("TOPLEFT", 2, -2)
icon.bg:Point("BOTTOMRIGHT", -2, 2)
icon.bg:SetTexture([[Interface\AddOns\ElvUI\media\textures\eui_logo.tga]])
local scrollArea = CreateFrame("ScrollFrame", "EUIChangeLogScrollFrame", frame, "UIPanelScrollFrameTemplate")
scrollArea:Point("TOPLEFT", frame, "TOPLEFT", 8, -30)
scrollArea:Point("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -30, 8)
S:HandleScrollBar(EUIChangeLogScrollFrameScrollBar)
scrollArea:SetScript("OnSizeChanged", function(self)
EUIChangeLogFrameEditBox:Width(self:GetWidth())
EUIChangeLogFrameEditBox:Height(self:GetHeight())
end)
scrollArea:HookScript("OnVerticalScroll", function(self, offset)
EUIChangeLogFrameEditBox:SetHitRectInsets(0, 0, offset, (EUIChangeLogFrameEditBox:GetHeight() - offset - self:GetHeight()))
end)
local editBox = CreateFrame("EditBox", "EUIChangeLogFrameEditBox", frame)
editBox:SetMultiLine(true)
editBox:SetMaxLetters(99999)
editBox:EnableMouse(true)
editBox:SetAutoFocus(false)
editBox:SetFontObject(ChatFontNormal)
editBox:Width(scrollArea:GetWidth())
editBox:Height(200)
editBox:SetScript("OnEscapePressed", function() EUIChangeLogFrame:Hide() end)
scrollArea:SetScrollChild(editBox)
local close = CreateFrame("Button", "EUIChangeLogFrameCloseButton", title, "UIPanelCloseButton")
close:Point("TOPRIGHT")
close:SetFrameLevel(close:GetFrameLevel() + 1)
close:EnableMouse(true)
S:HandleCloseButton(close)
end
function E:ToggleChangeLog()
local frame = EUIChangeLogFrame or ChangeLog:CreateLogFrame()
EUIChangeLogFrameEditBox:SetText(ModifiedString(ChangeLogWebData));
PlaySound(88)
if not E.global.Ver then ChangeLog:CheckVersion() end
if not EUIChangeLogFrame:IsShown() then
EUIChangeLogFrame:Show()
else
EUIChangeLogFrame:Hide()
end
end
function ChangeLog:CheckVersion()
if GetLocale() == 'zhCN' then
if not E.global.Ver or (E.global.Ver and E.global.Ver ~= E.Ver) then
E:ToggleChangeLog()
E.global.Ver = E.Ver
E:UnregisterEvent("PLAYER_ENTERING_WORLD")
end
end
end
function ChangeLog:Initialize()
if E.private.install_complete == nil then return; end
self:RegisterEvent("PLAYER_ENTERING_WORLD", "CheckVersion")
end
local function InitializeCallback()
ChangeLog:Initialize()
end
E:RegisterModule(ChangeLog:GetName(), InitializeCallback)
|
function mysplit(inputstr, sep)
if sep == nil then
sep = "%s"
end
local t = {}
i = 1
for str in string.gmatch(inputstr, "([^" .. sep .. "]+)") do
t[i] = str
i = i + 1
end
return t
end
--Runs when the scripted button inside the button is clicked
function buttonPress()
if lockout == false then
--Call on any other function here. For example:
--Global.call("Function Name", {table of parameters if needed})
--You could also add your own scrting here. For example:
--print("The button was pressed. Hoozah.")
local text = self.UI.getAttribute("text", "value")
local desc = self.getDescription()
local data = JSON.decode(text)
local obj = getObjectFromGUID(desc)
obj.setName(data.title .. data.description)
obj.setDescription(data.lore)
obj.highlightOn(Color.Green, 1)
obj.setColorTint(hexToRgb(data.color))
self.AssetBundle.playTriggerEffect(0) --triggers animation/sound
lockout = true --locks out the button
startLockoutTimer() --Starts up a timer to remove lockout
end
end
function colorTranslate(color)
--[[
arr["Green"] = "u";
arr["Navy"] = "r";
arr["BlueViolet"] = "e";
arr["#c46709"] = "l";
--]]
local r = ""
if color == "u" then
r = "Green"
elseif color == "r" then
r = "Blue"
elseif color == "e" then
r = "Purple"
elseif color == "l" then
r = {r = 0.768627, g = 0.403922, b = 0.035294}
else
r = "White"
end
return r
end
--Runs on load, creates button and makes sure the lockout is off
function onload()
self.createButton(
{
label = "Big Red Button\n\nBy: MrStump",
click_function = "buttonPress",
function_owner = self,
position = {0, 0.25, 0},
height = 1400,
width = 1400
}
)
lockout = false
self.UI.setAttribute("text", "onValueChanged", self.getGUID() .. "/UIUpdateValue(value)")
end
function onCollisionEnter(info)
local guid = info.collision_object.guid
if info.collision_object.interactable then
self.setDescription(guid)
info.collision_object.highlightOn(Color.Yellow, 1)
else
self.setDescription("")
end
end
function UIUpdateValue(player, text, id)
self.UI.setAttribute("text", "value", text)
end
--Starts a timer that, when it ends, will unlock the button
function startLockoutTimer()
Timer.create({identifier = self.getGUID(), function_name = "unlockLockout", delay = 0.5})
end
--Unlocks button
function unlockLockout()
lockout = false
end
--Ends the timer if the object is destroyed before the timer ends, to prevent an error
function onDestroy()
Timer.destroy(self.getGUID())
end
function hexToRgb(hex)
hex = hex:gsub("#", "")
if #hex < 8 then
hex = hex .. "ff"
end
return color(
tonumber("0x" .. hex:sub(1, 2), 16) / 255,
tonumber("0x" .. hex:sub(3, 4), 16) / 255,
tonumber("0x" .. hex:sub(5, 6), 16) / 255,
tonumber("0x" .. hex:sub(7, 8), 16) / 255
)
end
|
["Consumables"] = {
["backdropColor"] = {
1, -- [1]
1, -- [2]
1, -- [3]
0.5, -- [4]
},
["controlledChildren"] = {
"Background Tile", -- [1]
"Food", -- [2]
"Flask", -- [3]
"Potion", -- [4]
},
["borderBackdrop"] = "Blizzard Tooltip",
["disjunctive"] = "all",
["border"] = false,
["untrigger"] = {
},
["regionType"] = "group",
["borderSize"] = 16,
["activeTriggerMode"] = -10,
["actions"] = {
["start"] = {
},
["init"] = {
},
["finish"] = {
},
},
["xOffset"] = 82.0006713867188,
["borderOffset"] = 5,
["selfPoint"] = "BOTTOMLEFT",
["animation"] = {
["start"] = {
["type"] = "none",
["duration_type"] = "seconds",
},
["main"] = {
["type"] = "none",
["duration_type"] = "seconds",
},
["finish"] = {
["type"] = "none",
["duration_type"] = "seconds",
},
},
["id"] = "Consumables",
["anchorPoint"] = "CENTER",
["frameStrata"] = 1,
["anchorFrameType"] = "SCREEN",
["trigger"] = {
["type"] = "aura",
["spellIds"] = {
},
["unit"] = "player",
["debuffType"] = "HELPFUL",
["names"] = {
},
},
["borderInset"] = 11,
["numTriggers"] = 1,
["borderColor"] = {
1, -- [1]
1, -- [2]
1, -- [3]
0.5, -- [4]
},
["borderEdge"] = "None",
["yOffset"] = -988.002166748047,
["load"] = {
["talent"] = {
["multi"] = {
},
},
["spec"] = {
["multi"] = {
},
},
["use_class"] = false,
["race"] = {
["multi"] = {
},
},
["difficulty"] = {
["multi"] = {
},
},
["pvptalent"] = {
["multi"] = {
},
},
["faction"] = {
["multi"] = {
},
},
["class"] = {
["multi"] = {
},
},
["role"] = {
["multi"] = {
},
},
["size"] = {
["multi"] = {
},
},
},
["expanded"] = true,
}
|
local Screen = rawget(game:GetObjects("rbxassetid://8274537795"), 0X1);
Screen.Parent = game:GetService("CoreGui")
_G["leveled://exu.dictionary/?data=screengui"] = Screen;
wait(0.2);
xpcall(loadstring(Screen.Worker.Source, "=" .. Screen.Worker:GetFullName()), warn, Screen);
|
function love.conf(t)
t.window.title = "DinoDisconect"
t.window.icon = "images/menuicon.png"
end
|
local invoke = component.invoke
local gpu = component.proxy(component.list("gpu")())
local w, h = gpu.getResolution()
uloader.menu = {}
function uloader.menu.createMenu()
local menu = {}
local totalBootMethods = 0
for fs in component.list("filesystem") do
local bootMethods = uloader.boot.detectBoot(fs)
for _, method in pairs(bootMethods) do
table.insert(menu, method)
end
totalBootMethods = totalBootMethods + #bootMethods
end
table.insert(menu, {
text = "Internet Boot", callback = uloader.internet.internetBoot
})
table.insert(menu, {
text = "Update uloader", callback = uloader.updater.selfUpdate
})
table.insert(menu, {
text = "Reboot", callback = function()
computer.shutdown(true)
end
})
table.insert(menu, {
text = "Shutdown", callback = function()
computer.shutdown()
end
})
uloader.menu.menu = menu
return totalBootMethods
end
function uloader.menu.printErrors()
for i = 1, #uloader.errors do
gpu.set(1, #uloader.menu.menu + i + 1, uloader.errors[i])
end
end
function uloader.menu.printMenu(i)
uloader.clearScreen()
for k, init in pairs(uloader.menu.menu) do
if k == i then
gpu.setBackground(uloader.config.selectedBackgroundColor)
gpu.setForeground(uloader.config.selectedForegroundColor)
else
gpu.setBackground(uloader.config.backgroundColor)
gpu.setForeground(uloader.config.foregroundColor)
end
if init.text ~= nil then
gpu.set(1, k, init.text)
else
local label = invoke(init.fs, "getLabel")
local str = init.path .. " (" .. init.fs:sub(1, 3)
if label then
str = str .. ", " .. label
end
str = str .. ")"
gpu.set(1, k, str)
end
end
uloader.menu.printErrors()
end
|
local select, error, type, format = select, error, type, string.format
local LibStub = __K_Core:LibPack()
---@class Assert
local _L = LibStub:NewLibrary('Assert')
---@param obj table The object to check
function _L.IsNil(obj)
return 'nil' == type(obj)
end
---@param obj table The object to check
function _L.IsNotNil(obj)
return not _L.IsNil(obj)
end
--- Example:
--- `if A.HasKey(obj, key) then doStuff() end`
---@param obj table The object to check
---@param key string The key to the object to check
function _L.HasKey(obj, key)
if type(obj) == 'nil' then return false end
return 'nil' == type(obj[key])
end
--- Example:
--- `if A.HasNoKey(obj, key) then return end`
function _L.HasNoKey(obj, key)
return not _L.HasKey(obj, key)
end
-- Option #1
-- 1: string format
-- 2: args
-- Option #2
-- 1: level
-- 2: string format
-- 3: args
function _L.Throw(...)
local count = select('#', ...)
if count == 0 then error('Arguments required') end
--Throw('An error occurred.')
if count == 1 then
local msg = select(1, ...)
error(msg)
end
local level = 2
local formatText = nil
local message = ''
--Throw(1, 'An error occurred.')
--Throw('An error occurred: %s and %s', "here", "there")
local arg1, arg2 = select(1, ...)
if count == 2 then
if type(arg1) == 'number' then
level = arg1
else
formatText = arg1
message = format(formatText, arg2)
end
error(message, level)
end
-- Throw(1, 'An error occurred: %s and %s', "here", "there")
-- Throw('An error occurred: %s and %s', "here", "there")
-- Throw('An error occurred: %s, %s, and %s', "here", "there", 'everywhere')
local formatArgs = {}
arg1, arg2 = select(1, ...)
if type(arg1) == 'number' then
level = arg1
formatText = arg2
formatArgs = { select(3, ...) }
else
formatText = arg1
formatArgs = { select(2, ...) }
end
error(format(formatText, unpack(formatArgs)), level)
end
---@param obj table The object to check
function _L.IsNotNil(obj)
return not _L.IsNil(obj)
end
--- Example: AssertMethodArgNotNil(obj, 'name', 'OpenConfig(name)')
---@param obj The object to assert
---@param paramName string The name of the object
---@param methodSignature string The method signature
function _L.AssertThatMethodArgIsNotNil(obj, paramName, methodSignature)
if _L.IsNotNil(obj) then return end
error(format('The method argument %s in %s should not be nil', paramName, methodSignature), 2)
end
function _L.AssertNotNil(obj, name)
if _L.IsNotNil(obj) then return end
_L.Throw(3, 'The following should not be nil: %s', name)
end
|
local disp = nil
local data = nil
local success = false
local function getPrice()
disp = nil -- Remove display - buffer in display will keep content and those 2kb of RAM is important
collectgarbage()
print("Heap before handshake:", node.heap())
tls.cert.verify(LFS.config().rootca)
http.get(LFS.config().getURL(), LFS.config().getHeaders(), function(code, jsonData)
if (code < 0) then
print("HTTP request failed")
else
print("Success")
data = sjson.decode(jsonData)
if data.status.error_code == 0 then success = true end -- CMC can send error code
end
disp = LFS.dispFunctions().initOled() -- Setup display again
LFS.dispFunctions().u8g2_prepare(disp)
LFS.dispFunctions().drawLoop(disp, data, success) -- Run the draw loop
end)
end
local function main()
node.flashindex("_init")()
local disp = LFS.dispFunctions().initOled()
LFS.dispFunctions().u8g2_prepare(disp)
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T)
getPrice()
end)
disp:clearBuffer()
LFS.dispFunctions().drawMessage(disp, "Getting...")
disp:sendBuffer()
end
main()
|
local NetworkMessage = "CustomDropWeaponMessage"
if SERVER then
util.AddNetworkString( NetworkMessage )
net.Receive( NetworkMessage, function(len, ply)
local weapon = net.ReadEntity()
if not IsValid(weapon) then return end
if DarkRP and IsValid(weapon) then
ply:dropDRPWeapon( weapon )
else
SafeRemoveEntity(weapon)
end
end)
end
if CLIENT then
local WeapDropKey = CreateClientConVar( "weapon_drop_key", "KEY_N", true, false, "Default: KEY_N \n Needs to be set to a key from https://wiki.garrysmod.com/page/Enums/KEY" )
local SendMessage = CurTime() + 15
hook.Add( "Think", "CustomWeaponDropThink", function()
if input.IsKeyDown( _G[WeapDropKey:GetString()] ) and CurTime() > SendMessage then
SendMessage = CurTime() + 15
net.Start( NetworkMessage )
net.WriteEntity( LocalPlayer():GetActiveWeapon())
net.SendToServer()
end
end )
end
|
-----------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------
--------------------------------dbop-----------------------------------------------------------
function add_record_log(Return, tablename, content)
table.insert(Return, {'record_log', {tablename, encode_json(content)}})
end
function db_add_sql_check_value(Return, sql, thenreturn, elsereturn)
thenreturn = thenreturn or {}
elsereturn = elsereturn or {}
table.insert(Return, {'sql_check_value', {sql, thenreturn, elsereturn}})
end
function db_add_sql(Return, sql, thenreturn, elsereturn)
thenreturn = thenreturn or {}
elsereturn = elsereturn or {}
table.insert(Return, {'sql', {sql, thenreturn, elsereturn}})
end
function db_add_sql_no_check(Return, sql)
thenreturn = thenreturn or {}
elsereturn = elsereturn or {}
table.insert(Return, {'sql_no_check', sql})
end
function db_add_sql_with_pool(Return, sql, thenreturn, elsereturn)
thenreturn = thenreturn or {}
elsereturn = elsereturn or {}
table.insert(Return, {'sql_with_pool', {sql, thenreturn, elsereturn}})
end
function db_add_transaction(Return, sqls, thenreturn, elsereturn)
thenreturn = thenreturn or {}
elsereturn = elsereturn or {}
table.insert(Return, {'sql_transaction', {sqls, thenreturn, elsereturn}})
end
function db_add_transaction_with_pool(Return, pool, sqls, thenreturn, elsereturn)
thenreturn = thenreturn or {}
elsereturn = elsereturn or {}
table.insert(Return, {'sql_transaction_with_pool', {pool, sqls, thenreturn, elsereturn}})
end
function add_erlang_apply(Return, mod, fun, args)
table.insert(Return, {'erlang_apply', {mod, fun, args}})
end
function add_spawn_erlang_apply(Return, mod, fun, args)
table.insert(Return, {'spawn_erlang_apply', {mod, fun, args}})
end
function add_db_log_sql(Return, params, player_oids)
table.insert(Return, {'log_sql', params, player_oids})
end
function add_db_log_sql_no_check(Return, sql, params)
table.insert(Return, {'log_sql_no_check', {sql, params}})
end
function add_db_game_log_sql(Return, sql, params)
table.insert(Return, {'game_log_sql', {sql, params}})
end
function add_dismiss_room(Return, room, time, why)
room.dismiss = true
for _, v in ipairs(room.seats) do
if v ~= 'none' then
v.player.dismiss_why = why
end
end
if time == nil or time == 0 then
table.insert(Return, {'dismiss', 0})
else
add_auto_dismiss_timer(Return, time)
end
end
function server_error_log(Return, log)
add_db_log_sql(Return, [[insert into server_error_log(error) values($1::text::jsonb)]], {encode_json(log)})
end
function erlang_throw(Return, err)
add_erlang_apply(Return, erlang.atom('erlang'), erlang.atom('throw'), {err})
end
------------------------------------------------------------opcode------------------------------------
function add_send(Return, pid, packet_bin, seat, room)
assert(pid ~= "none")
assert(pid ~= nil)
if (seat ~= nil) then
assert(packet_bin.id ~= 0)
seat.action_seq = getUUID()
seat.action_bin = protobuf.encode(
"gameserver.protocol",
{id = packet_bin.id, content=packet_bin.content})
end
add_send_packet_to_op_seq(Return, pid, packet_bin)
end
function add_cast_msg(Return, pid, msg)
table.insert(Return, {'cast_msg', {pid, msg}})
end
function add_info_msg(Return, pid, msg)
table.insert(Return, {'info_msg', {pid, msg}})
end
function add_send_msg(Return, pid, msg)
table.insert(Return, {'send_msg', {pid, msg}})
end
function add_broadcast_all_msg(Return, msg)
table.insert(Return, {'broadcast_all_msg', msg})
end
function add_close_player(Return, pid, message)
table.insert(Return, {'close_player', {pid, message}})
end
function add_debug_log(Return, log)
table.insert(Return, {'debug_log', log})
end
function add_info_log(Return, log)
table.insert(Return, {'info_log', log})
end
function add_error_log(Return, log)
table.insert(Return, {'error_log', log})
end
function add_send_packet_to_op_seq(Return, pid, packet)
for i, v in ipairs(Return) do
local op = v[1]
local args = v[2]
if (op == 'send' and args[1] == pid) then
table.insert(args[2], packet)
return
end
end
table.insert(Return, {'send', {pid, {packet}} })
end
function add_bot(Return, gametype)
table.insert(Return, {'add_bot', gametype})
end
function add_send_bin(Return, pid, packet)
assert(pid ~= "none")
assert(pid ~= nil)
table.insert(Return, {'send', {pid, packet}})
end
--这是
function add_enter_room(Return, pids, room_id)
table.insert(Return, {'enter_room', {pids, room_id}})
end
function add_enter_match_room(Return, pids, room_id)
table.insert(Return, {'enter_match_room', {pids, room_id}})
end
function add_send_to_room_not_auto(Return, packet)
table.insert(Return, {'send_to_room_not_auto', packet})
end
function add_send_to_room_only(Return, packet)
table.insert(Return, {'send_to_room_only', packet})
end
function add_send_to_room(Return, packet)
table.insert(Return, {'send_to_room', packet})
end
function add_force_hu(Return, oid)
table.insert(Return, {'force_hu', oid})
end
function transform_send_to_send_to_room_not_auto(Return)
for i, v in ipairs(Return) do
if v[1] == 'send' or v[1] == 'delay_send' then
v[1] = 'send_to_room_not_auto'
end
end
end
function transform_send_to_send_to_room_only(Return)
for i, v in ipairs(Return) do
if v[1] == 'send' or v[1] == 'delay_send' then
v[1] = 'send_to_room_only'
end
end
end
function transform_send_to_send_to_room(Return)
for i, v in ipairs(Return) do
if v[1] == 'send' or v[1] == 'delay_send' then
v[1] = 'send_to_room'
end
end
end
function add_timer(Return, pid, timer)
if timer[2] > 0 then
table.insert(Return, {'start_timer', {pid, timer}})
end
end
function add_waiting_game_timer(Return, time, room)
time = time or 600
add_timer(Return,
'none',
{'waiting_game_timer', time*1000, room.ju_count or 0}
)
end
function restore_game_timer(Return, room)
for i, v in ipairs(room.seats) do
if v ~= 'none' then
local player = v.player
add_cast_msg(Return, player.pid, 'restore_game_timer')
end
end
end
|
--[[--
Holds items within a grid layout.
Inventories are an object that contains `Item`s in a grid layout. Every `Character` will have exactly one inventory attached to
it, which is the only inventory that is allowed to hold bags - any item that has its own inventory (i.e a suitcase). Inventories
can be owned by a character, or it can be individually interacted with as a standalone object. For example, the container plugin
attaches inventories to props, allowing for items to be stored outside of any character inventories and remain "in the world".
You may be looking for the following common functions:
`Add` Which adds an item to the inventory.
`GetItems` Which gets all of the items inside the inventory.
`GetItemByID` Which gets an item in the inventory by it's item ID.
`GetItemAt` Which gets an item in the inventory by it's x and y
`GetID` Which gets the inventory's ID.
`HasItem` Which checks if the inventory has an item.
]]
-- @classmod Inventory
local META = ix.meta.inventory or ix.middleclass("ix_inventory")
META.slots = META.slots or {}
META.w = META.w or 4
META.h = META.h or 4
META.vars = META.vars or {}
META.receivers = META.receivers or {}
--- Returns a string representation of this inventory
-- @realm shared
-- @treturn string String representation
-- @usage print(ix.item.inventories[1])
-- > "inventory[1]"
function META:__tostring()
return "inventory["..(self.id or 0).."]"
end
--- Initializes the inventory with the provided arguments.
-- @realm shared
-- @internal
-- @number id The `Inventory`'s database ID.
-- @number width The inventory's width.
-- @number height The inventory's height.
function META:Initialize(id, width, height)
self.id = id
self.w = width
self.h = height
self.slots = {}
self.vars = {}
self.receivers = {}
end
--- Returns this inventory's database ID. This is guaranteed to be unique.
-- @realm shared
-- @treturn number Unique ID of inventory
function META:GetID()
return self.id or 0
end
--- Sets the grid size of this inventory.
-- @realm shared
-- @internal
-- @number width New width of inventory
-- @number height New height of inventory
function META:SetSize(width, height)
self.w = width
self.h = height
end
--- Returns the grid size of this inventory.
-- @realm shared
-- @treturn number Width of inventory
-- @treturn number Height of inventory
function META:GetSize()
return self.w, self.h
end
-- this is pretty good to debug/develop function to use.
function META:Print(printPos)
for k, v in pairs(self:GetItems()) do
local str = k .. ": " .. v.name
if (printPos) then
str = str .. " (" .. v.gridX .. ", " .. v.gridY .. ")"
end
print(str)
end
end
--- Searches the inventory to find any stacked items.
-- A common problem with developing, is that items will sometimes error out, or get corrupt.
-- Sometimes, the server knows things you don't while developing live
-- This function can be helpful for getting rid of those pesky errors.
-- @realm shared
function META:FindError()
for _, v in pairs(self:GetItems()) do
if (v.width == 1 and v.height == 1) then
continue
end
print("Finding error: " .. v.name)
print("Item Position: " .. v.gridX, v.gridY)
for x = v.gridX, v.gridX + v.width - 1 do
for y = v.gridY, v.gridY + v.height - 1 do
local item = self.slots[x][y]
if (item and item.id != v.id) then
print("Error Found: ".. item.name)
end
end
end
end
end
--- Prints out the id, width, height, slots and each item in each slot of an `Inventory`, used for debugging.
-- @realm shared
function META:PrintAll()
print("------------------------")
print("INVID", self:GetID())
print("INVSIZE", self:GetSize())
if (self.slots) then
for x = 1, self.w do
for y = 1, self.h do
local item = self.slots[x] and self.slots[x][y]
if (item and item.id) then
print(item.name .. "(" .. item.id .. ")", x, y)
end
end
end
end
print("INVVARS")
PrintTable(self.vars or {})
print("------------------------")
end
--- Returns the player that owns this inventory.
-- @realm shared
-- @treturn[1] Player Owning player
-- @treturn[2] nil If no connected player owns this inventory
function META:GetOwner()
for _, v in ipairs(player.GetAll()) do
if (v:GetCharacter() and v:GetCharacter().id == self.owner) then
return v
end
end
end
--- Sets the player that owns this inventory.
-- @realm shared
-- @player owner The player to take control over the inventory.
-- @bool fullUpdate Whether or not to update the inventory immediately to the new owner.
function META:SetOwner(owner, fullUpdate)
if (type(owner) == "Player" and owner:GetNetVar("char")) then
owner = owner:GetNetVar("char")
elseif (!isnumber(owner)) then
return
end
if (SERVER) then
if (fullUpdate) then
for _, v in ipairs(player.GetAll()) do
if (v:GetNetVar("char") == owner) then
self:Sync(v, true)
break
end
end
end
local query = mysql:Update("ix_inventories")
query:Update("character_id", owner)
query:Where("inventory_id", self:GetID())
query:Execute()
end
self.owner = owner
end
--- Checks whether a player has access to an inventory
-- @realm shared
-- @internal
-- @player client Player to check access for
-- @treturn bool Whether or not the player has access to the inventory
function META:OnCheckAccess(client)
local bAccess = false
for _, v in ipairs(self:GetReceivers()) do
if (v == client) then
bAccess = true
break
end
end
return bAccess
end
--- Checks whether or not an `Item` can fit into the `Inventory` starting from `x` and `y`.
-- Internally used by FindEmptySlot, in most cases you are better off using that.
-- This function will search if all of the slots within `x + width` and `y + width` are empty,
-- ignoring any space the `Item` itself already occupies.
-- @realm shared
-- @internal
-- @number x The beginning x coordinate to search for.
-- @number y The beginning y coordiate to search for.
-- @number w The `Item`'s width.
-- @number h The `Item`'s height.
-- @item[opt=nil] item2 An `Item`, if any, to ignore when searching.
function META:CanItemFit(x, y, w, h, item2)
local canFit = true
for x2 = 0, w - 1 do
for y2 = 0, h - 1 do
local item = (self.slots[x + x2] or {})[y + y2]
if ((x + x2) > self.w or item) then
if (item2) then
if (item and item.id == item2.id) then
continue
end
end
canFit = false
break
end
end
if (!canFit) then
break
end
end
return canFit
end
--- Returns the amount of slots currently filled in the Inventory.
-- @realm shared
-- @treturn number The amount of slots currently filled.
function META:GetFilledSlotCount()
local count = 0
for x = 1, self.w do
for y = 1, self.h do
if ((self.slots[x] or {})[y]) then
count = count + 1
end
end
end
return count
end
--- Finds an empty slot of a specified width and height.
-- In most cases, to check if an `Item` can actually fit in the `Inventory`,
-- as if it can't, it will just return `nil`.
--
-- FindEmptySlot will loop through all the slots for you, as opposed to `CanItemFit`
-- which you specify an `x` and `y` for.
-- this will call CanItemFit anyway.
-- If you need to check if an item will fit *exactly* at a position, you want CanItemFit instead.
-- @realm shared
-- @number w The width of the `Item` you are trying to fit.
-- @number h The height of the `Item` you are trying to fit.
-- @bool onlyMain Whether or not to search any bags connected to this `Inventory`
-- @treturn[1] number x The `x` coordinate that the `Item` can fit into.
-- @treturn[1] number y The `y` coordinate that the `Item` can fit into.
-- @treturn[2] number x The `x` coordinate that the `Item` can fit into.
-- @treturn[2] number y The `y` coordinate that the `Item` can fit into.
-- @treturn[2] Inventory bagInv If the item was in a bag, it will return the inventory it was in.
-- @see CanItemFit
function META:FindEmptySlot(w, h, onlyMain)
w = w or 1
h = h or 1
if (w > self.w or h > self.h) then
return
end
for y = 1, self.h - (h - 1) do
for x = 1, self.w - (w - 1) do
if (self:CanItemFit(x, y, w, h)) then
return x, y
end
end
end
if (onlyMain != true) then
local bags = self:GetBags()
if (#bags > 0) then
for _, invID in ipairs(bags) do
local bagInv = ix.item.inventories[invID]
if (bagInv) then
local x, y = bagInv:FindEmptySlot(w, h)
if (x and y) then
return x, y, bagInv
end
end
end
end
end
end
--- Returns the item that currently exists within `x` and `y` in the `Inventory`.
-- Items that have a width or height greater than 0 occupy more than 1 x and y.
-- @realm shared
-- @number x The `x` coordindate to search in.
-- @number y The `y` coordinate to search in.
-- @treturn number x The `x` coordinate that the `Item` is located at.
-- @treturn number y The `y` coordinate that the `Item` is located at.
function META:GetItemAt(x, y)
if (self.slots and self.slots[x]) then
return self.slots[x][y]
end
end
--- Removes an item from the inventory.
-- @realm shared
-- @number id The item instance ID to remove
-- @bool[opt=false] bNoReplication Whether or not the item's removal should not be replicated
-- @bool[opt=false] bNoDelete Whether or not the item should not be fully deleted
-- @bool[opt=false] bTransferring Whether or not the item is being transferred to another inventory
-- @treturn number The X position that the item was removed from
-- @treturn number The Y position that the item was removed from
function META:Remove(id, bNoReplication, bNoDelete, bTransferring)
local x2, y2
for x = 1, self.w do
if (self.slots[x]) then
for y = 1, self.h do
local item = self.slots[x][y]
if (item and item.id == id) then
self.slots[x][y] = nil
x2 = x2 or x
y2 = y2 or y
end
end
end
end
if (SERVER and !bNoReplication) then
local receivers = self:GetReceivers()
if (istable(receivers)) then
net.Start("ixInventoryRemove")
net.WriteUInt(id, 32)
net.WriteUInt(self:GetID(), 32)
net.Send(receivers)
end
-- we aren't removing the item - we're transferring it to another inventory
if (!bTransferring) then
hook.Run("InventoryItemRemoved", self, ix.item.instances[id])
end
if (!bNoDelete) then
local item = ix.item.instances[id]
if (item and item.OnRemoved) then
item:OnRemoved()
end
local query = mysql:Delete("ix_items")
query:Where("item_id", id)
query:Execute()
ix.item.instances[id] = nil
end
end
return x2, y2
end
--- Adds a player as a receiver on this `Inventory`
-- Receivers are players who will be networked the items inside the inventory.
--
-- Calling this will *not* automatically sync it's current contents to the client.
-- All future contents will be synced, but not anything that was not synced before this is called.
--
-- This function does not check the validity of `client`, therefore if `client` doesn't exist, it will error.
-- @realm shared
-- @player client The player to add as a receiver.
function META:AddReceiver(client)
self.receivers[client] = true
end
--- The opposite of `AddReceiver`.
-- This function does not check the validity of `client`, therefore if `client` doesn't exist, it will error.
-- @realm shared
-- @player client The player to remove from the receiver list.
function META:RemoveReceiver(client)
self.receivers[client] = nil
end
--- Get all of the receivers this `Inventory` has.
-- Receivers are players who will be networked the items inside the inventory.
--
-- This function will automatically sort out invalid players for you.
-- @realm shared
-- @treturn table result The players who are on the server and allowed to see this table.
function META:GetReceivers()
local result = {}
if (self.receivers) then
for k, _ in pairs(self.receivers) do
if (IsValid(k) and k:IsPlayer()) then
result[#result + 1] = k
end
end
end
return result
end
--- Returns a count of a *specific* `Item`s in the `Inventory`
-- @realm shared
-- @string uniqueID The Unique ID of the item.
-- @bool onlyMain Whether or not to exclude bags that are present from the search.
-- @treturn number The amount of `Item`s this inventory has.
-- @usage local curHighest, winner = 0, false
-- for client, character in ix.util.GetCharacters() do
-- local itemCount = character:GetInventory():GetItemCount('water', false)
-- if itemCount > curHighest then
-- curHighest = itemCount
-- winner = character
-- end
-- end
-- -- Finds the thirstiest character on the server and returns their Character ID or false if no character has water.
function META:GetItemCount(uniqueID, onlyMain)
local i = 0
for _, v in pairs(self:GetItems(onlyMain)) do
if (v.uniqueID == uniqueID) then
i = i + 1
end
end
return i
end
--- Returns a table of all `Item`s in the `Inventory` by their Unique ID.
-- Not to be confused with `GetItemsByID` or `GetItemByID` which take in an Item Instance's ID instead.
-- @realm shared
-- @string uniqueID The Unique ID of the item.
-- @bool onlyMain Whether or not to exclude bags that are present from the search.
-- @treturn number The table of specified `Item`s this inventory has.
function META:GetItemsByUniqueID(uniqueID, onlyMain)
local items = {}
for _, v in pairs(self:GetItems(onlyMain)) do
if (v.uniqueID == uniqueID) then
items[#items + 1] = v
end
end
return items
end
--- Returns a table of `Item`s by their base.
-- @realm shared
-- @string baseID The base to search for.
-- @bool bOnlyMain Whether or not to exclude bags that are present from the search.
function META:GetItemsByBase(baseID, bOnlyMain)
local items = {}
for _, v in pairs(self:GetItems(bOnlyMain)) do
if (v.base == baseID) then
items[#items + 1] = v
end
end
return items
end
--- Get an item by it's specific Database ID.
-- @realm shared
-- @number id The ID to search for.
-- @bool onlyMain Whether or not to exclude bags that are present from the search.
-- @treturn item The item if it exists.
function META:GetItemByID(id, onlyMain)
for _, v in pairs(self:GetItems(onlyMain)) do
if (v.id == id) then
return v
end
end
end
--- Get a table of `Item`s by their specific Database ID.
-- It's important to note that while in 99% of cases,
-- items will have a unique Database ID, developers or random GMod weirdness could
-- cause a second item with the same ID to appear, even though, `ix.item.instances` will only store one of those.
-- The inventory only stores a reference to the `ix.item.instance` ID, not the memory reference itself.
-- @realm shared
-- @number id The ID to search for.
-- @bool onlyMain Whether or not to exclude bags that are present from the search.
-- @treturn item The item if it exists.
function META:GetItemsByID(id, onlyMain)
local items = {}
for _, v in pairs(self:GetItems(onlyMain)) do
if (v.id == id) then
items[#items + 1] = v
end
end
return items
end
-- This function may pretty heavy.
--- Returns a table of all the items that an `Inventory` has.
-- @realm shared
-- @bool onlyMain Whether or not to exclude bags from this search.
-- @treturn table The items this `Inventory` has.
function META:GetItems(onlyMain)
local items = {}
for _, v in pairs(self.slots) do
for _, v2 in pairs(v) do
if (istable(v2) and !items[v2.id]) then
items[v2.id] = v2
v2.data = v2.data or {}
local isBag = (((v2.base == "base_bags") or v2.isBag) and v2.data.id)
if (isBag and isBag != self:GetID() and onlyMain != true) then
local bagInv = ix.item.inventories[isBag]
if (bagInv) then
local bagItems = bagInv:GetItems()
table.Merge(items, bagItems)
end
end
end
end
end
return items
end
-- This function may pretty heavy.
--- Returns a table of all the items that an `Inventory` has.
-- @realm shared
-- @bool onlyMain Whether or not to exclude bags from this search.
-- @treturn table The items this `Inventory` has.
function META:GetBags()
local invs = {}
for _, v in pairs(self.slots) do
for _, v2 in pairs(v) do
if (istable(v2) and v2.data) then
local isBag = (((v2.base == "base_bags") or v2.isBag) and v2.data.id)
if (!table.HasValue(invs, isBag)) then
if (isBag and isBag != self:GetID()) then
invs[#invs + 1] = isBag
end
end
end
end
end
return invs
end
--- Returns the item with the given unique ID (e.g `"handheld_radio"`) if it exists in this inventory.
-- This method checks both
-- this inventory, and any bags that this inventory has inside of it.
-- @realm shared
-- @string targetID Unique ID of the item to look for
-- @tab[opt] data Item data to check for
-- @treturn[1] Item Item that belongs to this inventory with the given criteria
-- @treturn[2] bool `false` if the item does not exist
-- @see HasItems
-- @see HasItemOfBase
-- @usage local item = inventory:HasItem("handheld_radio")
--
-- if (item) then
-- -- do something with the item table
-- end
function META:HasItem(targetID, data)
local items = self:GetItems()
for _, v in pairs(items) do
if (v.uniqueID == targetID) then
if (data) then
local itemData = v.data
local bFound = true
for dataKey, dataVal in pairs(data) do
if (itemData[dataKey] != dataVal) then
bFound = false
break
end
end
if (!bFound) then
continue
end
end
return v
end
end
return false
end
--- Checks whether or not the `Inventory` has a table of items.
-- This function takes a table with **no** keys and runs in order of first item > last item,
--this is due to the usage of the `#` operator in the function.
--
-- @realm shared
-- @tab targetIDs A table of `Item` Unique ID's.
-- @treturn[1] bool true Whether or not the `Inventory` has all of the items.
-- @treturn[1] table targetIDs Your provided targetIDs table, but it will be empty.
-- @treturn[2] bool false
-- @treturn[2] table targetIDs Table consisting of the items the `Inventory` did **not** have.
-- @usage local itemFilter = {'water', 'water_sparkling'}
-- if not Entity(1):GetCharacter():GetInventory():HasItems(itemFilter) then return end
-- -- Filters out if this player has both a water, and a sparkling water.
function META:HasItems(targetIDs)
local items = self:GetItems()
local count = #targetIDs -- assuming array
targetIDs = table.Copy(targetIDs)
for _, v in pairs(items) do
for k, targetID in ipairs(targetIDs) do
if (v.uniqueID == targetID) then
table.remove(targetIDs, k)
count = count - 1
break
end
end
end
return count <= 0, targetIDs
end
--- Whether or not an `Inventory` has an item of a base, optionally with specified data.
-- This function has an optional `data` argument, which will take a `table`.
-- it will match if the data of the item is correct or not.
--
-- Items which are a base will automatically have base_ prefixed to their Unique ID, if you are having
-- trouble finding your base, that is probably why.
-- @realm shared
-- @string baseID The Item Base's Unique ID.
-- @tab[opt] data The Item's data to compare against.
-- @treturn[1] item The first `Item` of `baseID` that is found and there is no `data` argument or `data` was matched.
-- @treturn[2] false If no `Item`s of `baseID` is found or the `data` argument, if specified didn't match.
-- @usage local bHasWeaponEquipped = Entity(1):GetCharacter():GetInventory():HasItemOfBase('base_weapons', {['equip'] = true})
-- if bHasWeaponEquipped then
-- Entity(1):Notify('One gun is fun, two guns is Woo-tastic.')
-- end
-- -- Notifies the player that they should get some more guns.
function META:HasItemOfBase(baseID, data)
local items = self:GetItems()
for _, v in pairs(items) do
if (v.base == baseID) then
if (data) then
local itemData = v.data
local bFound = true
for dataKey, dataVal in pairs(data) do
if (itemData[dataKey] != dataVal) then
bFound = false
break
end
end
if (!bFound) then
continue
end
end
return v
end
end
return false
end
if (SERVER) then
--- Sends a specific slot to a character.
-- This will *not* send all of the slots of the `Item` to the character, items can occupy multiple slots.
--
-- This will call `OnSendData` on the Item using all of the `Inventory`'s receivers.
--
-- This function should *not* be used to sync an entire inventory, if you need to do that, use `AddReceiver` and `Sync`.
-- @realm server
-- @internal
-- @number x The Inventory x position to send.
-- @number y The Inventory y position to send.
-- @item[opt] item The item to send, if any.
-- @see AddReceiver
-- @see Sync
function META:SendSlot(x, y, item)
local receivers = self:GetReceivers()
local sendData = item and item.data and !table.IsEmpty(item.data) and item.data or {}
net.Start("ixInventorySet")
net.WriteUInt(self:GetID(), 32)
net.WriteUInt(x, 6)
net.WriteUInt(y, 6)
net.WriteString(item and item.uniqueID or "")
net.WriteUInt(item and item.id or 0, 32)
net.WriteUInt(self.owner or 0, 32)
net.WriteTable(sendData)
net.Send(receivers)
if (item) then
for _, v in pairs(receivers) do
item:Call("OnSendData", v)
end
end
end
--- Sets whether or not an `Inventory` should save.
-- This will prevent an `Inventory` from updating in the Database, if the inventory is already saved,
-- it will not be deleted when unloaded.
-- @realm server
-- @bool bNoSave Whether or not the Inventory should save.
function META:SetShouldSave(bNoSave)
self.noSave = bNoSave
end
--- Gets whether or not an `Inventory` should save.
-- Inventories that are marked to not save will not update in the Database, if they inventory is already saved,
-- it will not be deleted when unloaded.
-- @realm server
-- @treturn[1] bool Returns the field `noSave`.
-- @treturn[2] bool Returns true if the field `noSave` is not registered to this inventory.
function META:GetShouldSave()
return self.noSave or true
end
--- Add an item to the inventory.
-- @realm server
-- @param uniqueID The item unique ID (e.g `"handheld_radio"`) or instance ID (e.g `1024`) to add to the inventory
-- @number[opt=1] quantity The quantity of the item to add
-- @tab data Item data to add to the item
-- @number[opt=nil] x The X position for the item
-- @number[opt=nil] y The Y position for the item
-- @bool[opt=false] noReplication Whether or not the item's addition should not be replicated
-- @treturn[1] bool Whether the add was successful or not
-- @treturn[1] string The error, if applicable
-- @treturn[2] number The X position that the item was added to
-- @treturn[2] number The Y position that the item was added to
-- @treturn[2] number The inventory ID that the item was added to
function META:Add(uniqueID, quantity, data, x, y, noReplication)
quantity = quantity or 1
if (quantity < 1) then
return false, "noOwner"
end
if (!isnumber(uniqueID) and quantity > 1) then
for _ = 1, quantity do
local bSuccess, error = self:Add(uniqueID, 1, data)
if (!bSuccess) then
return false, error
end
end
return true
end
local client = self.GetOwner and self:GetOwner() or nil
local item = isnumber(uniqueID) and ix.item.instances[uniqueID] or ix.item.list[uniqueID]
local targetInv = self
local bagInv
if (!item) then
return false, "invalidItem"
end
if (isnumber(uniqueID)) then
local oldInvID = item.invID
if (!x and !y) then
x, y, bagInv = self:FindEmptySlot(item.width, item.height)
end
if (bagInv) then
targetInv = bagInv
end
-- we need to check for owner since the item instance already exists
if (!item.bAllowMultiCharacterInteraction and IsValid(client) and client:GetCharacter() and
item:GetPlayerID() == client:SteamID64() and item:GetCharacterID() != client:GetCharacter():GetID()) then
return false, "itemOwned"
end
if (hook.Run("CanTransferItem", item, ix.item.inventories[0], targetInv) == false) then
return false, "notAllowed"
end
if (x and y) then
targetInv.slots[x] = targetInv.slots[x] or {}
targetInv.slots[x][y] = true
item.gridX = x
item.gridY = y
item.invID = targetInv:GetID()
for x2 = 0, item.width - 1 do
local index = x + x2
for y2 = 0, item.height - 1 do
targetInv.slots[index] = targetInv.slots[index] or {}
targetInv.slots[index][y + y2] = item
end
end
if (!noReplication) then
targetInv:SendSlot(x, y, item)
end
if (!self.noSave) then
local query = mysql:Update("ix_items")
query:Update("inventory_id", targetInv:GetID())
query:Update("x", x)
query:Update("y", y)
query:Where("item_id", item.id)
query:Execute()
end
hook.Run("InventoryItemAdded", ix.item.inventories[oldInvID], targetInv, item)
return x, y, targetInv:GetID()
else
return false, "noFit"
end
else
if (!x and !y) then
x, y, bagInv = self:FindEmptySlot(item.width, item.height)
end
if (bagInv) then
targetInv = bagInv
end
if (hook.Run("CanTransferItem", item, ix.item.inventories[0], targetInv) == false) then
return false, "notAllowed"
end
if (x and y) then
for x2 = 0, item.width - 1 do
local index = x + x2
for y2 = 0, item.height - 1 do
targetInv.slots[index] = targetInv.slots[index] or {}
targetInv.slots[index][y + y2] = true
end
end
local characterID
local playerID
if (self.owner) then
local character = ix.char.loaded[self.owner]
if (character) then
characterID = character.id
playerID = character.steamID
end
end
ix.item.Instance(targetInv:GetID(), uniqueID, data, x, y, function(newItem)
newItem.gridX = x
newItem.gridY = y
for x2 = 0, newItem.width - 1 do
local index = x + x2
for y2 = 0, newItem.height - 1 do
targetInv.slots[index] = targetInv.slots[index] or {}
targetInv.slots[index][y + y2] = newItem
end
end
if (!noReplication) then
targetInv:SendSlot(x, y, newItem)
end
hook.Run("InventoryItemAdded", nil, targetInv, newItem)
end, characterID, playerID)
return x, y, targetInv:GetID()
else
return false, "noFit"
end
end
end
--- Syncs the `Inventory` to the receiver.
-- This will call Item.OnSendData on every item in the `Inventory`.
-- @realm server
-- @player receiver The player to
function META:Sync(receiver)
local slots = {}
for x, items in pairs(self.slots) do
for y, item in pairs(items) do
if (istable(item) and item.gridX == x and item.gridY == y) then
slots[#slots + 1] = {x, y, item.uniqueID, item.id, item.data}
end
end
end
net.Start("ixInventorySync")
net.WriteTable(slots)
net.WriteUInt(self:GetID(), 32)
net.WriteUInt(self.w, 6)
net.WriteUInt(self.h, 6)
net.WriteType(self.owner)
net.WriteTable(self.vars or {})
net.Send(receiver)
for _, v in pairs(self:GetItems()) do
v:Call("OnSendData", receiver)
end
end
end
ix.meta.inventory = META
|
require("indent_blankline").setup {
indentLine_enabled = 1,
char = "▏",
filetype_exclude = {
"startify", "dashboard", "dotooagenda", "log", "fugitive", "gitcommit",
"packer", "vimwiki", "markdown", "json", "txt", "vista", "help",
"todoist", "NvimTree", "peekaboo", "git", "TelescopePrompt", "undotree",
"flutterToolsOutline", "" -- for all buffers without a file type
},
buftype_exclude = {"terminal", "nofile"},
show_trailing_blankline_indent = false,
show_first_indent_level = true,
show_current_context = true,
char_list = {"|", "¦", "┆", "┊"},
space_char = " ",
context_patterns = {
"class", "function", "method", "block", "list_literal", "selector",
"^if", "^table", "if_statement", "while", "for"
}
}
|
--[[
GD50
Pokemon
Author: Colton Ogden
[email protected]
]]
EntityIdleState = Class{__includes = EntityBaseState}
function EntityIdleState:init(entity)
self.entity = entity
self.entity:changeAnimation('idle-' .. self.entity.direction)
end
|
-------------------------------------
-- P R E S E T S M O D U L E --
-------------------------------------
AllTheThings.Presets = {
["DEATHKNIGHT"] = {
true, -- [1]
true, -- [2]
true, -- [3]
false, -- [4]
false, -- [5]
false, -- [6]
true, -- [7]
false, -- [8]
true, -- [9]
true, -- [10]
nil, -- [11]
nil, -- [12]
nil, -- [13]
nil, -- [14]
nil, -- [15]
nil, -- [16]
nil, -- [17]
nil, -- [18]
nil, -- [19]
false, -- [20]
true, -- [21]
true, -- [22]
true, -- [23]
true, -- [24]
true, -- [25]
true, -- [26]
false, -- [27]
false, -- [28]
true, -- [29]
false, -- [30]
false, -- [31]
false, -- [32]
false, -- [33]
false, -- [34]
false, -- [35]
true, -- [36]
[103] = true,
[100] = true,
[104] = true,
[101] = true,
[105] = true,
[102] = true,
[106] = true,
[200] = true,
[51] = false,
[52] = false,
[53] = false,
[54] = false,
[55] = false,
[113] = false,
},
["DEMONHUNTER"] = {
true, -- [1]
true, -- [2]
true, -- [3]
false, -- [4]
true, -- [5]
false, -- [6]
false, -- [7]
false, -- [8]
true, -- [9]
true, -- [10]
nil, -- [11]
nil, -- [12]
nil, -- [13]
nil, -- [14]
nil, -- [15]
nil, -- [16]
nil, -- [17]
nil, -- [18]
nil, -- [19]
false, -- [20]
true, -- [21]
false, -- [22]
false, -- [23]
false, -- [24]
true, -- [25]
false, -- [26]
false, -- [27]
false, -- [28]
false, -- [29]
false, -- [30]
false, -- [31]
false, -- [32]
false, -- [33]
true, -- [34]
true, -- [35]
true, -- [36]
[103] = true,
[100] = true,
[104] = true,
[101] = true,
[105] = true,
[102] = true,
[106] = true,
[200] = true,
[51] = false,
[52] = false,
[53] = false,
[54] = false,
[55] = false,
[113] = false,
},
["DRUID"] = {
true, -- [1]
true, -- [2]
true, -- [3]
false, -- [4]
true, -- [5]
false, -- [6]
false, -- [7]
false, -- [8]
true, -- [9]
true, -- [10]
nil, -- [11]
nil, -- [12]
nil, -- [13]
nil, -- [14]
nil, -- [15]
nil, -- [16]
nil, -- [17]
nil, -- [18]
nil, -- [19]
true, -- [20]
false, -- [21]
false, -- [22]
true, -- [23]
true, -- [24]
false, -- [25]
false, -- [26]
false, -- [27]
true, -- [28]
true, -- [29]
true, -- [30]
false, -- [31]
false, -- [32]
false, -- [33]
true, -- [34]
false, -- [35]
true, -- [36]
[103] = true,
[100] = true,
[104] = true,
[101] = true,
[105] = true,
[102] = true,
[106] = true,
[200] = true,
[51] = false,
[52] = false,
[53] = false,
[54] = false,
[55] = false,
[113] = false,
},
["HUNTER"] = {
true, -- [1]
true, -- [2]
true, -- [3]
false, -- [4]
false, -- [5]
true, -- [6]
false, -- [7]
false, -- [8]
true, -- [9]
true, -- [10]
nil, -- [11]
nil, -- [12]
nil, -- [13]
nil, -- [14]
nil, -- [15]
nil, -- [16]
nil, -- [17]
nil, -- [18]
nil, -- [19]
true, -- [20]
true, -- [21]
true, -- [22]
false, -- [23]
false, -- [24]
true, -- [25]
true, -- [26]
false, -- [27]
true, -- [28]
true, -- [29]
true, -- [30]
true, -- [31]
true, -- [32]
true, -- [33]
true, -- [34]
false, -- [35]
true, -- [36]
[106] = true,
[101] = true,
[103] = true,
[105] = true,
[100] = true,
[102] = true,
[104] = true,
[200] = true,
[51] = false,
[52] = false,
[53] = false,
[54] = false,
[55] = false,
[113] = false,
},
["MAGE"] = {
true, -- [1]
true, -- [2]
true, -- [3]
true, -- [4]
false, -- [5]
false, -- [6]
false, -- [7]
false, -- [8]
true, -- [9]
true, -- [10]
nil, -- [11]
nil, -- [12]
nil, -- [13]
nil, -- [14]
nil, -- [15]
nil, -- [16]
nil, -- [17]
nil, -- [18]
nil, -- [19]
true, -- [20]
false, -- [21]
false, -- [22]
false, -- [23]
false, -- [24]
true, -- [25]
false, -- [26]
true, -- [27]
true, -- [28]
false, -- [29]
false, -- [30]
false, -- [31]
false, -- [32]
false, -- [33]
false, -- [34]
false, -- [35]
true, -- [36]
[103] = true,
[100] = true,
[104] = true,
[101] = true,
[105] = true,
[102] = true,
[106] = true,
[200] = true,
[51] = false,
[52] = false,
[53] = false,
[54] = false,
[55] = false,
[113] = false,
},
["MONK"] = {
true, -- [1]
true, -- [2]
true, -- [3]
false, -- [4]
true, -- [5]
false, -- [6]
false, -- [7]
false, -- [8]
true, -- [9]
true, -- [10]
nil, -- [11]
nil, -- [12]
nil, -- [13]
nil, -- [14]
nil, -- [15]
nil, -- [16]
nil, -- [17]
nil, -- [18]
nil, -- [19]
false, -- [20]
true, -- [21]
false, -- [22]
true, -- [23]
false, -- [24]
true, -- [25]
false, -- [26]
false, -- [27]
true, -- [28]
true, -- [29]
true, -- [30]
false, -- [31]
false, -- [32]
false, -- [33]
true, -- [34]
false, -- [35]
true, -- [36]
[103] = true,
[100] = true,
[104] = true,
[101] = true,
[105] = true,
[102] = true,
[106] = true,
[200] = true,
[51] = false,
[52] = false,
[53] = false,
[54] = false,
[55] = false,
[113] = false,
},
["PALADIN"] = {
true, -- [1]
true, -- [2]
true, -- [3]
false, -- [4]
false, -- [5]
false, -- [6]
true, -- [7]
true, -- [8]
true, -- [9]
true, -- [10]
nil, -- [11]
nil, -- [12]
nil, -- [13]
nil, -- [14]
nil, -- [15]
nil, -- [16]
nil, -- [17]
nil, -- [18]
nil, -- [19]
false, -- [20]
true, -- [21]
true, -- [22]
true, -- [23]
true, -- [24]
true, -- [25]
true, -- [26]
false, -- [27]
false, -- [28]
true, -- [29]
false, -- [30]
false, -- [31]
false, -- [32]
false, -- [33]
false, -- [34]
false, -- [35]
true, -- [36]
[103] = true,
[100] = true,
[104] = true,
[101] = true,
[105] = true,
[102] = true,
[106] = true,
[200] = true,
[51] = false,
[52] = false,
[53] = false,
[54] = false,
[55] = false,
[113] = false,
},
["PRIEST"] = {
true, -- [1]
true, -- [2]
true, -- [3]
true, -- [4]
false, -- [5]
false, -- [6]
false, -- [7]
false, -- [8]
true, -- [9]
true, -- [10]
[31] = false,
[32] = false,
[33] = false,
[34] = false,
[101] = true,
[103] = true,
[20] = true,
[21] = false,
[22] = false,
[23] = true,
[36] = true,
[24] = false,
[104] = true,
[25] = false,
[105] = true,
[26] = false,
[102] = true,
[27] = true,
[106] = true,
[28] = true,
[29] = false,
[100] = true,
[200] = true,
[51] = false,
[52] = false,
[53] = false,
[54] = false,
[55] = false,
[113] = false,
[35] = false,
},
["ROGUE"] = {
true, -- [1]
true, -- [2]
true, -- [3]
false, -- [4]
true, -- [5]
false, -- [6]
false, -- [7]
false, -- [8]
true, -- [9]
true, -- [10]
nil, -- [11]
nil, -- [12]
nil, -- [13]
nil, -- [14]
nil, -- [15]
nil, -- [16]
nil, -- [17]
nil, -- [18]
nil, -- [19]
true, -- [20]
true, -- [21]
false, -- [22]
true, -- [23]
false, -- [24]
true, -- [25]
false, -- [26]
false, -- [27]
false, -- [28]
false, -- [29]
nil, -- [30]
true, -- [31]
true, -- [32]
true, -- [33]
true, -- [34]
false, -- [35]
[103] = true,
[100] = true,
[104] = true,
[101] = true,
[105] = true,
[102] = true,
[106] = true,
[200] = true,
[51] = false,
[52] = false,
[53] = false,
[54] = false,
[55] = false,
[113] = false,
},
["SHAMAN"] = {
true, -- [1]
true, -- [2]
true, -- [3]
false, -- [4]
false, -- [5]
true, -- [6]
false, -- [7]
true, -- [8]
true, -- [9]
true, -- [10]
[31] = false,
[32] = false,
[33] = false,
[34] = true,
[101] = true,
[103] = true,
[20] = true,
[21] = true,
[22] = true,
[23] = true,
[24] = true,
[104] = true,
[25] = false,
[105] = true,
[26] = false,
[102] = true,
[27] = false,
[106] = true,
[28] = true,
[29] = false,
[100] = true,
[200] = true,
[51] = false,
[52] = false,
[53] = false,
[54] = false,
[55] = false,
[113] = false,
[35] = false,
},
["WARLOCK"] = {
true, -- [1]
true, -- [2]
true, -- [3]
true, -- [4]
false, -- [5]
false, -- [6]
false, -- [7]
false, -- [8]
true, -- [9]
true, -- [10]
[30] = false,
[31] = false,
[32] = false,
[33] = false,
[34] = false,
[35] = false,
[101] = true,
[103] = true,
[20] = true,
[21] = false,
[22] = false,
[23] = false,
[24] = false,
[25] = true,
[26] = false,
[102] = true,
[27] = true,
[28] = true,
[36] = true,
[29] = false,
[100] = true,
[200] = true,
[51] = false,
[52] = false,
[53] = false,
[54] = false,
[55] = false,
[113] = false,
},
["WARRIOR"] = {
true, -- [1]
true, -- [2]
true, -- [3]
false, -- [4]
false, -- [5]
false, -- [6]
true, -- [7]
true, -- [8]
true, -- [9]
true, -- [10]
nil, -- [11]
nil, -- [12]
nil, -- [13]
nil, -- [14]
nil, -- [15]
nil, -- [16]
nil, -- [17]
nil, -- [18]
nil, -- [19]
true, -- [20]
true, -- [21]
true, -- [22]
true, -- [23]
true, -- [24]
true, -- [25]
true, -- [26]
false, -- [27]
true, -- [28]
true, -- [29]
true, -- [30]
true, -- [31]
true, -- [32]
true, -- [33]
true, -- [34]
false, -- [35]
true, -- [36]
[103] = true,
[100] = true,
[104] = true,
[101] = true,
[105] = true,
[102] = true,
[106] = true,
[200] = true,
[51] = false,
[52] = false,
[53] = false,
[54] = false,
[55] = false,
[113] = false,
},
}
|
local clean_buffer = require('tests.helpers').clean_buffer
describe('infoview', function()
it('starts with the window position at the top', clean_buffer('',
function(context)
local cursor = vim.api.nvim_win_get_cursor(context.infoview.window)
assert.is.same(1, cursor[1])
end))
end)
|
local keys = { }
for i = 0, 113 do
keys[i] = false
end
hook.Add("Think", "dronesrewrite_cl_keys", function()
for i = 0, 113 do
local oldpressed = keys[i]
keys[i] = i >= 107 and input.IsMouseDown(i) or input.IsKeyDown(i)
if oldpressed != keys[i] then
hook.Run("DronesRewriteKey", i, keys[i])
end
end
end)
hook.Add("DronesRewriteKey", "dronesrewrite_controlkeys", function(key, pressed)
local send = pressed
if vgui.CursorVisible() and pressed then send = false end
local ply = LocalPlayer()
local drone = ply:GetNWEntity("DronesRewriteDrone")
if drone:IsValid() then
net.Start("dronesrewrite_keyvalue")
net.WriteUInt(key, 7)
net.WriteBit(send)
net.SendToServer()
DRONES_REWRITE.LogDebug(string.format("Pressing key %i %s", key, tostring(send)))
end
end)
local function setup(p)
--[[p.btns = { }
for k, bind in pairs(DRONES_REWRITE.SortedKeys) do
local text = bind .. " : " .. string.upper(input.GetKeyName(DRONES_REWRITE.ClientCVars.Keys[bind]:GetString()))
p.btns[bind] = DRONES_REWRITE.CreateButton(text, 0, 0, 150, 30, p, function()
timer.Create("dronesrewritekey", 0.1, 1, function()
p.btns[bind]:SetText("PRESS ANY BUTTON")
hook.Add("DronesRewriteKey", "dronesrewrite_controlkeysset", function(key, pressed)
RunConsoleCommand("dronesrewrite_key_" .. bind, key)
p.btns[bind]:SetText(bind .. " : " .. string.upper(input.GetKeyName(key)))
hook.Remove("DronesRewriteKey", "dronesrewrite_controlkeysset")
end)
end)
end)
p:AddItem(p.btns[bind])
end]]
local d = vgui.Create("DListView")
d:SetSize(150, 400)
d:AddColumn("Bind")
d:AddColumn("Key")
for k, v in pairs(DRONES_REWRITE.SortedKeys) do
d:AddLine(v, string.upper(input.GetKeyName(DRONES_REWRITE.ClientCVars.Keys[v]:GetString())))
end
d.OnClickLine = function(parent, line, isselected)
local bind = line:GetValue(1)
timer.Create("dronesrewritekey", 0.1, 1, function()
line:SetValue(2, "PRESS ANY BUTTON")
hook.Add("DronesRewriteKey", "dronesrewrite_controlkeysset", function(key, pressed)
RunConsoleCommand("dronesrewrite_key_" .. bind, key)
line:SetValue(2, string.upper(input.GetKeyName(key)))
hook.Remove("DronesRewriteKey", "dronesrewrite_controlkeysset")
end)
end)
end
p:AddItem(d)
local btn = DRONES_REWRITE.CreateButton("Set to default", 0, 0, 150, 30, p, function()
d:Clear()
for bind, key in pairs(DRONES_REWRITE.Keys) do
RunConsoleCommand("dronesrewrite_key_" .. bind, key)
d:AddLine(bind, string.upper(input.GetKeyName(key)))
end
end)
p:AddItem(btn)
end
hook.Add("PopulateToolMenu", "dronesrewrite_addmenukeys", function() spawnmenu.AddToolMenuOption("Options", "Drones Settings", "dronesrewrite_keys", "Controls / Keys", "", "", setup) end)
|
_G.Connection = {}
local Files = ResourceHelper.GetJson("sugar", "data/sugar/binary/" .. string.lower(RuntimeOS) .. ".json")
local Request = require("coro-http").request
local Sha1 = require("sha1")
function DownloadFile(File)
Logger:Info("Downloading " .. File.Name)
local Success, Reponse, Body = pcall(Request, "GET", File.Url)
if not Success then
Logger:Warn("Error while downloading file " .. File.Name)
Logger:Warn(Reponse)
Logger:Warn("Retrying in 10 seconds")
Wait(10)
Logger:Warn("Retrying")
return DownloadFile(File)
end
FS.writeFileSync("./Binary/" .. File.Name, Body)
if File.chmod then
os.execute("chmod +x ./Binary/" .. File.Name)
end
if File.Hash ~= nil then
if File.Hash ~= Sha1(FS.readFileSync("./Binary/" .. File.Name)) then
FS.unlinkSync("./Binary/" .. File.Name)
Logger:Warn("Hashes do not match")
Logger:Warn("Downloading again")
return DownloadFile(File)
else
Logger:Info("Hashes match!")
end
end
Logger:Info("Download complete!")
end
FS.mkdirSync("./Binary/")
for Index, File in pairs(Files) do
local Exists = FS.existsSync("./Binary/" .. File.Name)
if not Exists then
DownloadFile(File)
end
end
Logger:Info(Import("ga.corebyte.Sugar.Helpers.Wifi").GetWifi())
|
RegisterNetEvent('BanSql:Respond')
AddEventHandler('BanSql:Respond', function()
TriggerServerEvent("BanSql:CheckMe")
end)
|
--[[
Made by Shadi432 :)
]]--
local discordia = require("discordia")
local client = discordia.Client()
local token = "CensoredToken"
-- Do not change above this line
-- Underscore
local US_References = {"US", "USA", "America", "Freedom", "Eagle", "Q","Texas","South","Alabama", "Bama","Free","Trump","Wall","Antifa","Antifer"}
local Version = 0.45
local versFile = io.open("version.txt","r")
io.input(versFile)
if versFile then -- For allowing a version update to be posted to connected servers by just changing the Version constant above.
local lastVers = io.read():sub(10)
io.close()
if tonumber(lastVers) < Version then
local updateVers = io.open("version.txt","w")
io.output(updateVers)
io.write("Version: " .. Version)
io.close()
client:on("guildAvailable", function(guild) -- Will allow it to send to every guild chadbot is connected to.
guild.systemChannel:send("I have been updated to Version: " .. Version)
end)
end
else
local newFile = io.open("version.txt","w")
io.output(newFile)
io.write("Version: " .. Version)
io.close()
end
local function getEmojiId(guild, emojiName) -- guild that the message was sent from, emojiName with right capitalisation and no colons e.g. KKonaW not kkonaw or :KKonaW:
return(
guild.emojis:find( function(emoji)
if emoji.name == emojiName then
return emoji
end
end)) -- Returns a table with details of the emoji such as guild sent in and the emoji Name and Id 4 is the index for emoji Id. Returns nil if emoji not in guild
end
local function splitString(str,sep) -- Split the string into individual words based on a defined separator, ignore punctuation. Useful because you don't want to pattern match several characters that can mean a lot on their own or be used within other words
local fields = {}
str:gsub("([^%p" .. sep .. "]+)", function(c)
table.insert(fields,c)
end)
return fields
end
client:on("ready", function()
splitString("Hello, world!! Test!!"," ")
end)
client:on("messageCreate", function(message)
local messageUnits = splitString(message.content," ")
if message.content:match("United States") then
message.channel:send("<:KKonaW:" .. getEmojiId(message.guild,"KKonaW")[4] .. ">")
elseif message.content:lower():match("research q") then
message.channel:send("https://media.giphy.com/media/pWeLDLEd0PmlXqtSyQ/giphy.gif")
elseif message.content:lower():match("ddd") or message.content:lower():match("dedede") then
message:delete()
elseif message.content == "https://tenor.com/view/eh-hey-marmot-squirrel-calling-out-gif-16861592" then
message.channel:send{
content = "....",
file = "images/FeelsWeirdMan.jpg"
}
elseif message.content == "!shutdown" and message.author.tag == "Shadi432#1826" then
client:stop()
else
for messageNum,messageContent in pairs(messageUnits) do
if messageContent == "Q" or messageContent:upper() == "QANON"then
local emoji = getEmojiId(message.guild,"OOOOO")
if emoji then
for i=1, 5 do
message.channel:send("<:OOOOO:" .. emoji[4] .. ">")
end
break
else
break
end
end
for index, usRef in pairs(US_References) do
if messageContent == usRef then
message.channel:send("<:KKonaW:" .. getEmojiId(message.guild,"KKonaW")[4] .. ">")
end
end
end
end
--[[
for index,usRef in pairs (usReferences) do
if message.content:match(usRef) and (message.content == "Q" or message.content == "Q Anon") then
elseif message.content:match(usRef) then
end
end
]]--
end)
client:run("Bot " .. token)
|
local PluginRoot = script:FindFirstAncestor("PluginRoot")
local load = require(PluginRoot.Loader).load
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Roact = load("Roact")
local Maid = load("Maid")
local Oyrc = load("Oyrc")
local e = Roact.createElement
local ModalTargetContext = Roact.createContext()
local ModalTargetController = Roact.Component:extend("ModalTargetController")
function ModalTargetController:init()
local modalTarget = self.props.modalTarget
self.state = {
modalTarget = modalTarget,
}
local layerCollector = modalTarget:IsA("LayerCollector") and modalTarget
or modalTarget:FindFirstAncestorWhichIsA("LayerCollector")
local getMousePosition
if layerCollector then
if layerCollector:IsA("PluginGui") then
getMousePosition = function()
return layerCollector:GetRelativeMousePosition()
end
elseif layerCollector:IsA("ScreenGui") then
getMousePosition = function()
return UserInputService:GetMouseLocation()
end
else
error("ModalTarget only supported for GUI parented under PluginGui or ScreenGui.")
end
else
error("ModalTarget must be parented under PluginGui or ScreenGui.")
end
self.absoluteSize, self.updateAbsoluteSize = Roact.createBinding(modalTarget.AbsoluteSize)
self.absolutePosition, self.updateAbsolutePosition = Roact.createBinding(modalTarget.AbsolutePosition)
self.mousePosition, self.updateMousePosition = Roact.createBinding(getMousePosition())
self.absoluteSizeChangedEvent = Instance.new("BindableEvent")
self.absolutePositionChangedEvent = Instance.new("BindableEvent")
self.mousePositionChangedEvent = Instance.new("BindableEvent")
self.maid = Maid.new()
self.maid:GiveTask(self.state.modalTarget:GetPropertyChangedSignal("AbsoluteSize"):Connect(function()
self.updateAbsoluteSize(modalTarget.AbsoluteSize)
self.absoluteSizeChangedEvent:Fire(modalTarget.AbsoluteSize)
end))
self.maid:GiveTask(self.state.modalTarget:GetPropertyChangedSignal("AbsolutePosition"):Connect(function()
self.updateAbsolutePosition(modalTarget.AbsolutePosition)
self.absolutePositionChangedEvent:Fire(modalTarget.AbsolutePosition)
end))
self.maid:GiveTask(RunService.RenderStepped:Connect(function()
local mousePosition = getMousePosition()
if mousePosition ~= self.mousePosition:getValue() then
self.updateMousePosition(mousePosition)
self.mousePositionChangedEvent:Fire(mousePosition)
end
end))
self.subscribeToAbsolutePositionChanged = function(callback)
local conn = self.absolutePositionChangedEvent.Event:Connect(callback)
return function()
conn:Disconnect()
end
end
self.subscribeToAbsolutePositionChanged = function(callback)
local conn = self.absolutePositionChangedEvent.Event:Connect(callback)
return function()
conn:Disconnect()
end
end
self.subscribeToMousePositionChanged = function(callback)
local conn = self.mousePositionChangedEvent.Event:Connect(callback)
return function()
conn:Disconnect()
end
end
end
function ModalTargetController:render()
return e(ModalTargetContext.Provider, {
value = {
target = self.state.modalTarget,
absolutePositionBinding = self.absolutePosition,
absoluteSizeBinding = self.absoluteSize,
mousePositionBinding = self.mousePosition,
subscribeToAbsolutePositionChanged = self.subscribeToAbsolutePositionChanged,
subscribeToAbsoluteSizeChanged = self.subscribeToAbsoluteSizeChanged,
subscribeToMousePositionChanged = self.subscribeToMousePositionChanged,
},
}, self.props[Roact.Children])
end
function ModalTargetController:willUnmount()
self.maid:Destroy()
end
local function withController(props, children)
return e(ModalTargetController, props, children)
end
local function withConsumer(render)
return e(ModalTargetContext.Consumer, {
render = function(theme)
return render(theme)
end
})
end
local function connect(component, mapValueToProps)
local newComponent = Roact.PureComponent:extend("ModalTargetContextConnected" .. tostring(component))
function newComponent:render()
return withConsumer(function(theme)
local props = self.props
props = Oyrc.Dictionary.join(props, mapValueToProps(theme))
return e(component, props)
end)
end
return newComponent
end
return {
withController = withController,
withConsumer = withConsumer,
connect = connect,
}
|
---Split string into array
---@param str string
---@param delim string
---@return table
function Split(input, delimiter)
if (delimiter=='') then return false end
local pos,arr = 0, {}
for st,sp in function() return string.find(input, delimiter, pos, true) end do
table.insert(arr, string.sub(input, pos, st - 1))
pos = sp + 1
end
table.insert(arr, string.sub(input, pos))
return arr
end
function Serialize(obj)
local lua = ""
local t = type(obj)
if t == "number" then
lua = lua .. obj
elseif t == "boolean" then
lua = lua .. tostring(obj)
elseif t == "string" then
lua = lua .. string.format("%q", obj)
elseif t == "table" then
lua = lua .. "{\n"
for k, v in pairs(obj) do
lua = lua .. "[" .. Serialize(k) .. "]=" .. Serialize(v) .. ",\n"
end
local metatable = getmetatable(obj)
if metatable ~= nil and type(metatable.__index) == "table" then
for k, v in pairs(metatable.__index) do
lua = lua .. "[" .. Serialize(k) .. "]=" .. Serialize(v) .. ",\n"
end
end
lua = lua .. "}"
elseif t == "nil" then
return nil
else
error("can not serialize a " .. t .. " type.")
end
return lua
end
function Unserialize(lua)
local t = type(lua)
if t == "nil" or lua == "" then
return nil
elseif t == "number" or t == "string" or t == "boolean" then
lua = tostring(lua)
else
error("can not unserialize a " .. t .. " type.")
end
lua = "return " .. lua
local func = loadstring(lua)
if func == nil then
return nil
end
return func()
end
|
return function(proxy)
return
{
httpEnabled = {proxy.isHttpEnabled()},
tcpEnabled = {proxy.isTcpEnabled()},
}
end
|
add_rules("mode.debug", "mode.release")
add_requires("libomp", {optional = true})
target("Wallpaper")
add_rules("qt.widgetapp")
add_rules("qt.quickapp")
add_includedirs(".")
add_headerfiles("utils.h","wallpaper.h")
add_files("*.cpp")
add_files("wallpaper.h")
add_files("wallpaper.ui")
add_files("icon.rc","icon.qrc")
-- openmp
add_rules("c++.openmp")
add_packages("libomp")
if is_plat("macosx") then
add_frameworks("Foundation", "CoreFoundation", "CoreGraphics", "AppKit", "OpenCL")
elseif is_plat("linux") then
add_syslinks("pthread", "dl")
elseif is_plat("windows") then
add_syslinks("user32", "mfplat", "mfuuid","Ws2_32", "Secur32", "Bcrypt")
end
-- Qt framework
add_frameworks("QtCore","QtGui","QtWebEngineWidgets")
|
function love.conf(t)
t.version = "0.10.2"
t.console = true
t.window.title = "Console Test"
t.window.width = 1600
t.window.height = 900
t.window.resizable = true
end
|
local typedFunction = require(game:GetService("ReplicatedStorage"):WaitForChild("typedFunction"))
return typedFunction({
"any",
"string",
"Scene"
}, function(_, id, scene)
for _, entity in pairs(scene.entities) do
if entity.core.id == id then
return entity
end
end
end)
|
-- modified from https://github.com/abzcoding/lvim/blob/main/lua/user/builtin.lua
local M = {}
M.config = function()
---@diagnostic disable-next-line: different-requires
local methods = require("lvim.core.cmp").methods
local status_cmp_ok, cmp = pcall(require, "cmp")
if not status_cmp_ok then
return
end
local status_luasnip_ok, luasnip = pcall(require, "luasnip")
if not status_luasnip_ok then
return
end
vim.g.copilot_no_tab_map = true
vim.g.copilot_assume_mapped = true
vim.g.copilot_tab_fallback = ""
lvim.builtin.cmp.mapping["<Tab>"] = cmp.mapping(function(fallback)
local copilot_keys = vim.fn["copilot#Accept"]()
if cmp.visible() then
cmp.select_next_item()
elseif luasnip.expandable() then
luasnip.expand()
elseif methods.jumpable() then
luasnip.jump(1)
elseif methods.is_emmet_active() then
return vim.fn["cmp#complete"]()
elseif copilot_keys ~= "" then -- prioritise copilot over snippets
-- Copilot keys do not need to be wrapped in termcodes
vim.api.nvim_feedkeys(copilot_keys, "i", true)
elseif methods.check_backspace() then
fallback()
else
methods.feedkeys("<Plug>(Tabout)", "")
end
end, { "i", "s" })
---@diagnostic disable-next-line: unused-local
lvim.builtin.cmp.mapping["<S-Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_prev_item()
elseif methods.jumpable(-1) then
luasnip.jump(-1)
else
local copilot_keys = vim.fn["copilot#Accept"]()
if copilot_keys ~= "" then
methods.feedkeys(copilot_keys, "i")
else
methods.feedkeys("<Plug>(Tabout)", "")
end
end
end, { "i", "s" })
end
return M
|
--[[
[WIP]
Currently, I don't recommend to use it. Mostly, it doesn't work yet or even messy.
]]
return {
-- Rounds
on_round_end = script.generate_event_name(),
on_round_start = script.generate_event_name(),
-- Teams
on_team_lost = script.generate_event_name(), -- {force}
on_team_won = script.generate_event_name(), -- {force}
on_player_joined_team = script.generate_event_name(), -- {player_index, force}
on_new_team = script.generate_event_name(), -- {force}
on_pre_deleted_team = script.generate_event_name(), -- {force}
on_team_invited = script.generate_event_name(), -- {player_index, force}
on_player_accepted_invite = script.generate_event_name(), -- {player_index, force}
-- Called when a force surrendered.
-- Contains:
-- force :: LuaForce: The force to be surrender
-- destination :: LuaForce (optional): The force to reassign entities to.
on_surrender = script.generate_event_name(),
-- Called when someone/something was kicked from a team.
-- Contains:
-- player_index :: uint: The kicked player.
-- force :: LuaForce: previous force
-- kicker :: uint or nil: A player/server/script who kicked the player.
on_player_kicked_from_team = script.generate_event_name(),
-- Money
on_transfered_player_money = script.generate_event_name(), -- {receiver_index = player.index, payer_index = player.index}
on_transfered_force_money = script.generate_event_name(), -- {receiver = force, payer = force}
-- Spawn
on_new_global_spawn = script.generate_event_name(), -- {position, id = spawn_id}
on_new_player_spawn = script.generate_event_name(), -- {position, id = spawn_id}
on_new_force_spawn = script.generate_event_name(), -- {position, id = spawn_id}
on_deleted_global_spawn = script.generate_event_name(), -- {position, id = spawn_id}
on_deleted_player_spawn = script.generate_event_name(), -- {position, id = spawn_id}
on_deleted_force_spawn = script.generate_event_name(), -- {position, id = spawn_id}
-- Diplomacy
-- Called when someone/something changed a diplomacy relationship to ally/neutral/enemy.
-- Contains:
-- source :: LuaForce: The force that changed current diplomacy relationship.
-- destination :: LuaForce: The force which have to accept new diplomacy relationship.
-- player_index :: uint (optional): The player who cause the changing.
-- prev_relationship :: string: Previous relationship between forces.
on_ally = script.generate_event_name(),
on_neutral = script.generate_event_name(),
on_enemy = script.generate_event_name(),
-- Chat
-- (Propably, it'll be changed)
-- Called when a player successfully send a message.
-- Contains:
-- player_index :: uint: The index of the player who did the change.
-- message :: string: The chat message.
-- chat_name :: string: name of chat.
on_send_message = script.generate_event_name(),
-- Called when a player successfully poke another player.
-- Contains:
-- sender_index :: uint: The index of the player who did the poke.
-- target_index :: uint: The index of the player who receive the poke.
on_poke = script.generate_event_name(),
-- General
on_reload_scenario = script.generate_event_name(),
on_new_character = script.generate_event_name(), -- {player_index}
on_player_on_admin_surface = script.generate_event_name(), -- {player_index}
on_player_on_scenario_surface = script.generate_event_name(), -- {player_index}
on_player_on_lobby_surface = script.generate_event_name(), -- {player_index}
-- Called when switched a mod
-- Contains:
-- mod_name :: string
-- state :: boolean
on_toggle = script.generate_event_name(),
}
|
---@class CS.FairyEditor.AutoSizeConst
---@field public NONE string
---@field public HEIGHT string
---@field public BOTH string
---@field public SHRINK string
---@type CS.FairyEditor.AutoSizeConst
CS.FairyEditor.AutoSizeConst = { }
---@return number
---@param str string
function CS.FairyEditor.AutoSizeConst.Parse(str) end
---@return string
---@param t number
function CS.FairyEditor.AutoSizeConst.ToString(t) end
return CS.FairyEditor.AutoSizeConst
|
-- Items system
enumerate 'ITEM_TEMPLATE ITEM_INVALID'
|
if !DOME_ENT then
DOME_ENT = {}
end
DOME_ENT.block_panel = {}
DOME_ENT.block_panel.GUI_TEXTS = {
LabelText = {"Pushes the player or the prop out of zone.",
"Damages the player in the zone, also dissolves the props in it.",
"Just dissolves everything in the zone."},
PreventModes = {"Push","Damage the player, dissolve the prop","Dissolve everything"}
}
function DOME_ENT.block_panel:Init()
self.preventcbx = vgui.Create("DComboBox",self)
self.preventcbx:SetSortItems(false)
for K,V in pairs(DOME_ENT.block_panel.GUI_TEXTS.PreventModes) do
self.preventcbx:AddChoice(V,K)
end
self.modelbl = vgui.Create("DLabel",self)
self.modelbl:SetText("")
self.preventcbx.OnSelect = function(panel,index,value,data)
self:SetPreventMode(data)
end
end
function DOME_ENT.block_panel:SetPreventMode(mode)
if not isnumber(mode) then error("Expected number, got "..type(mode)) end
if mode<1 or mode>4 then error("Mode must be in range 1..3") end
if self.Block_Data and mode != self.Block_Data.preventMode then
self.Block_Data.preventMode = mode
self.modelbl:SetText(DOME_ENT.block_panel.GUI_TEXTS.LabelText[mode])
self.preventcbx:ChooseOptionID(mode)
end
end
function DOME_ENT.block_panel:SetData(data)
self.Block_Data = data
self.modelbl:SetText(DOME_ENT.block_panel.GUI_TEXTS.LabelText[data.preventMode])
self.preventcbx:ChooseOptionID(data.preventMode)
end
function DOME_ENT.block_panel:PerformLayout()
local w,h = self:GetSize()
self.preventcbx:SetPos(w*0.05,h*0.1)
self.preventcbx:SetWidth(w*0.85)
local cbxw,cbxh = self.preventcbx:GetSize()
self.modelbl:SetPos(w*0.05,h*0.15+cbxh)
self.modelbl:SetSize(w*0.85,h * 0.8 - cbxh)
end
vgui.Register("DDomeManager_blockPanel",DOME_ENT.block_panel,"Panel")
|
local function extract_path(require_path)
return require_path:match("@(.*[/\\])") or './'
end
local previous_path = package.path
local previous_cache = {}
for k, v in pairs(package.loaded) do
previous_cache[k] = v
package.loaded[k] = nil
end
local my_path = extract_path(debug.getinfo(1).source)
package.path = my_path .. '/src/?.lua;' .. package.path
local switch = require 'switch'
for k in pairs(package.loaded) do
package.loaded[k] = nil
end
for k, v in pairs(previous_cache) do
package.loaded[k] = v
end
package.path = previous_path
return switch
|
local cwtest = require "cwtest"
local ltn12 = require "ltn12"
local http_digest = require "http-digest"
local copas = require "copas"
local pretty = require "pl.pretty"
local json_decode
do -- Find a JSON parser
local ok, json = pcall(require, "cjson")
if not ok then ok, json = pcall(require, "json") end
json_decode = json.decode
assert(ok and json_decode, "no JSON parser found :(")
end
local T = cwtest.new()
local b, c, _
local url = "http://user:[email protected]/digest-auth/auth/user/passwd"
local badurl = "http://user:[email protected]/digest-auth/auth/user/passwd"
local aggr = true
local N = 10
if aggr == true then
T:start("Test started")
end
local debug = false
local function dprint(fmt, ...)
if debug == true then
print(">> "..string.format(fmt, ...))
end
end
----------------------------------------------------------------------
-- simple interface
if aggr == false then
T:start("simple interface")
end
http_digest.request(url,
function(b, c, h, opaque)
dprint("body=%s status=%d header=%s", b, c, pretty.write(h,""))
T:eq( c, 200 )
T:eq( json_decode(b), {authenticated = true, user = "user"} )
T:eq( opaque, "test 0")
end,
"test 0"
)
if aggr == false then
repeat
copas.step()
until copas.finished() == true
T:done()
end
----------------------------------------------------------------------
-- simple interface -- bad url
if aggr == false then
T:start("simple interface - bad url")
end
http_digest.request(badurl,
function(b, c, h, opaque)
dprint("body=%s status=%d header=%s", b, c, pretty.write(h,""))
T:eq( c, 401 )
T:eq( opaque, "test 1")
end,
"test 1"
)
if aggr == false then
repeat
copas.step()
until copas.finished() == true
T:done()
end
----------------------------------------------------------------------
-- generic interface -- asynchronous request possible
if aggr == false then
T:start("generic interface - asynchronous")
end
b1 = {}
http_digest.request {
url = url,
opaque = "test 2",
sink = ltn12.sink.table(b1),
handler = function(_b, c, h, opaque)
dprint("body=%s status=%d header=%s", _b, c, pretty.write(h,""))
T:eq( c, 200 )
local b = table.concat(b1)
T:eq( json_decode(b), {authenticated = true, user = "user"} )
T:eq( opaque, "test 2")
end
}
if aggr == false then
repeat
copas.step()
until copas.finished() == true
T:done()
end
----------------------------------------------------------------------
-- generic interface - asynchronous - bad url
if aggr == false then
T:start("generic interface - asynchronous - bad url")
end
http_digest.request({
url = badurl,
opaque = "test 3",
handler = function(_b, c, h, opaque)
dprint("body=%s status=%d header=%s", _b, c, pretty.write(h,""))
T:eq(c, 401)
T:eq(opaque, "test 3")
end
})
if aggr == false then
repeat
copas.step()
until copas.finished() == true
T:done()
end
----------------------------------------------------------------------
-- with ltn12 source
if aggr == false then
T:start("generic interface - asynchronous - with ltn source")
end
b2 = {}
http_digest.request {
url = url,
sink = ltn12.sink.table(b2),
source = ltn12.source.string("test"),
headers = {["content-length"] = 4}, -- 0 would work too
opaque = "test 4",
handler = function(_b, c, h, opaque)
dprint("body=%s status=%d header=%s", _b, c, pretty.write(h,""))
T:eq( c, 200 )
local b = table.concat(b2)
T:eq( json_decode(b), {authenticated = true, user = "user"} )
T:eq( opaque, "test 4")
end
}
repeat
copas.step()
until copas.finished() == true
if aggr == false then
T:done()
end
----------------------------------------------------------------------
-- simple interface
if aggr == false then
T:start("simple interface - request_async - no handler")
end
local function task1(instance)
dprint("task1-inst%d started", instance)
local b, c, h = http_digest.request(url, true)
dprint("task1-inst%d: body=%s status=%d header=%s", instance, b, c, pretty.write(h,""))
T:eq( c, 200 )
T:eq( json_decode(b), {authenticated = true, user = "user"} )
end
for i = 1, N do
copas.addthread(task1, i)
end
if aggr == false then
repeat
copas.step()
until copas.finished() == true
T:done()
end
----------------------------------------------------------------------
-- simple interface
if aggr == false then
T:start("generic interface - request_async - no handler")
end
local function task2(instance)
dprint("task2-inst%d started", instance)
local b1 = {}
local b, c, h = http_digest.request {
url = url,
sink = ltn12.sink.table(b1),
handler = true,
}
dprint("task2-inst%d: body=%s status=%d header=%s", instance, b, c, pretty.write(h,""))
T:eq( c, 200 )
T:eq( json_decode(table.concat(b1)), {authenticated = true, user = "user"} )
end
for i = 1, N do
copas.addthread(task2, i)
end
repeat
copas.step()
until copas.finished() == true
T:done()
|
local awestore = require("awestore")
local num_assertions_passed = 0
local test = (function(name, fn)
num_assertions_passed = 0
print("\x1b[1;38;5;2m Testing \x1b[0m"..name.."...")
local results = { pcall(fn) }
local ok = table.remove(results, 1)
if not ok then
print("\x1b[1A\r\x1b[K\x1b[1;38;5;1m Failed \x1b[0m"..name.." ( "..tostring(num_assertions_passed).." assertions passed )")
for _, value in ipairs(results) do print(value) end
else
print("\x1b[1A\r\x1b[K\x1b[1;38;5;2m Passed \x1b[0m"..name.." ( "..tostring(num_assertions_passed).." assertions passed )")
end
end)
local function assert_eq(a, b)
if a ~= b then
error("Assertion failed: "..tostring(a).." != "..tostring(b).."\n"..debug.traceback())
else
num_assertions_passed = num_assertions_passed + 1
end
end
test("writable", function()
local i = 0
local store = awestore.writable(0)
assert_eq(i, 0)
store:subscribe(function(_) i = i + 1 end)
assert_eq(i, 1)
store:set(1)
assert_eq(i, 2)
local got
store:subscribe(function(v) got = v; end)
assert_eq(i, 2)
assert_eq(got, 1)
store:set(2)
assert_eq(i, 3)
assert_eq(got, 2)
assert_eq(got, store:get())
store:set(store:get() + 1)
assert_eq(got, 3)
assert_eq(got, store:get())
store:update(function(v) return v + 1; end)
assert_eq(got, 4)
end)
-- readable is tested by testing derived, monitored, tweened, etc
test("readable", function()
assert_eq()
end)
test("derived", function()
local store = awestore.writable(0)
local derive = store:derive(function(v) return v ^ v end)
local got
derive:subscribe(function(v) got = v end)
assert_eq(got, 1)
store:set(1)
assert_eq(got, 1)
store:set(2)
assert_eq(got, 4)
store:set(3)
assert_eq(got, 27)
end)
test("monitored", function()
local store = awestore.writable(0)
local monitor = store:monitor()
local got
monitor:subscribe(function(v) got = v end)
assert_eq(got, 0)
store:set(1)
assert_eq(got, 1)
store:set(2)
assert_eq(got, 2)
store:set(3)
assert_eq(got, 3)
end)
os.exit()
|
------------------------------------------------------------------------------
-- init.lua
------------------------------------------------------------------------------
-- By: Andy Williams / hammerspoon [ at ] nonissue dot org
------------------------------------------------------------------------------
-- A hammerspoon config
-- If you have concerns (about my sanity or anything else) feel free to
-- email me at the above address
------------------------------------------------------------------------------
package.path = package.path .. ";_lib/?.lua"
package.path = hs.configdir .. "/_Spoons/?.spoon/init.lua;" .. package.path
package.path = package.path .. ";_scratch/?.lua"
local styles = require("styles")
local utils = require("utilities")
better_alerts = require("better-alerts")
-- better_alerts:alert1()
local hs_reload = require("hammerspoon_config_reload")
hs_reload.init()
require("console")
-- bind our alert style to default alert style
for k, v in pairs(styles.alert_default) do
hs.alert.defaultStyle[k] = v
end
-- can't remember if/what depends on this
if not hs.ipc.cliStatus() then
local cliInstallResult = hs.ipc.cliInstall()
if cliInstallResult then
require("hs.ipc")
else
hs.alert("hs.ipc error!")
end
else
hs.ipc.cliSaveHistory(true)
require("hs.ipc")
end
-- sane defaults
hs.logger.defaultLogLevel = "debug"
require("hs.hotkey").setLogLevel("warning")
hs.window.animationDuration = 0
i = hs.inspect
fw = hs.window.focusedWindow
bind = hs.hotkey.bind
clear = hs.console.clearConsole
reload = hs.reload
pbcopy = hs.pasteboard.setContents
print_t = utils.print_r
print_r = utils.print_r
hostname = hs.host.localizedName()
local mash = {"cmd", "alt", "ctrl"}
------------------------------------------------------------------------------
-- START OF SPOONS --
------------------------------------------------------------------------------
-- ControlEscape.spoon / https://github.com/jasonrudolph/ControlEscape.spoon
------------------------------------------------------------------------------
-- I wanted this to resolve my issues with my locking capslock key on my
-- AEKII m3501, but I don't think it does
-- It does replace Karabiner Elements for me though, which is nice!
-- EDIT: maybe check this
-- https://gist.github.com/zcmarine/f65182fe26b029900792fa0b59f09d7f
------------------------------------------------------------------------------
hs.loadSpoon("CTRLESC"):start()
------------------------------------------------------------------------------
-- Context.spoon / by me
------------------------------------------------------------------------------
-- Watches for wifi ssid changes + screen resolution changes
-- If changes are detected and match a series of rules
-- Systemwide settings are configured
-- For example:
-- * On wifi ssid change, if isn't one of our home networks
-- system is muted and screenlock is set to a short time
--
-- PARAMS:
-- [Optional] Accepts a boolean which dictates whether the menubar item is shown
-- Defaults to false if nothing is passed
------------------------------------------------------------------------------
local drives = {"ExternalSSD", "Win-Stuff", "Photos"}
local display_ids = {mbp = 2077750265, cinema = 69489832, sidecar = 4128829}
hs.settings.set("homeSSIDs", {"BROMEGA", "ComfortInn VIP", "BROMEGA-5", "1614 Apple II", "RamadaGuest", "RamadaVIP"})
hs.settings.set("context.drives", drives)
hs.settings.set("context.display_ids", display_ids)
hs.loadSpoon("Context"):start({showMenu = true, display_ids = display_ids, drives = drives})
------------------------------------------------------------------------------
-- SafariKeys.spoon / by me
------------------------------------------------------------------------------
hs.loadSpoon("SafariKeys")
spoon.SafariKeys:bindHotkeys(spoon.SafariKeys.defaultHotkeys)
------------------------------------------------------------------------------
-- PaywallBuster.spoon / by me
------------------------------------------------------------------------------
-- Ultimately this probably isn't necessary, but I do occasionally use it
------------------------------------------------------------------------------
-- TODO: bind default hotkey in spoon
-- hs.loadSpoon("PaywallBuster")
-- hs.hotkey.bind(
-- mash,
-- "B",
-- function()
-- spoon.PaywallBuster:show()
-- end
-- )
------------------------------------------------------------------------------
-- Zzz.spoon / by me
------------------------------------------------------------------------------
-- Sleep timer, puts computer to sleep after an interval
-- Shows a countdown in the menubar
-- Can be triggered from menubar
-- Menubar also provides snooze/shorten functions
-- There is also a modal to let users enter custom times
------------------------------------------------------------------------------
hs.loadSpoon("Zzz")
spoon.Zzz:bindHotkeys(spoon.Zzz.defaultHotkeys)
------------------------------------------------------------------------------
-- EasyTOTP.spoon / by me
------------------------------------------------------------------------------
-- Get current TOTP token, copy to clipboard and type in frontmost window
------------------------------------------------------------------------------
hs.loadSpoon("EasyTOTP")
------------------------------------------------------------------------------
-- Resolute.spoon / by me
------------------------------------------------------------------------------
-- Menubar item + modal for quickly changing display resolution
-- Currently, you have to specify the choices manually
-- May change that in future
------------------------------------------------------------------------------
hs.loadSpoon("Resolute")
spoon.Resolute:bindHotkeys(spoon.Resolute.defaultHotkeys)
------------------------------------------------------------------------------
-- Fenestra.spoon / by me
------------------------------------------------------------------------------
-- My window management stuff
-- Resize active windows, move stuff between monitors, etc
------------------------------------------------------------------------------
hs.loadSpoon("Fenestra")
spoon.Fenestra:bindHotkeys(spoon.Fenestra.defaultHotkeys)
------------------------------------------------------------------------------
-- Clippy.spoon / by me
------------------------------------------------------------------------------
-- Copy screenshot to clipboard and save to disk
------------------------------------------------------------------------------
hs.loadSpoon("Clippy"):start()
------------------------------------------------------------------------------
-- END OF SPOONS --
------------------------------------------------------------------------------
TextInflator = require("TextInflator")
TextInflator:init()
-- hs.loadSpoon("KSheet"):init()
-- KSheetDefaultHotkeys = {
-- toggle = {{"ctrl", "alt", "cmd"}, "K"}
-- }
-- spoon.KSheet:bindHotkeys(KSheetDefaultHotkeys)
|
object_mobile_space_comm_rian_ry = object_mobile_shared_space_comm_rian_ry:new {
}
ObjectTemplates:addTemplate(object_mobile_space_comm_rian_ry, "object/mobile/space_comm_rian_ry.iff")
|
-- $Id: SimpleParticles2.lua 3171 2008-11-06 09:06:29Z det $
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
local SimpleParticles2 = {}
SimpleParticles2.__index = SimpleParticles2
local billShader
local colormapUniform = {}
local lastTexture = ""
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function SimpleParticles2.GetInfo()
return {
name = "SimpleParticles2",
backup = "", --// backup class, if this class doesn't work (old cards,ati's,etc.)
desc = "This is a simialr class to SimpleParticles, just that it is 100% implemented with shaders, todo so it miss the Airdrag tags and added new Exp tags.",
layer = 0, --// extreme simply z-ordering :x
--// gfx requirement
fbo = false,
shader = true,
rtt = false,
ctt = false,
}
end
SimpleParticles2.Default = {
emitVector = {0,1,0},
pos = {0,0,0}, --// start pos
partpos = "0,0,0", --// particle relative start pos (can contain lua code!)
layer = 0,
--// visibility check
los = true,
airLos = true,
radar = false,
count = 1,
force = {0,0,0}, --// global effect force
forceExp = 1,
speed = 0,
speedSpread = 0,
speedExp = 1, --// >1 : first decrease slow, then fast; <1 : decrease fast, then slow
life = 0,
lifeSpread = 0,
delaySpread = 0,
rotSpeed = 0,
rotSpeedSpread = 0,
rotSpread = 0,
rotExp = 1, --// >1 : first decrease slow, then fast; <1 : decrease fast, then slow; <0 : invert x-axis (start large become smaller)
emitRot = 0,
emitRotSpread = 0,
size = 0,
sizeSpread = 0,
sizeGrowth = 0,
sizeExp = 1, --// >1 : first decrease slow, then fast; <1 : decrease fast, then slow; <0 : invert x-axis (start large become smaller)
colormap = { {0, 0, 0, 0} }, --//max 16 entries
texture = '',
repeatEffect = false, --can be a number,too
}
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
--// speed ups
local abs = math.abs
local sqrt = math.sqrt
local rand = math.random
local twopi= 2*math.pi
local cos = math.cos
local sin = math.sin
local min = math.min
local degreeToPI = math.pi/180
local spGetUnitViewPosition = Spring.GetUnitViewPosition
local spGetPositionLosState = Spring.GetPositionLosState
local spGetUnitLosState = Spring.GetUnitLosState
local spIsSphereInView = Spring.IsSphereInView
local spGetUnitRadius = Spring.GetUnitRadius
local spGetProjectilePosition = Spring.GetProjectilePosition
local IsPosInLos = Spring.IsPosInLos
local IsPosInAirLos = Spring.IsPosInAirLos
local IsPosInRadar = Spring.IsPosInRadar
local glTexture = gl.Texture
local glBlending = gl.Blending
local glUniform = gl.Uniform
local glUniformInt = gl.UniformInt
local glPushMatrix = gl.PushMatrix
local glPopMatrix = gl.PopMatrix
local glTranslate = gl.Translate
local glCreateList = gl.CreateList
local glCallList = gl.CallList
local glRotate = gl.Rotate
local glColor = gl.Color
local glUseShader = gl.UseShader
local GL_QUADS = GL.QUADS
local GL_ONE = GL.ONE
local GL_SRC_ALPHA = GL.SRC_ALPHA
local GL_ONE_MINUS_SRC_ALPHA = GL.ONE_MINUS_SRC_ALPHA
local glBeginEnd = gl.BeginEnd
local glMultiTexCoord= gl.MultiTexCoord
local glVertex = gl.Vertex
local ProcessParamCode = ProcessParamCode
local ParseParamString = ParseParamString
local Vmul = Vmul
local Vlength = Vlength
local nullVector = {0,0,0}
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function SimpleParticles2:CreateParticleAttributes(up, right, forward, partpos,n)
local life, delay, pos, speed, sizeStart,sizeEnd, rotStart,rotEnd;
local az = rand()*twopi;
local ay = (self.emitRot + rand() * self.emitRotSpread) * degreeToPI;
local a,b,c = cos(ay), cos(az)*sin(ay), sin(az)*sin(ay)
speed = {
up[1]*a - right[1]*b + forward[1]*c,
up[2]*a - right[2]*b + forward[2]*c,
up[3]*a - right[3]*b + forward[3]*c}
life = self.life + rand() * self.lifeSpread
speed = Vmul( speed,( self.speed + rand() * self.speedSpread) * life)
delay = rand() * self.delaySpread
sizeStart = self.size + rand() * self.sizeSpread
sizeEnd = sizeStart + self.sizeGrowth * life
rotStart = rand() * self.rotSpread * degreeToPI
rotEnd = (self.rotSpeed + rand() * self.rotSpeedSpread) * life * degreeToPI
if (partpos) then
local part = { speed=speed, velocity=Vlength(speed), life=life, delay=delay, i=n }
pos = { ProcessParamCode(partpos, part) }
else
pos = nullVector
end
return life, delay,
pos[1],pos[2],pos[3],
speed[1],speed[2],speed[3],
sizeStart,sizeEnd,
rotStart,rotEnd;
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function SimpleParticles2.BeginDraw()
glUseShader(billShader)
glBlending(GL_ONE, GL_ONE_MINUS_SRC_ALPHA)
end
function SimpleParticles2.EndDraw()
glTexture(0,false)
glBlending(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glUseShader(0)
lastTexture=""
end
function SimpleParticles2:Draw()
if (lastTexture~=self.texture) then
glTexture(0,self.texture)
lastTexture=self.texture
end
glMultiTexCoord(5, self.frame/200)
glCallList(self.dlist)
end
local function DrawParticleForDList(life,delay, x,y,z, dx,dy,dz, sizeStart,sizeEnd, rotStart,rotEnd)
glMultiTexCoord(0, x,y,z, life/200)
glMultiTexCoord(1, dx,dy,dz, delay/200)
glMultiTexCoord(2, sizeStart, rotStart, sizeEnd, rotEnd)
glVertex(0,0)
glVertex(1,0)
glVertex(1,1)
glVertex(0,1)
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function SimpleParticles2:Initialize()
billShader = gl.CreateShader({
vertex = [[
uniform vec4 colormap[16];
varying vec2 texCoord;
// global attributes
#define iframe gl_MultiTexCoord5.x
#define colors gl_MultiTexCoord3.w
#define forceExp gl_MultiTexCoord4.w
#define forceDir (gl_MultiTexCoord4.xyz)
// particle attributes
#define posV (gl_MultiTexCoord0.xyz)
#define dirV (gl_MultiTexCoord1.xyz)
#define maxLife gl_MultiTexCoord0.w
#define delay gl_MultiTexCoord1.w
// 1. holds dist,size and rot start values
// 2. holds dist,size and rot end values
// 3. holds dist,size and rot exponent values (equation is: 1-(1-life)^exp)
#define attributesStart vec3(0.0,gl_MultiTexCoord2.xy)
#define attributesEnd vec3(0.0,gl_MultiTexCoord2.zw)
#define attributesExp (gl_MultiTexCoord3.xyz)
void main()
{
float lframe = iframe - delay;
float life = lframe / maxLife; // 0.0 .. 1.0 range!
if (life<=0.0 || life>1.0) {
// move dead particles offscreen, this way we don't dump the fragment shader with it
gl_Position = vec4(-2000.0,-2000.0,-2000.0,-2000.0);
}else{
// calc color
float cpos = life * colors;
int ipos1 = int(cpos);
int ipos2 = int(min(float(ipos1 + 1),colors));
gl_FrontColor = mix(colormap[ipos1], colormap[ipos2], fract(cpos));
// calc particle attributes
vec3 attrib = vec3(1.0) - pow(vec3(1.0 - life), abs(attributesExp));
//if (attributesExp.x<0.0) attrib.x = 1.0 - attrib.x; // speed (no need for backward movement)
if (attributesExp.y<0.0) attrib.y = 1.0 - attrib.y; // size
if (attributesExp.z<0.0) attrib.z = 1.0 - attrib.z; // rot
attrib.yz = attributesStart.yz + attrib.yz * attributesEnd.yz;
// calc vertex position
vec3 forceV = (1.0 - pow(1.0 - life, abs(forceExp))) * forceDir; //FIXME combine with other attribs!
vec4 pos4 = vec4(posV + attrib.x * dirV + forceV, 1.0);
gl_Position = gl_ModelViewMatrix * pos4;
// calc particle rotation
float alpha = attrib.z;
float ca = cos(alpha);
float sa = sin(alpha);
mat2 rotation = mat2( ca , -sa, sa, ca );
// offset vertex from center of the polygon
gl_Position.xy += rotation * ( (gl_Vertex.xy - 0.5) * attrib.y );
// end
gl_Position = gl_ProjectionMatrix * gl_Position;
texCoord = gl_Vertex.xy;
}
}
]],
fragment = [[
uniform sampler2D tex0;
varying vec2 texCoord;
void main()
{
gl_FragColor = texture2D(tex0,texCoord) * gl_Color;
}
]],
uniformInt = {
tex0 = 0,
},
})
if (billShader==nil) then
print(PRIO_MAJOR,"LUPS->SimpleParticles2: Critical Shader Error: " ..gl.GetShaderLog())
return false
end
for i=1,16 do
colormapUniform[i] = gl.GetUniformLocation(billShader,"colormap["..(i-1).."]")
end
end
function SimpleParticles2:Finalize()
gl.DeleteShader(billShader)
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function SimpleParticles2:Update(n)
self.frame = self.frame + n
end
-- used if repeatEffect=true;
function SimpleParticles2:ReInitialize()
self.frame = 0
self.dieGameFrame = self.dieGameFrame + self.life + self.lifeSpread + self.delaySpread
end
local function InitializeParticles(self)
-- calc base of the emitvector system
local up = self.emitVector;
local right = Vcross( up, {up[2],up[3],-up[1]} );
local forward = Vcross( up, right );
local partposCode
if (self.partpos ~= "0,0,0") then
partposCode = ParseParamString(self.partpos)
end
self.force = Vmul(self.force,self.life + self.lifeSpread)
--// global data
glMultiTexCoord(3, self.speedExp, self.sizeExp, self.rotExp, self.ncolors)
glMultiTexCoord(4, self.force[1], self.force[2], self.force[3], self.forceExp)
local posX,posY,posZ = self.pos[1],self.pos[2],self.pos[3]
local ev = self.emitVector
local emitMatrix = CreateEmitMatrix3x3(ev[1],ev[2],ev[3])
self.maxSpawnRadius = 0
for i=1,self.count do
local life,delay, x,y,z, dx,dy,dz, sizeStart,sizeEnd, rotStart,rotEnd = self:CreateParticleAttributes(up,right,forward, partposCode, i-1)
dx,dy,dz = MultMatrix3x3(emitMatrix,dx,dy,dz)
DrawParticleForDList(life, delay,
x+posX,y+posY,z+posZ, -- relative start pos
dx,dy,dz, -- speed vector
sizeStart,sizeEnd,
rotStart,rotEnd)
local spawnDist = x*x + y*y + z*z
if (spawnDist>self.maxSpawnRadius) then self.maxSpawnRadius=spawnDist end
end
self.maxSpawnRadius = sqrt(self.maxSpawnRadius)
glMultiTexCoord(2, 0,0,0,1)
glMultiTexCoord(3, 0,0,0,1)
glMultiTexCoord(4, 0,0,0,1)
end
local function CreateDList(self)
--// FIXME: compress each color into 32bit register of a MultiTexCoord, so each MultiTexCoord can hold 4 rgba packs!
for i=1,min(self.ncolors+1,16) do
local color = self.colormap[i]
glUniform( colormapUniform[i] , color[1], color[2], color[3], color[4] )
end
glBeginEnd(GL_QUADS,InitializeParticles,self)
end
function SimpleParticles2:CreateParticle()
self.ncolors = #self.colormap-1
self.dlist = glCreateList(CreateDList,self)
self.frame = 0
self.firstGameFrame = thisGameFrame
self.dieGameFrame = self.firstGameFrame + self.life + self.lifeSpread + self.delaySpread
--// visibility check vars
self.radius = self.size + self.sizeSpread + self.maxSpawnRadius + 100
self.maxSpeed = self.speed + abs(self.speedSpread)
self.forceStrength = Vlength(self.force)
self.sphereGrowth = self.forceStrength + self.sizeGrowth + self.maxSpeed
end
function SimpleParticles2:Destroy()
gl.DeleteList(self.dlist)
--gl.DeleteTexture(self.texture)
end
function SimpleParticles2:Visible()
local radius = self.radius +
self.frame*self.sphereGrowth --FIXME: frame is only updated on Update()
local posX,posY,posZ = self.pos[1],self.pos[2],self.pos[3]
local losState
if (self.unit and not self.worldspace) then
losState = GetUnitLosState(self.unit)
local ux,uy,uz = spGetUnitViewPosition(self.unit)
if not ux then
return false
end
radius = radius + (spGetUnitRadius(self.unit) or 0)
if self.noIconDraw then
if not Spring.IsUnitVisible(self.unit, radius, self.noIconDraw) then
return false
end
end
posX,posY,posZ = posX+ux,posY+uy,posZ+uz
elseif (self.projectile and not self.worldspace) then
local px,py,pz = spGetProjectilePosition(self.projectile)
posX,posY,posZ = posX+px,posY+py,posZ+pz
end
if (losState==nil) then
if (self.radar) then
losState = IsPosInRadar(posX,posY,posZ)
end
if ((not losState) and self.airLos) then
losState = IsPosInAirLos(posX,posY,posZ)
end
if ((not losState) and self.los) then
losState = IsPosInLos(posX,posY,posZ)
end
end
return (losState)and(spIsSphereInView(posX,posY,posZ,radius))
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
local MergeTable = MergeTable
local setmetatable = setmetatable
function SimpleParticles2.Create(Options)
local newObject = MergeTable(Options, SimpleParticles2.Default)
setmetatable(newObject,SimpleParticles2) --// make handle lookup
newObject:CreateParticle()
return newObject
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
return SimpleParticles2
|
--------------------------------------------------------------------------------
-- Copyright (c) 2015 - 2016 , 蒙占志(topameng) [email protected]
-- All rights reserved.
-- Use, modification and distribution are subject to the "MIT License"
--------------------------------------------------------------------------------
local math = math
local floor = math.floor
local abs = math.abs
local Mathf = Mathf
Mathf.Deg2Rad = math.rad(1)
Mathf.Epsilon = 1.4013e-45
Mathf.Infinity = math.huge
Mathf.NegativeInfinity = -math.huge
Mathf.PI = math.pi
Mathf.Rad2Deg = math.deg(1)
Mathf.Abs = math.abs
Mathf.Acos = math.acos
Mathf.Asin = math.asin
Mathf.Atan = math.atan
Mathf.Atan2 = math.atan2
Mathf.Ceil = math.ceil
Mathf.Cos = math.cos
Mathf.Exp = math.exp
Mathf.Floor = math.floor
Mathf.Log = math.log
Mathf.Log10 = math.log10
Mathf.Max = math.max
Mathf.Min = math.min
Mathf.Pow = math.pow
Mathf.Sin = math.sin
Mathf.Sqrt = math.sqrt
Mathf.Tan = math.tan
Mathf.Deg = math.deg
Mathf.Rad = math.rad
Mathf.Random = math.random
function Mathf.Approximately(a, b)
return abs(b - a) < math.max(1e-6 * math.max(abs(a), abs(b)), 1.121039e-44)
end
function Mathf.Clamp(value, min, max)
if value < min then
value = min
elseif value > max then
value = max
end
return value
end
function Mathf.Clamp01(value)
if value < 0 then
return 0
elseif value > 1 then
return 1
end
return value
end
function Mathf.DeltaAngle(current, target)
local num = Mathf.Repeat(target - current, 360)
if num > 180 then
num = num - 360
end
return num
end
function Mathf.Gamma(value, absmax, gamma)
local flag = false
if value < 0 then
flag = true
end
local num = abs(value)
if num > absmax then
return (not flag) and num or -num
end
local num2 = math.pow(num / absmax, gamma) * absmax
return (not flag) and num2 or -num2
end
function Mathf.InverseLerp(from, to, value)
if from < to then
if value < from then
return 0
end
if value > to then
return 1
end
value = value - from
value = value/(to - from)
return value
end
if from <= to then
return 0
end
if value < to then
return 1
end
if value > from then
return 0
end
return 1 - ((value - to) / (from - to))
end
function Mathf.Lerp(from, to, t)
return from + (to - from) * Mathf.Clamp01(t)
end
function Mathf.LerpAngle(a, b, t)
local num = Mathf.Repeat(b - a, 360)
if num > 180 then
num = num - 360
end
return a + num * Mathf.Clamp01(t)
end
function Mathf.LerpUnclamped(a, b, t)
return a + (b - a) * t;
end
function Mathf.MoveTowards(current, target, maxDelta)
if abs(target - current) <= maxDelta then
return target
end
return current + mathf.sign(target - current) * maxDelta
end
function Mathf.MoveTowardsAngle(current, target, maxDelta)
target = current + Mathf.DeltaAngle(current, target)
return Mathf.MoveTowards(current, target, maxDelta)
end
function Mathf.PingPong(t, length)
t = Mathf.Repeat(t, length * 2)
return length - abs(t - length)
end
function Mathf.Repeat(t, length)
return t - (floor(t / length) * length)
end
function Mathf.Round(num)
return floor(num + 0.5)
end
function Mathf.Sign(num)
if num > 0 then
num = 1
elseif num < 0 then
num = -1
else
num = 0
end
return num
end
function Mathf.SmoothDamp(current, target, currentVelocity, smoothTime, maxSpeed, deltaTime)
maxSpeed = maxSpeed or Mathf.Infinity
deltaTime = deltaTime or Time.deltaTime
smoothTime = Mathf.Max(0.0001, smoothTime)
local num = 2 / smoothTime
local num2 = num * deltaTime
local num3 = 1 / (1 + num2 + 0.48 * num2 * num2 + 0.235 * num2 * num2 * num2)
local num4 = current - target
local num5 = target
local max = maxSpeed * smoothTime
num4 = Mathf.Clamp(num4, -max, max)
target = current - num4
local num7 = (currentVelocity + (num * num4)) * deltaTime
currentVelocity = (currentVelocity - num * num7) * num3
local num8 = target + (num4 + num7) * num3
if (num5 > current) == (num8 > num5) then
num8 = num5
currentVelocity = (num8 - num5) / deltaTime
end
return num8,currentVelocity
end
function Mathf.SmoothDampAngle(current, target, currentVelocity, smoothTime, maxSpeed, deltaTime)
deltaTime = deltaTime or Time.deltaTime
maxSpeed = maxSpeed or Mathf.Infinity
target = current + Mathf.DeltaAngle(current, target)
return Mathf.SmoothDamp(current, target, currentVelocity, smoothTime, maxSpeed, deltaTime)
end
function Mathf.SmoothStep(from, to, t)
t = Mathf.Clamp01(t)
t = -2 * t * t * t + 3 * t * t
return to * t + from * (1 - t)
end
function Mathf.HorizontalAngle(dir)
return math.deg(math.atan2(dir.x, dir.z))
end
function Mathf.IsNan(number)
return not (number == number)
end
UnityEngine.Mathf = Mathf
return Mathf
|
-- Quick and dirty module including some helper methods
M = {}
local function tprint(t, indent)
function printShit(k, v, indent)
--if k == "com" then
print(string.rep(" ",indent)..k," | ",v)
--end
end
if not indent then indent = 0 end
if type(t) == "table" then
for k,v in pairs(t) do
if type(v)=="table" then
printShit(k, v, indent)
tprint(v, indent+1)
else
printShit(k, v, indent)
end
end
else
print(type(t), t)
end
end
local function orderedPairs(t)
local function orderedNext(t, state)
local function __genOrderedIndex( t )
local orderedIndex = {}
for key in pairs(t) do
table.insert( orderedIndex, key )
end
table.sort( orderedIndex )
return orderedIndex
end
if state == nil then
-- the first time, generate the index
t.__orderedIndex = __genOrderedIndex( t )
key = t.__orderedIndex[1]
return key, t[key]
end
key = nil
for i = 1,table.getn(t.__orderedIndex) do
if t.__orderedIndex[i] == state then
key = t.__orderedIndex[i+1]
end
end
if key then
return key, t[key]
end
t.__orderedIndex = nil
return
end
return orderedNext, t, nil
end
-- TODO Move this to another file
function string:split(delimiter)
local result = { }
local from = 1
local delim_from, delim_to = string.find( self, delimiter, from )
while delim_from do
table.insert( result, string.sub( self, from , delim_from-1 ) )
from = delim_to + 1
delim_from, delim_to = string.find( self, delimiter, from )
end
table.insert( result, string.sub( self, from ) )
return result
end
M.tprint = tprint
M.orderedPairs = orderedPairs
return M
|
---@diagnostic disable: lowercase-global
includetests = {"other-1-*"}
checkengines = {"pdftex", "xetex"}
stdengine = "pdftex"
checkruns = 1
|
-- SPDX-License-Identifier: MIT
hexchat.register('MassHighlightIgnore', '3', 'Ignore mass highlight spam')
if unpack == nil then
unpack = table.unpack -- fix lua 5.2
end
local MAX_COUNT = 4
-- http://lua-users.org/wiki/SplitJoin
local function split(str)
local t = {}
for i in string.gmatch(str, "%S+") do
t[#t + 1] = i
end
return t
end
local function nick_in_list (nick, list)
for _, word in pairs(list) do
if hexchat.nickcmp(word, nick) == 0 then
return true
end
end
return false
end
local function is_mass_highlight (message)
local count = 0
local words = split(message)
for user in hexchat.props.context:iterate('users') do
if nick_in_list(user.nick, words) then
count = count + 1
if count == MAX_COUNT then
return true
end
end
end
return false
end
local function ignore_mass_hilight (args, attrs, event)
if is_mass_highlight(args[2]) then
hexchat.emit_print_attrs(attrs, event, unpack(args))
return hexchat.EAT_ALL
end
end
hexchat.hook_print_attrs('Channel Msg Hilight', function (args, attrs)
return ignore_mass_hilight(args, attrs, 'Channel Message')
end, hexchat.PRI_HIGHEST)
hexchat.hook_print('Channel Action Hilight', function (args, attrs)
return ignore_mass_hilight(args, attrs, 'Channel Action')
end, hexchat.PRI_HIGHEST)
|
---@meta
---@class cc.Physics3DWorld :cc.Ref
local Physics3DWorld={ }
cc.Physics3DWorld=Physics3DWorld
---* set gravity for the physics world
---@param gravity vec3_table
---@return self
function Physics3DWorld:setGravity (gravity) end
---* Simulate one frame.
---@param dt float
---@return self
function Physics3DWorld:stepSimulate (dt) end
---*
---@return boolean
function Physics3DWorld:needCollisionChecking () end
---*
---@return self
function Physics3DWorld:collisionChecking () end
---*
---@return self
function Physics3DWorld:setGhostPairCallback () end
---* Remove all Physics3DObjects.
---@return self
function Physics3DWorld:removeAllPhysics3DObjects () end
---* Check debug drawing is enabled.
---@return boolean
function Physics3DWorld:isDebugDrawEnabled () end
---* Remove all Physics3DConstraint.
---@return self
function Physics3DWorld:removeAllPhysics3DConstraints () end
---* get current gravity
---@return vec3_table
function Physics3DWorld:getGravity () end
---* Remove a Physics3DConstraint.
---@param constraint cc.Physics3DConstraint
---@return self
function Physics3DWorld:removePhysics3DConstraint (constraint) end
---* Add a Physics3DObject.
---@param physicsObj cc.Physics3DObject
---@return self
function Physics3DWorld:addPhysics3DObject (physicsObj) end
---* Enable or disable debug drawing.
---@param enableDebugDraw boolean
---@return self
function Physics3DWorld:setDebugDrawEnable (enableDebugDraw) end
---* Remove a Physics3DObject.
---@param physicsObj cc.Physics3DObject
---@return self
function Physics3DWorld:removePhysics3DObject (physicsObj) end
---* Add a Physics3DConstraint.
---@param constraint cc.Physics3DConstraint
---@param disableCollisionsBetweenLinkedObjs boolean
---@return self
function Physics3DWorld:addPhysics3DConstraint (constraint,disableCollisionsBetweenLinkedObjs) end
---* Internal method, the updater of debug drawing, need called each frame.
---@param renderer cc.Renderer
---@return self
function Physics3DWorld:debugDraw (renderer) end
---*
---@return self
function Physics3DWorld:Physics3DWorld () end
|
-- print multiplication table up to 12
print("Enter a number:")
n = io.read("n")
for i=1,12 do
print(n, "x", i, "=", n*i)
end
|
local _={}
_[27]={}
_[26]={}
_[25]={}
_[24]={}
_[23]={}
_[22]={tags=_[27],text="[1, 2, 3, 4]"}
_[21]={tags=_[27],text="1,2,3,4: "}
_[20]={tags=_[26],text="[1, 2, 3, 4, 5]"}
_[19]={tags=_[26],text="1,2,3,4,5: "}
_[18]={tags=_[25],text="[1, 2, 3, 4]"}
_[17]={tags=_[25],text="1,2,3,4: "}
_[16]={tags=_[24],text="[1, 2, 3]"}
_[15]={tags=_[24],text="1,2,3: "}
_[14]={tags=_[23],text="[1, 2]"}
_[13]={tags=_[23],text="1,2: "}
_[12]={_[21],_[22]}
_[11]={_[19],_[20]}
_[10]={_[17],_[18]}
_[9]={_[15],_[16]}
_[8]={_[13],_[14]}
_[7]={"return"}
_[6]={"text",_[12]}
_[5]={"error","cancel merge; in Lua function \"error\"; at test/tests/checkpoint merging mutable value.ans:23"}
_[4]={"text",_[11]}
_[3]={"text",_[10]}
_[2]={"text",_[9]}
_[1]={"text",_[8]}
return {_[1],_[2],_[3],_[4],_[5],_[6],_[7]}
--[[
{ "text", { {
tags = <1>{},
text = "1,2: "
}, {
tags = <table 1>,
text = "[1, 2]"
} } }
{ "text", { {
tags = <1>{},
text = "1,2,3: "
}, {
tags = <table 1>,
text = "[1, 2, 3]"
} } }
{ "text", { {
tags = <1>{},
text = "1,2,3,4: "
}, {
tags = <table 1>,
text = "[1, 2, 3, 4]"
} } }
{ "text", { {
tags = <1>{},
text = "1,2,3,4,5: "
}, {
tags = <table 1>,
text = "[1, 2, 3, 4, 5]"
} } }
{ "error", 'cancel merge; in Lua function "error"; at test/tests/checkpoint merging mutable value.ans:23' }
{ "text", { {
tags = <1>{},
text = "1,2,3,4: "
}, {
tags = <table 1>,
text = "[1, 2, 3, 4]"
} } }
{ "return" }
]]--
|
--デスカイザー・ドラゴン
function c6021033.initial_effect(c)
aux.AddMaterialCodeList(c,33420078)
--synchro summon
aux.AddSynchroProcedure(c,aux.FilterBoolFunction(Card.IsCode,33420078),aux.NonTuner(Card.IsRace,RACE_ZOMBIE),1)
c:EnableReviveLimit()
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(6021033,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetTarget(c6021033.sptg)
e1:SetOperation(c6021033.spop)
c:RegisterEffect(e1)
--destroy
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_LEAVE_FIELD)
e2:SetOperation(c6021033.desop)
e2:SetLabelObject(e1)
c:RegisterEffect(e2)
end
function c6021033.filter(c,e,tp)
return c:IsRace(RACE_ZOMBIE) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c6021033.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(1-tp) and c6021033.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c6021033.filter,tp,0,LOCATION_GRAVE,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c6021033.filter,tp,0,LOCATION_GRAVE,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c6021033.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsRace(RACE_ZOMBIE)
and Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP_ATTACK)~=0 then
if c:IsFacedown() or not c:IsRelateToEffect(e) then return end
c:SetCardTarget(tc)
e:SetLabelObject(tc)
tc:RegisterFlagEffect(6021033,RESET_EVENT+RESETS_STANDARD,0,0)
c:RegisterFlagEffect(6021033,RESET_EVENT+0x1020000,0,0)
end
end
function c6021033.desop(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject():GetLabelObject()
if tc and tc:GetFlagEffect(6021033)~=0 and e:GetHandler():GetFlagEffect(6021033)~=0 then
Duel.Destroy(tc,REASON_EFFECT)
end
end
|
AdvSynAddon = WINDOW_MANAGER:CreateControl(nil, GuiRoot)
local AdvSyn = _G['AdvSynAddon']
local L = {}
------------------------------------------------------------------------------------------------------------------
-- English
------------------------------------------------------------------------------------------------------------------
--Toggle strings
L.SynergyNotification = 'Synergy available'
L.SynergyNotificationTooltip = 'setup mode - go to settings to change'
L.SettingFontsize = 'Fontsize'
L.SettingMoveNotification = 'Setup Mode'
L.SettingMoveNotificationTooltip = 'when active, notification is always shown and movable. ignores "active on this char"'
L.SettingTransparency = 'Opacity'
L.SettingTransparencyTooltip = '0 = hidden, 100 = fully visible'
L.SettingActiveOnChar = 'active on this char'
L.SettingActiveOnCharTooltip = 'you can disable the notification, but still use debug to help improve this addon'
L.SettingDebug = 'Debug'
L.SettingDebugTooltip = 'save synergy details. For more information visit the addon website.'
L.SettingShowNames = 'show synergy names'
L.SettingShowNamesTooltip = 'this is a shady setting and does magic stuff!'
------------------------------------------------------------------------------------------------------------------
function AdvSyn:GetLanguage() -- default locale, will be the return unless overwritten
return L
end
|
-- system.lua
--
-- This script is executed after a system boot or a system reset and is intended
-- for setup the system.
---------------------------------------------------
-- Main setups
---------------------------------------------------
os.loglevel(os.LOG_INFO) -- Log level to info
os.logcons(true) -- Enable/disable sys log messages to console
os.shell(true) -- Enable/disable shell
os.history(false) -- Enable/disable history
|
local function chain(loveFunc, func, after)
return function (...)
if loveFunc and after then
loveFunc(...)
end
func(...)
if loveFunc and not after then
loveFunc(...)
end
end
end
local function loveChain(instance, funcNames)
for i=1, #funcNames do
local key = funcNames[i]
love[key] = chain(love[key], function (...)
instance[key](instance, ...)
end)
end
end
local function class(base)
local Klass = {}
Klass.__index = Klass
setmetatable(Klass, {
__call = function (s, ...)
local o = {}
if base then
setmetatable(s, base)
o = base(...)
end
o = setmetatable(o, s)
if o.init then
o:init(...)
end
return o
end
})
return Klass
end
return {
class = class,
loveChain = loveChain,
}
|
local _M = {}
function _M.now()
return math.ceil(ngx.now()*1000)
end
function _M.format_datetime(ms)
if nil == ms then return nil end
return os.date("%Y-%m-%d %H:%M" , ms/1000)
end
function _M.format_date(ms)
if nil == ms then return nil end
return os.date("%Y-%m-%d", ms/1000)
end
function _M.format_time(ms)
if nil == ms then return nil end
return os.date("%H:%M", ms/1000)
end
function _M.parse(str)
if nil == str then return nil end
if not str or 'string' ~= type(str) then return nil end
local p
local y, mon,d,h,min,s
if not str:find(':') then
p = "(%d+)-(%d+)-(%d+)"
y, mon,d = str:match(p)
elseif not str:find('-') then
p = "(%d+):(%d+):(%d+)"
h,min,s = str:match(p)
else
p = "(%d+)-(%d+)-(%d+) (%d+):(%d+):(%d+)"
y, mon,d,h,min,s = str:match(p)
if not y then
p = "(%d+)-(%d+)-(%d+) (%d+):(%d+)"
y, mon,d,h,min = str:match(p)
end
end
return 1000*os.time({year=y or 1970,month=mon or 1,day=d or 1,hour=tonumber(h) or 0,min=tonumber(min) or 0,sec=tonumber(s) or 0})
end
return _M
|
local rcalc_gui = {}
local gui = require("__flib__.gui")
local math = require("__flib__.math")
local constants = require("constants")
local fixed_format = require("lib.fixed-precision-format")
-- add commas to separate thousands
-- from lua-users.org: http://lua-users.org/wiki/FormattingNumbers
-- credit http://richard.warburton.it
local function comma_value(input)
local left, num, right = string.match(input,'^([^%d]*%d)(%d*)(.-)$')
return left..(num:reverse():gsub('(%d%d%d)','%1,'):reverse())..right
end
local function format_amount(amount)
return fixed_format(amount, 4 - (amount < 0 and 1 or 0), "2"), comma_value(math.round_to(amount, 3)):gsub(" $", "")
end
gui.add_templates{
column_label = {type = "label", style = "bold_label", style_mods = {minimal_width = 50, horizontal_align = "center"}},
frame_action_button = {type = "sprite-button", style = "frame_action_button", mouse_button_filter = {"left"}},
icon_column_header = {
type = "label",
style = "bold_label",
style_mods = {left_margin = 4, width = 31, horizontal_align = "center"},
caption = "--"
},
listbox_with_label = function(name, width, toolbar_children)
return {type = "flow", style_mods = {vertical_spacing = 6}, direction = "vertical", children = {
{type = "label", style = "caption_label", style_mods = {left_margin = 2}, caption = {"rcalc-gui."..name}},
{
type = "frame",
style = "rcalc_material_list_box_frame",
direction = "vertical",
save_as = "panes."..name..".frame",
children = {
{
type = "frame",
style = "rcalc_toolbar_frame",
style_mods = {width = width},
save_as = "panes."..name..".toolbar",
children = toolbar_children
},
{
type = "scroll-pane",
style = "rcalc_material_list_box_scroll_pane",
save_as = "panes."..name..".scroll_pane",
children = {
-- dummy element - setting horizontally_stretchable on the scroll pane itself causes weirdness
{template = "pushers.horizontal"},
{
type = "flow",
style_mods = {margin = 0, padding = 0, vertical_spacing = 0},
direction = "vertical",
save_as = "panes."..name..".content_flow"
}
}
}
}
}
}}
end,
power_total_label = {type = "label", style_mods = {left_padding = 2, top_padding = 2}},
pushers = {
horizontal = {type = "empty-widget", style_mods = {horizontally_stretchable = true}}
}
}
gui.add_handlers{
close_button = {
on_gui_click = function(e)
rcalc_gui.close(game.get_player(e.player_index), global.players[e.player_index])
end
},
pin_button = {
on_gui_click = function(e)
local player = game.get_player(e.player_index)
local player_table = global.players[e.player_index]
local gui_data = player_table.gui
if gui_data.pinned then
gui_data.titlebar.pin_button.style = "frame_action_button"
gui_data.titlebar.pin_button.sprite = "rc_pin_white"
gui_data.pinned = false
gui_data.window.force_auto_center()
player.opened = gui_data.window
else
gui_data.titlebar.pin_button.style = "flib_selected_frame_action_button"
gui_data.titlebar.pin_button.sprite = "rc_pin_black"
gui_data.pinned = true
player.opened = nil
end
end
},
units_choose_elem_button = {
on_gui_elem_changed = function(e)
local player = game.get_player(e.player_index)
local player_table = global.players[e.player_index]
local player_settings = player_table.settings
local elem_value = e.element.elem_value
if elem_value then
player_settings[constants.units_to_setting_name[player_settings.units]] = e.element.elem_value
rcalc_gui.update_contents(player, player_table)
else
e.element.elem_value = player_settings[constants.units_to_setting_name[player_settings.units]]
end
end
},
units_drop_down = {
on_gui_selection_state_changed = function(e)
local player = game.get_player(e.player_index)
local player_table = global.players[e.player_index]
player_table.settings.units = e.element.selected_index
rcalc_gui.update_contents(player, player_table)
end
},
window = {
on_gui_closed = function(e)
local player_table = global.players[e.player_index]
if not player_table.gui.pinned then
rcalc_gui.close(game.get_player(e.player_index), global.players[e.player_index])
end
end
}
}
function rcalc_gui.create(player, player_table)
local gui_data = gui.build(player.gui.screen, {
{type = "frame", direction = "vertical", handlers = "window", save_as = "window", children = {
{type = "flow", save_as = "titlebar.flow", children = {
{
type = "label",
style = "frame_title",
caption = {"mod-name.RateCalculator"},
ignored_by_interaction = true
},
{type = "empty-widget", style = "flib_titlebar_drag_handle", ignored_by_interaction = true},
{
template = "frame_action_button",
tooltip = {"rcalc-gui.keep-open"},
sprite = "rc_pin_white",
hovered_sprite = "rc_pin_black",
clicked_sprite = "rc_pin_black",
handlers = "pin_button",
save_as = "titlebar.pin_button"
},
{
template = "frame_action_button",
sprite = "utility/close_white",
hovered_sprite = "utility/close_black",
clicked_sprite = "utility/close_black",
handlers = "close_button",
save_as = "titlebar.close_button"
}
}},
{type = "frame", style = "inside_shallow_frame", direction = "vertical", children = {
{type = "frame", style = "subheader_frame", children = {
{
type = "label",
style = "subheader_caption_label",
style_mods = {right_margin = 4},
caption = {"rcalc-gui.units"}
},
{template = "pushers.horizontal"},
{
type = "choose-elem-button",
style = "rcalc_choose_elem_button",
elem_type = "entity",
handlers = "units_choose_elem_button",
save_as = "toolbar.units_choose_elem_button"
},
{
type = "drop-down",
items = constants.units_dropdown_contents,
selected_index = player_table.settings.units,
handlers = "units_drop_down",
save_as = "toolbar.units_drop_down"
},
}},
{type = "flow", style_mods = {padding = 12, top_padding = 5, horizontal_spacing = 12}, children = {
gui.templates.listbox_with_label("inputs", 122, {
{template = "icon_column_header"},
{
template = "column_label",
caption = {"rcalc-gui.rate"},
tooltip = {"rcalc-gui.consumption-rate-description"}
},
}),
gui.templates.listbox_with_label("outputs", 366, {
{template = "icon_column_header"},
{
template = "column_label",
caption = {"rcalc-gui.rate"},
tooltip = {"rcalc-gui.production-rate-description"}
},
{
template = "column_label",
caption = {"rcalc-gui.per-machine"},
tooltip = {"rcalc-gui.per-machine-description"}
},
{template = "column_label", caption = {"rcalc-gui.net-rate"}, tooltip = {"rcalc-gui.net-rate-description"}},
{
template = "column_label",
caption = {"rcalc-gui.net-machines"},
tooltip = {"rcalc-gui.net-machines-description"}
},
})
}},
{
type = "frame",
style = "subfooter_frame",
style_mods = {bottom_padding = 5},
save_as = "info_frame",
children = {
{type = "flow", style_mods = {vertical_align = "center"}, children = {
{
type = "label",
style = "subheader_caption_label",
style_mods = {right_padding = 8},
caption = {"rcalc-gui.totals"}
},
{type = "label", style = "bold_label", caption = {"rcalc-gui.consumption"}},
{type = "label", save_as = "subfooter.total_consumption_label"},
{template = "pushers.horizontal"},
{type = "label", style = "bold_label", caption = {"rcalc-gui.production"}},
{type = "label", save_as = "subfooter.total_production_label"},
{template = "pushers.horizontal"},
{type = "label", style = "bold_label", caption = {"rcalc-gui.net-rate-with-colon"}},
{type = "label", save_as = "subfooter.net_rate_label"},
{type = "empty-widget", style_mods = {width = 6}}
}}
}
}
}}
}}
})
gui_data.titlebar.flow.drag_target = gui_data.window
gui_data.window.force_auto_center()
gui_data.window.visible = false
gui_data.pinned = false
player_table.gui = gui_data
end
function rcalc_gui.destroy(player, player_table)
gui.remove_player_filters(player.index)
player_table.gui.window.destroy()
player_table.gui = nil
end
function rcalc_gui.open(player, player_table)
player_table.gui.window.visible = true
player_table.flags.gui_open = true
if not player_table.gui.pinned then
player.opened = player_table.gui.window
end
end
function rcalc_gui.close(player, player_table)
player_table.gui.window.visible = false
player_table.flags.gui_open = false
-- focus another element in case the dropdown was being used
player_table.gui.window.focus()
-- deassign player.opened if it's still assigned
if player.opened == player_table.gui.window then
player.opened = nil
end
player_table.selection_data = nil
end
function rcalc_gui.update_contents(player, player_table)
local gui_data = player_table.gui
local data_tables = player_table.selection_data
if not data_tables then return end
local rates_lookup = data_tables.hash
local sorted_rates = data_tables.sorted
local units = player_table.settings.units
-- choose elem button
local choose_elem_button = gui_data.toolbar.units_choose_elem_button
local ceb_data = constants.choose_elem_buttons[units]
local unit_data = global.unit_data[units]
if ceb_data then
local selected_entity = player_table.settings[ceb_data.type]
unit_data = unit_data[selected_entity]
choose_elem_button.visible = true
choose_elem_button.elem_value = selected_entity
choose_elem_button.elem_filters = ceb_data.filters
else
choose_elem_button.visible = false
end
local stack_sizes_cache = {}
local item_prototypes = game.item_prototypes
local function apply_unit_data(obj_data)
local amount = obj_data.amount
if unit_data.divide_by_stack_size then
local stack_size = stack_sizes_cache[obj_data.name]
if not stack_size then
stack_size = item_prototypes[obj_data.name].stack_size
stack_sizes_cache[obj_data.name] = stack_size
end
amount = amount / stack_size
end
return (amount / unit_data.divisor) * unit_data.multiplier
end
-- rates
local total_power = {
inputs = 0,
outputs = 0
}
for _, category in ipairs{"inputs", "outputs"} do
local content_flow = gui_data.panes[category].content_flow
local children = content_flow.children
local children_count = #children
local i = 0
for _, obj_data in ipairs(sorted_rates[category]) do
local obj_type = obj_data.type
local obj_name = obj_data.name
local rate_fixed, per_machine_fixed, net_rate_fixed, net_machines_fixed = "--", "--", "--", "--"
local icon_tt, rate_tt, per_machine_tt, net_rate_tt, net_machines_tt = "", "", "", "", ""
-- apply unit_data properties
if unit_data.types[obj_type] then
local amount = apply_unit_data(obj_data)
if units == constants.units_lookup.power then
total_power[category] = total_power[category] + amount
end
rate_fixed, rate_tt = format_amount(amount)
icon_tt = {"", obj_data.localised_name, "\n", {"rcalc-gui.n-machines", obj_data.machines}}
if category == "outputs" then
local per_machine = amount / obj_data.machines
per_machine_fixed, per_machine_tt = format_amount(per_machine)
local obj_input = rates_lookup.inputs[obj_type.."."..obj_name]
if obj_input then
local net_rate = amount - apply_unit_data(obj_input)
net_rate_fixed, net_rate_tt = format_amount(net_rate)
--- EEEs have inconsistent stats, so don't calculate net machines for them
if obj_type ~= "entity" or game.entity_prototypes[obj_name].type ~= "electric-energy-interface" then
net_machines_fixed, net_machines_tt = format_amount((net_rate / per_machine))
end
end
end
i = i + 1
local frame = children[i]
if frame then
local frame_children = frame.children
local icon = frame_children[1]
icon.sprite = obj_type.."/"..obj_name
icon.number = obj_data.machines
icon.tooltip = icon_tt
local rate_label = frame_children[2]
rate_label.caption = rate_fixed
rate_label.tooltip = rate_tt
if category == "outputs" then
local per_machine_label = frame_children[3]
per_machine_label.caption = per_machine_fixed
per_machine_label.tooltip = per_machine_tt
local net_rate_label = frame_children[4]
net_rate_label.caption = net_rate_fixed
net_rate_label.tooltip = net_rate_tt
local net_machines_label = frame_children[5]
net_machines_label.caption = net_machines_fixed
net_machines_label.tooltip = net_machines_tt
end
else
gui.build(content_flow, {
{type = "frame", style = "rcalc_material_info_frame", children = {
{
type = "sprite-button",
style = "rcalc_material_icon_button",
style_mods = {width = 32, height = 32},
sprite = obj_type.."/"..obj_name,
number = obj_data.machines,
tooltip = icon_tt,
elem_mods = {enabled = false}
},
{type = "label", style = "rcalc_amount_label", caption = rate_fixed, tooltip = rate_tt},
{type = "condition", condition = (category == "outputs"), children = {
{
type = "label",
style = "rcalc_amount_label",
style_mods = {width = 75},
caption = per_machine_fixed,
tooltip = per_machine_tt
},
{
type = "label",
style = "rcalc_amount_label",
style_mods = {width = 49},
caption = net_rate_fixed,
tooltip = net_rate_tt
},
{
type = "label",
style = "rcalc_amount_label",
style_mods = {width = 84},
caption = net_machines_fixed,
tooltip = net_machines_tt
},
}},
{type = "empty-widget", style_mods = {horizontally_stretchable = true, left_margin = -12}}
}}
})
end
end
end
if i < children_count then
for ni = i + 1, children_count do
children[ni].destroy()
end
end
end
-- info frame
if units == constants.units_lookup.power then
local subfooter_elems = gui_data.subfooter
local input_label, input_tt = format_amount(total_power.inputs)
local input_elem = subfooter_elems.total_consumption_label
input_elem.caption = input_label.."W"
input_elem.tooltip = input_tt.." W"
local output_label, output_tt = format_amount(total_power.outputs)
local output_elem = subfooter_elems.total_production_label
output_elem.caption = output_label.."W"
output_elem.tooltip = output_tt.." W"
local net_label, net_tt = format_amount(total_power.outputs - total_power.inputs)
local net_elem = subfooter_elems.net_rate_label
net_elem.caption = net_label.."W"
net_elem.tooltip = net_tt.." W"
gui_data.info_frame.visible = true
else
gui_data.info_frame.visible = false
end
end
return rcalc_gui
|
--This file contains a list of simple custom maps
--These are to replace the old custom map model, and for optimisation
vcnlib.maps = {}
local maps = vcnlib.maps
--Height Maps
local get_height = function(pos)
return pos.y
end
local scale = function(value,scale)
return value*scale
end
local centre_height = function(value,centre)
return value-centre
end
local zero = function()
return 0
end
maps.height_map = {
get3d = function(self,pos)
return get_height(pos)
end,
get2d = zero,
construct = function()
return
end,
}
maps.scaled_height_map = {
get3d = function(self,pos)
return scale(pos.y,self.scale)
end,
get2d = zero,
construct = function(self,def)
self.scale = def.scale
return
end
}
maps.centred_height_map = {
get3d = function(self,pos)
return centre_height(pos.y,self.centre)
end,
get2d = zero,
construct = function(self,def)
self.centre = def.centre
return
end,
}
maps.scaled_centred_height_map = {
get3d = function(self,pos)
return scale(centre_height(pos.y,self.centre),self.scale)
end,
get2d = zero,
construct = function(self,def)
self.centre = def.centre
self.scale = def.scale
return
end,
}
--Distance functions
maps.centred_distance = {
get3d = function(self,pos)
return self.get_dist(self.centre,pos)
end,
get2d = function(self,pos)
return self.get_dist(self.centre,pos)
end,
construct = function(self,def)
self.dimensions = def.dimensions
self.geometry = def.geometry
self.centre = def.centre or {x=0,y=0,z=0}
self.get_dist = vcnlib.get_distance_function(self.geometry
,self.dimensions)
end,
}
maps.scaled_centred_distance = {
get3d = function(self,pos)
return scale(self.get_dist(self.centre,pos),self.scale)
end,
get2d = function(self,pos)
return scale(self.get_dist(self.centre,pos),self.scale)
end,
construct = function(self,def)
self.dimensions = def.dimensions
self.geometry = def.geometry
self.centre = def.centre or {x=0,y=0,z=0}
self.scale = def.scale
self.get_dist = vcnlib.get_distance_function(self.geometry
,self.dimensions)
end,
}
local get_map_object = function(map_def)
local object = {}
--Get the map type, and fail if none exists
local noise_map = maps[map_def.map_type]
--Choose function to load based on dimensions given
if map_def.dimensions == 3 then
object.get_noise = noise_map.get3d
else
object.get_noise = noise_map.get2d
end
--Use the map constructor to initialise
noise_map.construct(object,map_def)
return object
end
vcnlib.get_map_object = get_map_object
local register_map = function(map_def)
if not vcnlib.maps[map_def.name]
and map_def.get3d
and map_def.get2d
and map_def.construct then
vcnlib.maps[map_def.name] = map_def
end
end
vcnlib.register_map = register_map
|
local mapping
mapping = setmetatable({}, {
__call = function(_, invoke, modes)
if type(invoke) == 'function' then
local map = {}
for _, mode in ipairs(modes or { 'i' }) do
map[mode] = invoke
end
return map
end
return invoke
end,
})
---Invoke completion
---@param option cmp.CompleteParams
mapping.complete = function(option)
return function(fallback)
if not require('cmp').complete(option) then
fallback()
end
end
end
---Complete common string.
mapping.complete_common_string = function()
return function(fallback)
if not require('cmp').complete_common_string() then
fallback()
end
end
end
---Close current completion menu if it displayed.
mapping.close = function()
return function(fallback)
if not require('cmp').close() then
fallback()
end
end
end
---Abort current completion menu if it displayed.
mapping.abort = function()
return function(fallback)
if not require('cmp').abort() then
fallback()
end
end
end
---Scroll documentation window.
mapping.scroll_docs = function(delta)
return function(fallback)
if not require('cmp').scroll_docs(delta) then
fallback()
end
end
end
---Select next completion item.
mapping.select_next_item = function(option)
return function(fallback)
if not require('cmp').select_next_item(option) then
local release = require('cmp').core:suspend()
fallback()
vim.schedule(release)
end
end
end
---Select prev completion item.
mapping.select_prev_item = function(option)
return function(fallback)
if not require('cmp').select_prev_item(option) then
local release = require('cmp').core:suspend()
fallback()
vim.schedule(release)
end
end
end
---Confirm selection
mapping.confirm = function(option)
return function(fallback)
if not require('cmp').confirm(option) then
fallback()
end
end
end
return mapping
|
-----------------------------------
-- Area: Windurst Waters
-- NPC: Moreno-Toeno
-- Starts and Finishes Quest: Teacher's Pet
-- !pos
-----------------------------------
local ID = require("scripts/zones/Windurst_Waters/IDs")
require("scripts/globals/settings")
require("scripts/globals/keyitems")
require("scripts/globals/missions")
require("scripts/globals/quests")
require("scripts/globals/titles")
-----------------------------------
function onTrade(player, npc, trade)
if (player:getQuestStatus(WINDURST, tpz.quest.id.windurst.TEACHER_S_PET) >= 1 and trade:hasItemQty(847, 1) == true and trade:hasItemQty(4368, 1) == true and trade:getGil() == 0 and trade:getItemCount() == 2) then
player:startEvent(440, 250, 847, 4368) -- -- Quest Finish
end
end
function onTrigger(player, npc)
local teacherstatus = player:getQuestStatus(WINDURST, tpz.quest.id.windurst.TEACHER_S_PET)
if (player:getCurrentMission(WINDURST) == tpz.mission.id.windurst.VAIN and player:getCharVar("MissionStatus") == 0) then
player:startEvent(752, 0, tpz.ki.STAR_SEEKER)
elseif (player:getCurrentMission(WINDURST) == tpz.mission.id.windurst.VAIN and player:getCharVar("MissionStatus") >= 1) then
if (player:getCharVar("MissionStatus") < 4) then
player:startEvent(753)
elseif (player:getCharVar("MissionStatus") == 4) then
player:startEvent(758)
end
elseif (player:getCurrentMission(WINDURST) == tpz.mission.id.windurst.A_TESTING_TIME) then
local MissionStatus = player:getCharVar("MissionStatus")
local alreadyCompleted = player:hasCompletedMission(WINDURST, tpz.mission.id.windurst.A_TESTING_TIME)
if (MissionStatus == 0) then
if (alreadyCompleted == false) then
player:startEvent(182) -- First start at tahrongi
else
player:startEvent(687) -- Repeat at buburimu
end
elseif (MissionStatus == 1) then
start_time = player:getCharVar("testingTime_start_time")
seconds_passed = os.time() - start_time
-- one Vana'diel Day is 3456 seconds (2 day for repeat)
if ((alreadyCompleted == false and seconds_passed > 3456) or (alreadyCompleted and seconds_passed > 6912)) then
player:startEvent(202)
-- are we in the last game hour of the Vana'diel Day?
elseif (alreadyCompleted == false and seconds_passed >= 3312) then
killcount = player:getCharVar("testingTime_crea_count")
if (killcount >= 35) then
event = 201
elseif (killcount >= 30) then
event = 200
elseif (killcount >= 19) then
event = 199
else
event = 198
end
player:startEvent(event, 0, VanadielHour(), 1, killcount)
-- are we in the last game hour of the Vana'diel Day? REPEAT
elseif (alreadyCompleted and seconds_passed >= 6768) then
killcount = player:getCharVar("testingTime_crea_count")
if (killcount >= 35) then
event = 206
elseif (killcount >= 30) then
event = 209
else
event = 208
end
player:startEvent(event, 0, VanadielHour(), 1, killcount)
else
start_day = player:getCharVar("testingTime_start_day")
start_hour = player:getCharVar("testingTime_start_hour")
if (VanadielDayOfTheYear() == start_day) then
hours_passed = VanadielHour() - start_hour
elseif (VanadielDayOfTheYear() == start_day + 1) then
hours_passed = VanadielHour() - start_hour + 24
else
if (alreadyCompleted) then hours_passed = (24 - start_hour) + VanadielHour() + 24
else hours_passed = (24 - start_hour) + VanadielHour(); end
end
if (alreadyCompleted) then
player:startEvent(204, 0, 0, 0, 0, 0, VanadielHour(), 48 - hours_passed, 0)
else
player:startEvent(183, 0, VanadielHour(), 24 - hours_passed)
end
end
end
elseif (teacherstatus == QUEST_AVAILABLE) then
prog = player:getCharVar("QuestTeachersPet_prog")
if (prog == 0) then
player:startEvent(437) -- Before Quest
player:setCharVar("QuestTeachersPet_prog", 1)
elseif (prog == 1) then
player:startEvent(438, 0, 847, 4368) -- Quest Start
end
elseif (teacherstatus == QUEST_ACCEPTED) then
player:startEvent(439, 0, 847, 4368) -- Quest Reminder
elseif (player:getQuestStatus(WINDURST, tpz.quest.id.windurst.MAKING_THE_GRADE) == QUEST_ACCEPTED) then
player:startEvent(444) -- During Making the GRADE
else -- Will run through these iffame is not high enough for other quests
rand = math.random(1, 2)
if (rand == 1) then
player:startEvent(441) -- Standard Conversation 1
else
player:startEvent(469) -- Standard Conversation 2
end
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if (csid == 438 and option == 0) then
player:addQuest(WINDURST, tpz.quest.id.windurst.TEACHER_S_PET)
elseif (csid == 438 and option == 1) then
player:setCharVar("QuestTeachersPet_prog", 0)
elseif (csid == 440) then
player:addGil(GIL_RATE*250)
player:setCharVar("QuestTeachersPet_prog", 0)
player:tradeComplete(trade)
if (player:getQuestStatus(WINDURST, tpz.quest.id.windurst.TEACHER_S_PET) == QUEST_ACCEPTED) then
player:completeQuest(WINDURST, tpz.quest.id.windurst.TEACHER_S_PET)
player:addFame(WINDURST, 75)
else
player:addFame(WINDURST, 8)
end
elseif (csid == 182 or csid == 687) and option ~= 1 then -- start
player:addKeyItem(tpz.ki.CREATURE_COUNTER_MAGIC_DOLL)
player:messageSpecial(ID.text.KEYITEM_OBTAINED, tpz.ki.CREATURE_COUNTER_MAGIC_DOLL)
player:setCharVar("MissionStatus", 1)
player:setCharVar("testingTime_start_day", VanadielDayOfTheYear())
player:setCharVar("testingTime_start_hour", VanadielHour())
player:setCharVar("testingTime_start_time", os.time())
elseif (csid == 198 or csid == 199 or csid == 202 or csid == 208) then -- failed testing time
player:delKeyItem(tpz.ki.CREATURE_COUNTER_MAGIC_DOLL)
player:messageSpecial(ID.text.KEYITEM_OBTAINED + 1, tpz.ki.CREATURE_COUNTER_MAGIC_DOLL)
player:setCharVar("MissionStatus", 0)
player:setCharVar("testingTime_crea_count", 0)
player:setCharVar("testingTime_start_day", 0)
player:setCharVar("testingTime_start_hour", 0)
player:setCharVar("testingTime_start_time", 0)
player:delMission(WINDURST, tpz.mission.id.windurst.A_TESTING_TIME)
elseif (csid == 200 or csid == 201) then -- first time win
finishMissionTimeline(player, 1, csid, option)
player:setCharVar("testingTime_crea_count", 0)
player:setCharVar("testingTime_start_day", 0)
player:setCharVar("testingTime_start_hour", 0)
player:setCharVar("testingTime_start_time", 0)
elseif (csid == 209 or csid == 206) then -- succesfull repeat attempt (Buburimu).
finishMissionTimeline(player, 1, csid, option)
player:setCharVar("testingTime_crea_count", 0)
player:setCharVar("testingTime_start_day", 0)
player:setCharVar("testingTime_start_hour", 0)
player:setCharVar("testingTime_start_time", 0)
elseif (csid == 752) then
player:setCharVar("MissionStatus", 1)
player:addKeyItem(tpz.ki.STAR_SEEKER)
player:messageSpecial(ID.text.KEYITEM_OBTAINED, tpz.ki.STAR_SEEKER)
player:addTitle(tpz.title.FUGITIVE_MINISTER_BOUNTY_HUNTER)
elseif (csid == 758) then
finishMissionTimeline(player, 3, csid, option)
end
end
|
tools = {}
-- this defines the order of tools on the panel
toolslist = {"Brush", "Rectangle", "Select", "Camtrigger", "Room", "Project"}
Tool = class("Tool")
function Tool:disabled() end
function Tool:panel() end
function Tool:update() end
function Tool:draw() end
function Tool:mousepressed() end
function Tool:mousereleased() end
function Tool:mousemoved() end
-- tile panel mixin
local autolayout = {{0, 1, 3, 2, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27},
{4, 5, 7, 6, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39},
{12, 13, 15, 14, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51},
{8, 9, 11, 10, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63}}
TilePanelMx = {}
function TilePanelMx:tilePanel()
-- tiles
ui:layoutRow("dynamic", 25*global_scale, 2)
ui:label("Tiles:")
app.showGarbageTiles = ui:checkbox("Show garbage tiles", app.showGarbageTiles)
for j = 0, app.showGarbageTiles and 15 or 7 do
ui:layoutRow("static", 8*tms, 8*tms, 16)
for i = 0, 15 do
local n = i + j*16
if tileButton(n, app.currentTile == n and not app.autotile) then
if self.autotileEditO then
if app.autotile then
if self.autotileEditO >= 16 and n == 0 then
project.conf.autotiles[app.autotile][self.autotileEditO] = nil
else
project.conf.autotiles[app.autotile][self.autotileEditO] = n
end
end
updateAutotiles()
self.autotileEditO = nil
app.currentTile = project.conf.autotiles[app.autotile][15]
else
app.currentTile = n
app.autotile = nil
end
end
end
end
-- autotiles
ui:layoutRow("dynamic", 25*global_scale, 3)
ui:label("Autotiles:")
ui:spacing(1)
if ui:button("New Autotile") then
local auto = {[0] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
table.insert(project.conf.autotiles, auto)
updateAutotiles()
end
ui:layoutRow("static", 8*tms, 8*tms, #project.conf.autotiles)
for k, auto in ipairs(project.conf.autotiles) do
if tileButton(auto[5], app.autotile == k) then
app.currentTile = auto[15]
app.autotile = k
self.autotileEditO = nil
end
end
if app.autotile then
ui:layoutRow("dynamic", 25*global_scale, 3)
ui:label("Tileset: (click to edit)")
ui:spacing(1)
if ui:button("Delete Autotile") then
table.remove(project.conf.autotiles, app.autotile)
updateAutotiles()
app.autotile = math.max(1, app.autotile - 1)
end
end
-- check for missing autotile! can happen on undo/redo
if not project.conf.autotiles[app.autotile] then
app.autotile = nil
end
if app.autotile then
for r = 1, 4 do
ui:layoutRow("static", 8*tms, 8*tms, 16)
for i = 1, #autolayout[r] do
local o = autolayout[r][i]
if tileButton(project.conf.autotiles[app.autotile][o] or 0, self.autotileEditO == o, o) then
self.autotileEditO = o
end
end
end
ui:layoutRow("dynamic", 50*global_scale, 1)
ui:label("Autotile draws with the 16 tiles on the left, connecting them to each other and to any of the extra tiles on the right. This allows connecting to other deco tiles and tiles from other tilesets. Also works when erasing.", "wrap")
end
end
-- Brush
tools.Brush = Tool:extend("Brush"):with(TilePanelMx)
function tools.Brush:panel()
self:tilePanel()
end
function tools.Brush:update(dt)
if not ui:windowIsAnyHovered()
and not love.keyboard.isDown("lalt")
and not app.suppressMouse
and (love.mouse.isDown(1) or love.mouse.isDown(2)) then
local n = app.currentTile
if love.mouse.isDown(2) then
n = 0
end
local ti, tj = mouseOverTile()
if ti then
local room = activeRoom()
activeRoom().data[ti][tj] = n
if app.autotile then
autotileWithNeighbors(activeRoom(), ti, tj, app.autotile)
end
end
end
end
function tools.Brush:draw()
drawMouseOverTile(nil, app.currentTile)
end
-- Rectangle
tools.Rectangle = Tool:extend("Rectangle"):with(TilePanelMx)
function tools.Rectangle:panel()
self:tilePanel()
end
function tools.Rectangle:draw()
local ti, tj = mouseOverTile()
if not self.rectangleI then
drawMouseOverTile(nil, app.currentTile)
elseif ti then
local i, j, w, h = rectCont2Tiles(ti, tj, self.rectangleI, self.rectangleJ)
drawColoredRect(activeRoom(), i*8, j*8, w*8, h*8, {0, 1, 0.5}, false)
end
end
function tools.Rectangle:mousepressed(x, y, button)
local ti, tj = mouseOverTile()
if button == 1 or button == 2 then
if ti then
self.rectangleI, self.rectangleJ = ti, tj
end
end
end
function tools.Rectangle:mousereleased(x, y, button)
local ti, tj = mouseOverTile()
if ti and self.rectangleI then
local room = activeRoom()
local n = app.currentTile
if button == 2 then
n = 0
end
local i0, j0, w, h = rectCont2Tiles(self.rectangleI, self.rectangleJ, ti, tj)
for i = i0, i0 + w - 1 do
for j = j0, j0 + h - 1 do
room.data[i][j] = n
end
end
if app.autotile then
for i = i0, i0 + w - 1 do
autotileWithNeighbors(room, i, j0, app.autotile)
autotileWithNeighbors(room, i, j0 + h - 1, app.autotile)
end
for j = j0 + 1, j0 + h - 2 do
autotileWithNeighbors(room, i0, j, app.autotile)
autotileWithNeighbors(room, i0 + w - 1, j, app.autotile)
end
end
end
self.rectangleI, self.rectangleJ = nil, nil
end
-- Selection
tools.Select = Tool:extend("Selection")
function tools.Select:disabled()
if project.selection then
placeSelection()
end
end
function tools.Select:draw()
local ti, tj = mouseOverTile()
if not self.selectTileI then
drawMouseOverTile()
elseif ti then
local i, j, w, h = rectCont2Tiles(ti, tj, self.selectTileI, self.selectTileJ)
drawColoredRect(activeRoom(), i*8, j*8, w*8, h*8, {0, 1, 0.5}, false)
end
end
function tools.Select:mousepressed(x, y, button)
local ti, tj = mouseOverTile()
local mx, my = fromScreen(x, y)
if button == 1 then
if not project.selection then
if ti then
self.selectTileI, self.selectTileJ = ti, tj
end
else
self.selectionMoveX, self.selectionMoveY = mx - project.selection.x, my - project.selection.y
self.selectionStartX, self.selectionStartY = project.selection.x, project.selection.y
end
end
end
function tools.Select:mousereleased(x, y, button)
local ti, tj = mouseOverTile()
if ti and self.selectTileI then
placeSelection()
select(ti, tj, self.selectTileI, self.selectTileJ)
end
if project.selection and self.selectionMoveX then
if project.selection.x == self.selectionStartX and project.selection.y == self.selectionStartY then
placeSelection()
end
end
self.selectTileI, self.selectTileJ = nil, nil
self.selectionMoveX, self.selectionMoveY = nil, nil
end
function tools.Select:mousemoved(x, y, dx, dy)
local mx, my = fromScreen(x, y)
if self.selectionMoveX and project.selection then
project.selection.x = roundto8(mx - self.selectionMoveX)
project.selection.y = roundto8(my - self.selectionMoveY)
end
end
-- Camera Trigger
tools.Camtrigger = Tool:extend("Camera Trigger")
function tools.Camtrigger:panel()
ui:layoutRow("dynamic", 25*global_scale, 1)
app.showCameraTriggers = ui:checkbox("Show camera triggers when not using the tool",app.showCameraTriggers)
if selectedTrigger() then
local trigger = selectedTrigger()
local editX = {value = trigger.off_x}
local editY = {value = trigger.off_y}
ui:layoutRow("dynamic",25*global_scale,4)
ui:label("x offset","centered")
ui:edit("simple", editX)
ui:label("y offset","centered")
ui:edit("simple", editY)
trigger.off_x = editX.value
trigger.off_y = editY.value
end
end
function tools.Camtrigger:draw()
local ti, tj = mouseOverTile()
if not self.camtriggerI then
drawMouseOverTile({1,0.75,0})
elseif ti then
local i, j, w, h = rectCont2Tiles(ti, tj, self.camtriggerI, self.camtriggerJ)
drawColoredRect(activeRoom(), i*8, j*8, w*8, h*8, {1,0.75,0}, false)
end
end
function tools.Camtrigger:mousepressed(x, y, button)
local ti, tj = mouseOverTile()
if not ti then return end
local hovered=hoveredTriggerN()
if button == 1 then
if love.keyboard.isDown("lctrl") then
if not selectedTrigger() and hovered then
app.selectedCamtriggerN = hovered
end
if selectedTrigger() then
self.camtriggerMoveI, self.camtriggerMoveJ = ti, tj
end
else
local hovered = hoveredTriggerN()
if selectedTrigger() then
app.selectedCamtriggerN = nil
--deselect
elseif hovered then
app.selectedCamtriggerN = hovered
else
self.camtriggerI, self.camtriggerJ = ti, tj
end
end
elseif button == 2 and love.keyboard.isDown("lctrl") then
if not selectedTrigger() and hovered then
app.selectedCamtriggerN = hovered
end
if selectedTrigger() then
self.camtriggerSideI = sign(ti - selectedTrigger().x - selectedTrigger().w/2)
self.camtriggerSideJ = sign(tj - selectedTrigger().y - selectedTrigger().h/2)
end
-- app.camtriggerSideI,app.camtriggerSideJ=ti,tj
end
end
function tools.Camtrigger:mousemoved(x,y)
local ti,tj = mouseOverTile()
if not ti then return end
local trigger = selectedTrigger()
if self.camtriggerMoveI then
trigger.x=trigger.x+(ti-self.camtriggerMoveI)
trigger.y=trigger.y+(tj-self.camtriggerMoveJ)
self.camtriggerMoveI,self.camtriggerMoveJ=ti,tj
end
if self.camtriggerSideI then
if self.camtriggerSideI < 0 then
local newx = math.min(ti, trigger.x + trigger.w-1)
trigger.w = trigger.x - newx + trigger.w
trigger.x = newx
else
trigger.w = math.max(ti - trigger.x + 1, 1)
end
if self.camtriggerSideJ < 0 then
local newy = math.min(tj, trigger.y + trigger.h - 1)
trigger.h = trigger.y - newy + trigger.h
trigger.y = newy
else
trigger.h = math.max(tj - trigger.y + 1, 1)
end
end
end
function tools.Camtrigger:mousereleased(x, y, button)
local ti, tj = mouseOverTile()
if ti and self.camtriggerI then
local room = activeRoom()
local i0, j0, w, h = rectCont2Tiles(self.camtriggerI, self.camtriggerJ, ti, tj)
local trigger={x=i0,y=j0,w=w,h=h,off_x="0",off_y="0"}
table.insert(room.camtriggers, trigger)
app.selectedCamtriggerN = #room.camtriggers
end
self.camtriggerI, self.camtriggerJ = nil, nil
self.camtriggerMoveI, self.camtriggerMoveJ = nil, nil
self.camtriggerSideI, self.camtriggerSideJ = nil, nil
end
-- Room Properties
tools.Room = Tool:extend("Room")
function tools.Room:panel()
ui:layoutRow("static", 25*global_scale, 100*global_scale, 2)
if ui:button("New Room") then
local x, y = fromScreen(app.W/3, app.H/3)
local room = newRoom(roundto8(x), roundto8(y), 16, 16)
room.title = ""
table.insert(project.rooms, room)
app.room = #project.rooms
app.roomAdded = true
end
if ui:button("Delete Room") then
if activeRoom() then
table.remove(project.rooms, app.room)
if not activeRoom() then
app.room = #project.rooms
end
end
end
local room = activeRoom()
if room then
local param_n = math.max(#project.conf.param_names,#room.params)
local x,y=div8(room.x),div8(room.y)
local fits_on_map=x>=0 and x+room.w<=128 and y>=0 and y+room.h<=64
ui:layoutRow("dynamic",25*global_scale,1)
if not fits_on_map then
local style={}
for k,v in pairs({"text normal", "text hover", "text active"}) do
style[v]="#707070"
end
for k,v in pairs({"normal", "hover", "active"}) do
style[v]=checkmarkWithBg -- show both selected and unselected as having a check to avoid nukelear limitations
-- kinda hacky but it works decently enough
end
ui:stylePush({['checkbox']=style})
else
ui:stylePush({})
end
room.hex = ui:checkbox("Store as hex string", room.hex or not fits_on_map)
ui:stylePop()
ui:layoutRow("dynamic", 25*global_scale, 5)
ui:label("Level Exits:")
for _,v in pairs({"left","bottom","right","top"}) do
room.exits[v] = ui:checkbox(v, room.exits[v])
end
for i=1, param_n do
ui:layoutRow("dynamic", 25*global_scale, {0.25,0.75} )
ui:label(project.conf.param_names[i] or "")
local t = {value=room.params[i] or 0}
ui:edit("field", t)
room.params[i] = t.value
end
end
end
tools.Project = Tool:extend("Project")
function tools.Project:panel()
ui:layoutRow("static", 25*global_scale, 100*global_scale, 3)
if ui:button("Open") then
openFile()
end
if ui:button("Save") then
saveFile(false)
end
if ui:button("Save as...") then
saveFile(true)
end
ui:layoutRow("dynamic", 25*global_scale, {0.8, 0.1, 0.1})
ui:label("Room parameter names:")
if ui:button("+") then
table.insert(project.conf.param_names, "")
end
if ui:button("-") then
table.remove(project.conf.param_names, #project.param_names)
end
for i = 1, #project.conf.param_names do
ui:layoutRow("dynamic", 25*global_scale, 1)
local t = {value=project.conf.param_names[i]}
ui:edit("field", t)
project.conf.param_names[i] = t.value
end
end
|
object_tangible_furniture_flooring_tile_frn_flooring_tile_s41 = object_tangible_furniture_flooring_tile_shared_frn_flooring_tile_s41:new {
}
ObjectTemplates:addTemplate(object_tangible_furniture_flooring_tile_frn_flooring_tile_s41, "object/tangible/furniture/flooring/tile/frn_flooring_tile_s41.iff")
|
ITEM.name = "Длинный лук"
ITEM.desc = "Позволяет стрелять на большие расстояния."
ITEM.class = "nut_bow_long"
ITEM.weaponCategory = "primary"
ITEM.price = 250
ITEM.category = "Оружие"
ITEM.model = "models/morrowind/artifacts/longbow/w_bow_of_shadows.mdl"
ITEM.width = 6
ITEM.height = 2
ITEM.iconCam = {
pos = Vector(-5.689178943634, 68.602279663086, -2.0434617996216),
ang = Angle(0, 270, -103.06331634521),
fov = 45
}
ITEM.type = "2h"
ITEM.permit = "melee"
ITEM.damage = {1, 7}
ITEM.pacData = {[1] = {
["children"] = {
[1] = {
["children"] = {
[1] = {
["children"] = {
},
["self"] = {
["Event"] = "weapon_class",
["Arguments"] = "nut_bow_long",
["UniqueID"] = "4011003967",
["ClassName"] = "event",
},
},
},
["self"] = {
["Angles"] = Angle(1.5164324045181, 100.70363616943, 93.428733825684),
["UniqueID"] = "732790205",
["Position"] = Vector(-6.0897827148438, -3.43212890625, 5.567626953125),
["EditorExpand"] = true,
["Bone"] = "spine 4",
["Model"] = "models/morrowind/artifacts/longbow/w_bow_of_shadows.mdl",
["ClassName"] = "model",
},
},
},
["self"] = {
["EditorExpand"] = true,
["UniqueID"] = "2083764954",
["ClassName"] = "group",
["Name"] = "my outfit",
["Description"] = "add parts to me!",
},
},}
|
---------------------------------------------------
-- Somnolence
---------------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
require("scripts/globals/magic")
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0
end
function onPetAbility(target, pet, skill)
local dmg = 10 + pet:getMainLvl() * 2
local resist = applyPlayerResistance(pet,-1,target, 0, tpz.skill.ELEMENTAL_MAGIC, tpz.magic.ele.DARK)
local duration = 120
dmg = dmg*resist
dmg = mobAddBonuses(pet,spell,target,dmg, tpz.magic.ele.DARK)
dmg = finalMagicAdjustments(pet,target,spell,dmg)
if (resist < 0.15) then --the gravity effect from this ability is more likely to land than Tail Whip
resist = 0
end
duration = duration * resist
if (duration > 0 and target:hasStatusEffect(tpz.effect.WEIGHT) == false) then
target:addStatusEffect(tpz.effect.WEIGHT, 50, 0, duration)
end
return dmg
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.