Merge branch 'main' into feature/reports-plugin

This commit is contained in:
Cooldude2606 authored and GitHub committed 2026-09-26 23:27:12 +01:00
commit e47f41d440
103 files changed
+4492 -4129

No files matched your search

@@ -1,807 +0,0 @@
--[[-- Control Module - vlayer
- Adds a virtual layer to store power to save space.
@control vlayer
@alias vlayer
]]
local ExpUtil = require("modules/exp_util")
local Storage = require("modules/exp_util/storage")
local Event = require("modules/exp_legacy/utils/event") --- @dep utils.event
local config = require("modules.exp_legacy.config.vlayer") --- @dep config.vlayer
local mega = 1000000
local vlayer = {}
local vlayer_data = {
entity_interfaces = {
energy = {}, --- @type LuaEntity[]
circuit = {}, --- @type LuaEntity[]
storage_input = {}, --- @type LuaEntity[]
storage_output = {}, --- @type LuaEntity[]
},
properties = {
total_surface_area = 0,
used_surface_area = 0,
total_production = 0,
production = 0,
discharge = 0,
capacity = 0,
},
storage = {
items = {}, --- @type table<string, number>
power_items = {}, --- @type table<string, { value: number, count: number }>
energy = 0,
unallocated = {}, --- @type table<string, number>
},
surface = table.deep_copy(config.surface),
}
Storage.register(vlayer_data, function(tbl)
vlayer_data = tbl
end)
for name, properties in pairs(config.allowed_items) do
properties.modded = false
if properties.power then
vlayer_data.storage.power_items[name] = {
value = assert(properties.fuel_value) * 1000000,
count = 0,
}
end
end
-- For all modded items, create a config for them
for item_name, properties in pairs(config.modded_items) do
local base_properties = config.allowed_items[properties.base_game_equivalent]
local m = properties.multiplier
config.allowed_items[item_name] = {
starting_value = properties.starting_value or 0,
required_area = base_properties.required_area or 0,
surface_area = (base_properties.surface_area or 0) * m,
production = (base_properties.production or 0) * m,
capacity = (base_properties.capacity or 0) * m,
modded = true,
}
end
--- Get all items in storage, do not modify
-- @treturn table a dictionary of all items stored in the vlayer
function vlayer.get_items()
return vlayer_data.storage.items
end
--- Get all unallocated items in storage
-- @treturn table a dictionary of all unallocated items stored in the vlayer
function vlayer.get_unallocated_items()
return vlayer_data.storage.unallocated
end
--- Get all allocated items in storage
-- @treturn table a dictionary of all allocated items stored in the vlayer
function vlayer.get_allocated_items()
local r = {}
for k, v in pairs(vlayer_data.storage.items) do
r[k] = v
if vlayer_data.storage.unallocated[k] then
r[k] = r[k] - vlayer_data.storage.unallocated[k]
end
end
return r
end
--- Get the actual defecit of land
local function get_actual_land_defecit()
local n = vlayer_data.properties.total_surface_area - vlayer_data.properties.used_surface_area
for k, v in pairs(vlayer.get_unallocated_items()) do
n = n - (config.allowed_items[k].required_area * v)
end
return n
end
--- Get interface counts
-- @treturn table a dictionary of the vlayer interface counts
function vlayer.get_interface_counts()
local interfaces = vlayer_data.entity_interfaces
return {
energy = #interfaces.energy,
circuit = #interfaces.circuit,
storage_input = #interfaces.storage_input,
storage_output = #interfaces.storage_output,
}
end
--- Get interfaces
-- @treturn table a dictionary of the vlayer interfaces
function vlayer.get_interfaces()
local interfaces = vlayer_data.entity_interfaces
return {
energy = interfaces.energy,
circuit = interfaces.circuit,
storage_input = interfaces.storage_input,
storage_output = interfaces.storage_output,
}
end
--[[
25,200 / 420 s
昼 210秒 ソーラー効率100%
夕方 84秒 1秒ごとにソーラー発電量が約1.2%ずつ下がり、やがて0%になる
夜 42秒 ソーラー発電量が0%になる
朝方 84秒 1秒ごとにソーラー発電量が約1.2%ずつ上がり、やがて100%になる
(surface.dawn) 0.75 18,900 Day 12,600 210s
0.00 0 Noon
(surface.dusk) 0.25 6,300 Sunset 5,040 84s
(surface.evening) 0.45 11,340 Night 2,520 42s
(surface.morning) 0.55 13,860 Sunrise 5,040 84s
]]
--- Get the power multiplier based on the surface time
local function get_production_multiplier()
local mul = vlayer_data.surface.solar_power_multiplier
local surface = vlayer_data.surface
if surface.always_day then
-- Surface is always day, so full production is used
return mul
end
if surface.darkness then
-- We are using a real surface, our config does not contain "darkness"
local brightness = 1 - surface.darkness
if brightness >= surface.min_brightness then
return mul * (brightness - surface.min_brightness) / (1 - surface.min_brightness)
else
return 0
end
end
-- Caused by using a set config rather than a surface
local tick = game.tick % surface.ticks_per_day
local daytime = tick / surface.ticks_per_day
surface.daytime = daytime
if daytime <= surface.dusk then -- Noon to Sunset
return mul
elseif daytime <= surface.evening then -- Sunset to Night
return mul * (1 - ((daytime - surface.dusk) / (surface.evening - surface.dusk)))
elseif daytime <= surface.morning then -- Night to Sunrise
return 0
elseif daytime <= surface.dawn then -- Sunrise to Morning
return mul * ((surface.daytime - surface.morning) / (surface.dawn - surface.morning))
else -- Morning to Noon
return mul
end
end
--- Get the sustained power multiplier, this needs improving
local function get_sustained_multiplier()
local mul = vlayer_data.surface.solar_power_multiplier
local surface = vlayer_data.surface
if surface.always_day then
-- Surface is always day, so full production is used
return mul
end
-- For nauvis vanilla: 210s + (1/2 x (84s + 84s))
local day_duration = 1 - surface.dawn + surface.dusk
local sunset_duration = surface.evening - surface.dusk
local sunrise_duration = surface.dawn - surface.morning
return mul * (day_duration + (0.5 * (sunset_duration + sunrise_duration)))
end
--- Internal, Allocate items in the vlayer, this will increase the property values of the vlayer such as production and capacity
-- Does not increment item storage, so should not be called before insert_item unless during init
-- Does not validate area requirements, so checks must be performed before calling this function
-- Accepts negative count for deallocating items
-- @tparam string item_name The name of the item to allocate
-- @tparam number count The count of the item to allocate
function vlayer.allocate_item(item_name, count)
local item_properties = config.allowed_items[item_name]
assert(item_properties, "Item not allowed in vlayer: " .. tostring(item_name))
if item_properties.production then
local nc = item_properties.production * count
vlayer_data.properties.production = vlayer_data.properties.production + nc
vlayer_data.properties.total_production = vlayer_data.properties.total_production + nc
end
if item_properties.capacity then
vlayer_data.properties.capacity = vlayer_data.properties.capacity + item_properties.capacity * count
end
if item_properties.discharge then
vlayer_data.properties.discharge = vlayer_data.properties.discharge + item_properties.discharge * count
end
if item_properties.surface_area then
vlayer_data.properties.total_surface_area = vlayer_data.properties.total_surface_area + item_properties.surface_area * count
end
if item_properties.required_area and item_properties.required_area > 0 then
vlayer_data.properties.used_surface_area = vlayer_data.properties.used_surface_area + item_properties.required_area * count
end
end
function vlayer.unable_alloc_item_pwr_calc(item_name, count)
local item_properties = config.allowed_items[item_name]
if item_properties.production then
vlayer_data.properties.total_production = vlayer_data.properties.total_production + item_properties.production * count
end
end
-- For all allowed items, setup their starting values, default 0
for item_name, properties in pairs(config.allowed_items) do
vlayer_data.storage.items[item_name] = properties.starting_value or 0
if properties.required_area and properties.required_area > 0 then
vlayer_data.storage.unallocated[item_name] = 0
end
vlayer.allocate_item(item_name, properties.starting_value)
end
--- Insert an item into the vlayer, this will increment its count in storage and allocate it if possible
-- @tparam string item_name The name of the item to insert
-- @tparam number count The count of the item to insert
function vlayer.insert_item(item_name, count)
local item_properties = config.allowed_items[item_name]
assert(item_properties, "Item not allowed in vlayer: " .. tostring(item_name))
vlayer_data.storage.items[item_name] = vlayer_data.storage.items[item_name] + count
if not config.unlimited_surface_area and item_properties.required_area and item_properties.required_area > 0 then
-- Calculate how many can be allocated
local surplus_area = vlayer_data.properties.total_surface_area - vlayer_data.properties.used_surface_area
local allocate_count = math.min(count, math.floor(surplus_area / item_properties.required_area))
if allocate_count > 0 then
vlayer.allocate_item(item_name, allocate_count)
end
local unallocated = count - allocate_count
vlayer_data.storage.unallocated[item_name] = vlayer_data.storage.unallocated[item_name] + unallocated
vlayer.unable_alloc_item_pwr_calc(item_name, unallocated)
else
vlayer.allocate_item(item_name, count)
end
end
--- Remove an item from the vlayer, this will decrement its count in storage and prioritise unallocated items over deallocation
-- Can not always fulfil the remove request for items which provide surface area, therefore returns the amount actually removed
-- @tparam string item_name The name of the item to remove
-- @tparam number count The count of the item to remove
-- @treturn number The count of the item actually removed
function vlayer.remove_item(item_name, count)
local item_properties = config.allowed_items[item_name]
assert(item_properties, "Item not allowed in vlayer: " .. tostring(item_name))
local remove_unallocated = 0
if not config.unlimited_surface_area and item_properties.required_area and item_properties.required_area > 0 then
-- Remove from the unallocated storage first
remove_unallocated = math.min(count, vlayer_data.storage.unallocated[item_name])
if remove_unallocated > 0 then
vlayer_data.storage.items[item_name] = vlayer_data.storage.items[item_name] - count
vlayer_data.storage.unallocated[item_name] = vlayer_data.storage.unallocated[item_name] - count
end
-- Check if any more items need to be removed
count = count - remove_unallocated
if count == 0 then
return remove_unallocated
end
end
-- Calculate the amount to remove based on items in storage
local remove_count = math.min(count, vlayer_data.storage.items[item_name])
if item_properties.surface_area and item_properties.surface_area > 0 then
-- If the item provides surface area then it has additional limitations
local surplus_area = vlayer_data.properties.total_surface_area - vlayer_data.properties.used_surface_area
remove_count = math.min(remove_count, math.floor(surplus_area / item_properties.surface_area))
if remove_count <= 0 then
return remove_unallocated
end
end
-- Remove the item from allocated storage
vlayer_data.storage.items[item_name] = vlayer_data.storage.items[item_name] - remove_count
vlayer.allocate_item(item_name, -remove_count)
return remove_unallocated + remove_count
end
--- Create a new storage input interface
-- @tparam LuaSurface surface The surface to place the interface onto
-- @tparam MapPosition position The position on the surface to place the interface at
-- @tparam[opt] LuaPlayer player The player to show as the last user of the interface
-- @treturn LuaEntity The entity that was created for the interface
function vlayer.create_input_interface(surface, position, circuit, last_user)
local interface = surface.create_entity{ name = "storage-chest", position = position, force = "neutral" }
interface.storage_filter = { name = "deconstruction-planner", quality = "normal" }
table.insert(vlayer_data.entity_interfaces.storage_input, interface)
if last_user then
interface.last_user = last_user
end
if circuit then
for k, _ in pairs(circuit) do
for _, v in pairs(circuit[k]) do
interface.connect_neighbour{ wire = defines.wire_type[k], target_entity = v }
end
end
end
interface.destructible = false
interface.minable_flag = false
interface.operable = true
return interface
end
--- Handle all input interfaces, will take their contents and insert it into the vlayer storage
local function handle_input_interfaces()
for index, interface in pairs(vlayer_data.entity_interfaces.storage_input) do
if not interface.valid then
vlayer_data.entity_interfaces.storage_input[index] = nil
else
local inventory = assert(interface.get_inventory(defines.inventory.chest))
for _, v in pairs(inventory.get_contents()) do
if config.allowed_items[v.name] then
--[[
there are no quality support currently.
so instead, using the stats projection value for higher quality.
]]
local count_deduct
local count_add
if prototypes.quality[v.quality].level == 0 then
count_deduct = v.count
count_add = v.count
elseif prototypes.quality[v.quality].level > 0 and v.count >= 10 then
local batch = math.floor(v.count / 10)
count_deduct = batch * 10
count_add = batch * (10 + (prototypes.quality[v.quality].level * 3))
end
if count_deduct and count_add then
if config.allowed_items[v.name].modded then
local modded_item = assert(config.modded_items[v.name])
if config.modded_auto_downgrade then
vlayer.insert_item(modded_item.base_game_equivalent, count_add * modded_item.multiplier)
else
vlayer.insert_item(v.name, count_add)
end
else
if vlayer_data.storage.power_items[v.name] then
vlayer_data.storage.power_items[v.name].count = vlayer_data.storage.power_items[v.name].count + count_add
else
vlayer.insert_item(v.name, count_add)
end
end
inventory.remove{ name = v.name, count = count_deduct, quality = v.quality }
end
end
end
end
end
end
--- Create a new storage output interface
-- @tparam LuaSurface surface The surface to place the interface onto
-- @tparam MapPosition position The position on the surface to place the interface at
-- @tparam[opt] LuaPlayer player The player to show as the last user of the interface
-- @treturn LuaEntity The entity that was created for the interface
function vlayer.create_output_interface(surface, position, circuit, last_user)
local interface = surface.create_entity{ name = "requester-chest", position = position, force = "neutral" }
table.insert(vlayer_data.entity_interfaces.storage_output, interface)
if last_user then
interface.last_user = last_user
end
if circuit then
for k, _ in pairs(circuit) do
for _, v in pairs(circuit[k]) do
interface.connect_neighbour{ wire = defines.wire_type[k], target_entity = v }
end
end
end
interface.destructible = false
interface.minable_flag = false
interface.operable = true
return interface
end
--- Handle all output interfaces, will take their requests and remove it from the vlayer storage
local function handle_output_interfaces()
for index, interface in pairs(vlayer_data.entity_interfaces.storage_output) do
if not interface.valid then
vlayer_data.entity_interfaces.storage_output[index] = nil
else
local inventory = assert(interface.get_inventory(defines.inventory.chest))
local inventory_request_sections = assert(interface.get_logistic_sections()).sections
for i = 1, #inventory_request_sections do
for _, v in pairs(inventory_request_sections[i].filters) do
if v.value and config.allowed_items[v.value.name] then
local current_amount = inventory.get_item_count(v.value.name)
local request_amount = math.min(assert(v.min) - current_amount, vlayer_data.storage.items[v.value.name])
if request_amount > 0 and inventory.can_insert{ name = v.value.name, count = request_amount } then
local removed_item_count = vlayer.remove_item(v.value.name, request_amount)
if removed_item_count > 0 then
inventory.insert{ name = v.value.name, count = removed_item_count, quality = "normal" }
end
end
end
end
end
end
end
end
--- Handle the unallocated items because more surface area may have been added
local function handle_unallocated()
-- unallocated cant happen when its unlimited
if config.unlimited_surface_area then
return
end
-- Get the total unallocated area so items can be allocated in equal amounts
local unallocated_area = 0
for item_name, count in pairs(vlayer_data.storage.unallocated) do
local item_properties = config.allowed_items[item_name]
unallocated_area = unallocated_area + item_properties.required_area * count
end
if unallocated_area == 0 then
return
end
-- Allocate items in an equal distribution
local surplus_area = vlayer_data.properties.total_surface_area - vlayer_data.properties.used_surface_area
for item_name, count in pairs(vlayer_data.storage.unallocated) do
local allocation_count = math.min(count, math.floor(count * surplus_area / unallocated_area))
if allocation_count > 0 then
vlayer_data.storage.unallocated[item_name] = vlayer_data.storage.unallocated[item_name] - allocation_count
vlayer.allocate_item(item_name, allocation_count)
vlayer.unable_alloc_item_pwr_calc(item_name, -allocation_count)
end
end
end
--- Get the statistics for the vlayer
function vlayer.get_statistics()
local vdp = vlayer_data.properties.production * mega
local gdm = get_production_multiplier()
local gsm = get_sustained_multiplier()
local gald = get_actual_land_defecit()
return {
total_surface_area = vlayer_data.properties.total_surface_area,
used_surface_area = vlayer_data.properties.used_surface_area,
remaining_surface_area = gald,
surface_area = vlayer_data.properties.total_surface_area - gald,
production_multiplier = gdm,
energy_max = vdp,
energy_production = vdp * gdm,
energy_total_production = vlayer_data.properties.total_production * gsm * mega,
energy_sustained = vdp * gsm,
energy_capacity = vlayer_data.properties.capacity * mega,
energy_storage = vlayer_data.storage.energy,
}
end
--- add or reduce vlayer power
--- @param power number
--- @return number
function vlayer.energy_changed(power)
local new_value = vlayer_data.storage.energy + power
vlayer_data.storage.energy = new_value
return new_value
end
--- Circuit signals used for the statistics
function vlayer.get_circuits()
return {
total_surface_area = "signal-A",
used_surface_area = "signal-U",
remaining_surface_area = "signal-R",
production_multiplier = "signal-M",
energy_production = "signal-P",
energy_sustained = "signal-S",
energy_capacity = "signal-C",
energy_storage = "signal-E",
}
end
local vlayer_circuits_string = ""
for key, value in pairs(vlayer.get_circuits()) do
vlayer_circuits_string = vlayer_circuits_string .. string.format("[virtual-signal=%s] = %s\n", value, key:gsub("_", " "))
end
--- Create a new circuit interface
-- @tparam LuaSurface surface The surface to place the interface onto
-- @tparam MapPosition position The position on the surface to place the interface at
-- @tparam[opt] LuaPlayer player The player to show as the last user of the interface
-- @treturn LuaEntity The entity that was created for the interface
function vlayer.create_circuit_interface(surface, position, circuit, last_user)
local interface = surface.create_entity{ name = "constant-combinator", position = position, force = "neutral" }
table.insert(vlayer_data.entity_interfaces.circuit, interface)
if last_user then
interface.last_user = last_user
end
if circuit then
for k, _ in pairs(circuit) do
for _, v in pairs(circuit[k]) do
interface.connect_neighbour{ wire = defines.wire_type[k], target_entity = v }
end
end
end
interface.destructible = false
interface.minable_flag = false
interface.operable = true
return interface
end
--- Handle all circuit interfaces, updating their signals to match the vlayer statistics
local function handle_circuit_interfaces()
local stats = vlayer.get_statistics()
for index, interface in pairs(vlayer_data.entity_interfaces.circuit) do
if not interface.valid then
vlayer_data.entity_interfaces.circuit[index] = nil
else
local control = interface.get_or_create_control_behavior() --[[@as LuaConstantCombinatorControlBehavior]]
if control.sections_count == 0 then
control.add_section()
end
local circuit_oc = assert(control.sections[1])
local signal_index = 1
local circuit = vlayer.get_circuits()
-- Set the virtual signals based on the vlayer stats
for stat_name, signal_name in pairs(circuit) do
if stat_name:find("energy") then
circuit_oc.set_slot(signal_index, { value = { type = "virtual", name = signal_name, quality = "normal" }, min = math.floor(stats[stat_name] / mega) })
elseif stat_name == "production_multiplier" then
circuit_oc.set_slot(signal_index, { value = { type = "virtual", name = signal_name, quality = "normal" }, min = math.floor(stats[stat_name] * 10000) })
else
circuit_oc.set_slot(signal_index, { value = { type = "virtual", name = signal_name, quality = "normal" }, min = math.floor(stats[stat_name]) })
end
signal_index = signal_index + 1
end
-- Set the item signals based on stored items
for item_name, count in pairs(vlayer_data.storage.items) do
if prototypes.item[item_name] and count > 0 then
local existing_index = circuit_oc.set_slot(signal_index, { value = { type = "item", name = item_name, quality = "normal" }, min = count })
if existing_index then
circuit_oc.clear_slot(existing_index)
circuit_oc.set_slot(signal_index, { value = { type = "item", name = item_name, quality = "normal" }, min = count })
end
signal_index = signal_index + 1
end
end
-- Clear remaining signals to prevent outdated values being present (caused by count > 0 check)
for clear_index = signal_index, #circuit do
if not circuit_oc.get_slot(clear_index).value then
break -- There are no more signals to clear
end
circuit_oc.clear_slot(clear_index)
end
interface.combinator_description = vlayer_circuits_string
end
end
end
--- Create a new energy interface
-- @tparam LuaSurface surface The surface to place the interface onto
-- @tparam MapPosition position The position on the surface to place the interface at
-- @tparam[opt] LuaPlayer player The player to show as the last user of the interface
-- @treturn LuaEntity The entity that was created for the interface, or nil if it could not be created
function vlayer.create_energy_interface(surface, position, last_user)
if not surface.can_place_entity{ name = "electric-energy-interface", position = position } then
return nil
end
local interface = surface.create_entity{ name = "electric-energy-interface", position = position, force = "neutral" }
table.insert(vlayer_data.entity_interfaces.energy, interface)
if last_user then
interface.last_user = last_user
end
interface.destructible = false
interface.minable_flag = false
interface.operable = false
interface.electric_buffer_size = 0
interface.power_production = 0
interface.power_usage = 0
interface.energy = 0
return interface
end
--- Handle all energy interfaces as well as the energy storage
local function handle_energy_interfaces()
-- Add the newly produced power
local production = vlayer_data.properties.production * mega * (config.update_tick_energy / 60)
vlayer_data.storage.energy = vlayer_data.storage.energy + math.floor(production * get_production_multiplier())
-- Calculate how much power is present in the network, that is storage + all interfaces
if #vlayer_data.entity_interfaces.energy > 0 then
local available_energy = vlayer_data.storage.energy
for index, interface in pairs(vlayer_data.entity_interfaces.energy) do
if not interface.valid then
vlayer_data.entity_interfaces.energy[index] = nil
else
available_energy = available_energy + interface.energy
end
end
-- Distribute the energy between all interfaces
local discharge_rate = 2 * (production + vlayer_data.properties.discharge * mega) / #vlayer_data.entity_interfaces.energy
local fill_to = math.min(discharge_rate, math.floor(available_energy / #vlayer_data.entity_interfaces.energy))
for _, interface in pairs(vlayer_data.entity_interfaces.energy) do
interface.electric_buffer_size = math.max(discharge_rate, interface.energy) -- prevent energy loss
local delta = fill_to - interface.energy -- positive means storage to interface
vlayer_data.storage.energy = vlayer_data.storage.energy - delta
interface.energy = interface.energy + delta
end
end
-- Cap the stored energy to the allowed capacity
if not config.unlimited_capacity and vlayer_data.storage.energy > vlayer_data.properties.capacity * mega then
vlayer_data.storage.energy = vlayer_data.properties.capacity * mega
-- burn the trash to produce power
elseif vlayer_data.storage.power_items then
for k, v in pairs(vlayer_data.storage.power_items) do
local max_burning = (vlayer_data.properties.capacity * mega / 2) - vlayer_data.storage.energy
if v.count > 0 and max_burning > 0 then
local to_burn = math.min(v.count, math.floor(max_burning / v.value))
vlayer_data.storage.energy = vlayer_data.storage.energy + (to_burn * v.value)
vlayer_data.storage.power_items[k].count = vlayer_data.storage.power_items[k].count - to_burn
end
end
end
end
--- Remove the entity interface using the given position
-- @tparam LuaSurface surface The surface to search for an interface on
-- @tparam MapPosition position The position of the item
-- @treturn string The type of interface that was removed, or nil if no interface was found
-- @treturn MapPosition The position the interface was at, or nil if no interface was found
function vlayer.remove_interface(surface, position)
local entities = surface.find_entities_filtered{
name = { "storage-chest", "requester-chest", "constant-combinator", "electric-energy-interface" },
force = "neutral",
position = position,
radius = 2,
limit = 1,
}
-- Get the details which will be returned
if #entities == 0 then
return nil, nil, nil
end
local interface = entities[1]
local name = interface.name
local sur = interface.surface
local pos = interface.position
-- Return the type of interface removed and do some clean up
if name == "storage-chest" then
local inventory = assert(interface.get_inventory(defines.inventory.chest))
ExpUtil.transfer_inventory_to_surface{
inventory = inventory,
surface = interface.surface,
name = "iron-chest",
allow_creation = true,
}
table.remove_element(vlayer_data.entity_interfaces.storage_input, interface)
interface.destroy()
return "storage-input", sur, pos
elseif name == "requester-chest" then
local inventory = assert(interface.get_inventory(defines.inventory.chest))
ExpUtil.transfer_inventory_to_surface{
inventory = inventory,
surface = interface.surface,
name = "iron-chest",
allow_creation = true,
}
table.remove_element(vlayer_data.entity_interfaces.storage_output, interface)
interface.destroy()
return "storage-output", sur, pos
elseif name == "constant-combinator" then
table.remove_element(vlayer_data.entity_interfaces.circuit, interface)
interface.destroy()
return "circuit", sur, pos
elseif name == "electric-energy-interface" then
vlayer_data.storage.energy = vlayer_data.storage.energy + interface.energy
table.remove_element(vlayer_data.entity_interfaces.energy, interface)
interface.destroy()
return "energy", sur, pos
end
end
local function on_surface_event()
if config.mimic_surface then
local surface = game.get_surface(config.mimic_surface)
if surface then
vlayer_data.surface = surface
return
end
end
if not vlayer_data.surface.index then
-- Our fake surface data never has an index, we test for this to avoid unneeded copies from the config
vlayer_data.surface = table.deep_copy(config.surface)
end
end
--- Handle all storage IO and attempt allocation of unallocated items
Event.on_nth_tick(config.update_tick_storage, function(_)
handle_input_interfaces()
handle_output_interfaces()
handle_unallocated()
end)
--- Handle all energy and circuit updates
Event.on_nth_tick(config.update_tick_energy, function(_)
handle_circuit_interfaces()
handle_energy_interfaces()
end)
Event.add(defines.events.on_surface_created, on_surface_event)
Event.add(defines.events.on_surface_renamed, on_surface_event)
Event.add(defines.events.on_surface_imported, on_surface_event)
Event.on_init(on_surface_event) -- Default surface always exists, does not trigger on_surface_created
return vlayer
-488
View File
@@ -1,488 +0,0 @@
--[[-- Control Module - Warps
- Stores warps for each force.
@control Warps
@alias Warps
@usage-- Making a new spawn warp
local player = game.player
local force = player.force
local spawn_id = Warps.add_warp(force.name, player.physical_surface, player.physical_position, player.name, 'Spawn')
Warps.set_spawn_warp(spawn_id, force)
Warps.make_warp_tag(spawn_id)
@usage-- Making a new warp with a warp area
local player = game.player
local force = player.force
local warp_id = Warps.add_warp(force.name, player.physical_surface, player.physical_position, player.name)
Warps.make_warp_area(warp_id)
Warps.make_warp_tag(warp_id)
]]
local Datastore = require("modules.exp_legacy.expcore.datastore") --- @dep expcore.datastore
local Storage = require("modules/exp_util/storage")
local config = require("modules.exp_legacy.config.gui.warps") --- @dep config.warps
--- Stores all data for the warp system
local WrapData = Datastore.connect("WrapData")
WrapData:set_serializer(function(raw_key) return raw_key.warp_id end)
local Warps = {}
--- @class ExpScenario_Warps.force_warps: { spawn: string, [number]: string }
-- Storage lookup table for force name to task ids
local force_warps = { _uid = 1 }
--- @cast force_warps table<string, ExpScenario_Warps.force_warps>
Storage.register(force_warps, function(tbl)
force_warps = tbl
end)
-- Create an array of entity names that will be added to the remove filter
local remove_warp_area_entity_names = {}
for _, entity in pairs(config.entities) do
table.insert(remove_warp_area_entity_names, entity[1])
end
-- When a warp is updated change its chat tag and restore the warp order
WrapData:on_update(function(warp_id, warp, old_warp)
if warp then
warp.updates = warp.updates + 1
-- Update the map chart tag if there is one
if warp.tag then
Warps.make_warp_tag(warp_id)
end
-- Check that the name of the warp has been changed
if not old_warp or warp.name == old_warp.name then return end
-- Get the names of all the warp points for this force
local force_name = warp.force_name
local warp_ids = force_warps[force_name]
local spawn_id = warp_ids.spawn
local warp_names = {} --- @type table<string, string>
for _, next_warp_id in pairs(warp_ids) do
local next_warp = WrapData:get(next_warp_id)
if next_warp_id ~= spawn_id then
warp_names[next_warp.name .. next_warp_id] = next_warp_id
end
end
-- Sort the warp names in alphabetical order
local new_warp_ids = table.get_values(table.key_sort(warp_names))
--- @cast new_warp_ids ExpScenario_Warps.force_warps
table.insert(new_warp_ids, 1, spawn_id)
new_warp_ids.spawn = spawn_id
force_warps[force_name] = new_warp_ids
end
end)
--- Map Integration.
-- functions used to create and alter warps with in the map
-- @section mapIntegration
--[[-- Add or update the chat tag for this warp
@tparam string warp_id the uid of the warp you want the chart tag for
@treturn boolean true if a new tag was made, false if it was updated
@usage-- Adding a chart tag for a new warp
local tag_added = Warps.make_warp_tag(warp_id)
]]
function Warps.make_warp_tag(warp_id)
local warp = WrapData:get(warp_id)
local name = warp.name
local icon = warp.icon
-- Edit the existing tag if it is present
local tag = warp.tag
if tag and tag.valid then
tag.text = "Warp: " .. name
tag.icon = icon
return false
end
-- Make a new tag if one did not exist
local force = game.forces[warp.force_name]
local surface = warp.surface
local position = warp.position
tag = force.add_chart_tag(surface, {
position = { position.x + 0.5, position.y + 0.5 },
text = "Warp: " .. name,
icon = icon,
})
-- Add the tag to this warp, store.update not needed as we dont want it to trigger
warp.tag = tag
return true
end
--[[-- Remove the chart tag for this warp
@tparam string warp_id the uid for the warp that you want to remove the chart tag from
@treturn boolean true if the tag was valid and was removed, false if the tag was invalid
@usage-- Removing the chart tag from a warp
local removed = Warps.remove_warp_tag(warp_id)
]]
function Warps.remove_warp_tag(warp_id)
local warp = WrapData:get(warp_id)
-- Check there is a tag to remove
local tag = warp.tag
if not tag or not tag.valid then
warp.tag = nil
return false
end
-- Remove the warp chart tag if it is valid
tag.destroy()
warp.tag = nil
return true
end
--[[-- Add a warp area for the warp, purely cosmetic
@tparam string warp_id the uid of the warp you want the area for
@usage-- Adding a warp area for a warp
Warps.make_warp_area(warp_id)
]]
function Warps.make_warp_area(warp_id)
local warp = WrapData:get(warp_id)
local surface = warp.surface
local position = warp.position
local posx = position.x
local posy = position.y
-- Get the tile that is being replaced, store.update not needed as we don't want it to trigger
local old_tile = surface.get_tile(position).name
warp.old_tile = old_tile
-- Add a tile pattern on top of the base
local tiles = {}
for _, tile in pairs(config.tiles) do
table.insert(tiles, { name = tile[1], position = { tile[2] + posx, tile[3] + posy } })
end
surface.set_tiles(tiles)
-- Add entities to the warp structure
for _, entity in pairs(config.entities) do
entity = surface.create_entity{
name = entity[1],
position = { entity[2] + posx, entity[3] + posy },
force = "neutral",
}
entity.destructible = false
entity.health = 0
entity.minable_flag = false
entity.rotatable = false
-- Save reference of the last power pole
if entity.type == "electric-pole" then
warp.electric_pole = entity
end
end
end
--[[-- Remove the warp area for a warp
@tparam string warp_id the uid of the warp that you want to remove the area for
@usage-- Remove the warp area for a warp
Warps.remove_warp_area(warp_id)
]]
function Warps.remove_warp_area(warp_id)
local warp = WrapData:get(warp_id)
local position = warp.position
local surface = warp.surface
local radius = config.standard_proximity_radius
-- Check that a warp area was created previously
local old_tile = warp.old_tile
if not old_tile then return end
-- Restore the original tiles before the creation of the warp
local tiles = {}
for _, tile in pairs(config.tiles) do
table.insert(tiles, { name = old_tile, position = { tile[2] + position.x, tile[3] + position.y } })
end
surface.set_tiles(tiles)
local area = {
{ position.x - radius, position.y - radius },
{ position.x + radius, position.y + radius },
}
-- Remove warp structure entities
local entities = surface.find_entities_filtered{ force = "neutral", area = area, name = remove_warp_area_entity_names }
for _, entity in pairs(entities) do
-- Destroy them, this will leave corpses of the entities that it destroyed.
if entity and entity.valid and entity.destructible == false then
entity.destructible = true
entity.die(entity.force)
end
end
-- Rechart map area, useful if warp is not covered by a radar
game.forces[warp.force_name].chart(surface, area)
end
--[[-- Set a warp to be the spawn point for a force, force must own this warp
@tparam string warp_id the uid of the warp that you want to be the spawn for the force
@tparam LuaForce force the force that you want to set the spawn for
@usage-- Set your forces spawn to a warp
Warps.set_spawn_warp(warp_id, game.player.force)
]]
function Warps.set_spawn_warp(warp_id, force)
-- Check the force owns this warp
local warp = WrapData:get(warp_id)
if warp.force_name ~= force.name then
return
end
-- Set this warp as the spawn
local warp_ids = force_warps[warp.force_name]
if not warp_ids then
warp_ids = {}
force_warps[warp.force_name] = warp_ids
end
warp_ids.spawn = warp_id
-- Set the forces spawn to this warp
force.set_spawn_position(warp.position, warp.surface)
end
--[[-- Teleport a player to a warp point
@tparam string warp_id the uid of the warp to send the player to
@tparam LuaPlayer player the player to teleport to the warp
@usage-- Teleport yourself to a warp point
Warps.teleport_player(warp_id, game.player)
]]
function Warps.teleport_player(warp_id, player)
local warp = WrapData:get(warp_id)
local surface = warp.surface
local position = {
x = warp.position.x + 0.5,
y = warp.position.y + 0.5,
}
if player.vehicle then
-- Teleport the entity
local entity = player.vehicle
local goto_position = surface.find_non_colliding_position(entity.name, position, 32, 1)
-- Surface teleport can only be done for players and cars at the moment. (with surface as an peramitor it gives this error)
if entity.type == "car" then
entity.teleport(goto_position, surface)
elseif surface.index == entity.surface.index then
-- Try teleport the entity
if not entity.teleport(goto_position) then
player.driving = false
-- Need to calculate new goto_position because entities have different collision boxes
goto_position = surface.find_non_colliding_position("character", position, 32, 1)
player.teleport(goto_position, surface)
end
end
else
-- Teleport the player
local goto_position = surface.find_non_colliding_position("character", position, 32, 1)
if player.driving then player.driving = false end
player.teleport(goto_position, surface)
end
end
--- Setters.
-- functions used to created and alter warps
-- @section setters
--[[-- Add a new warp for a force, the warp must have a surface and a position
@tparam string force_name the name of the force to add the warp for
@tparam LuaSurface surface the surface that the warp will be on
@tparam Concepts.Position position the position that the warp will be on
@tparam[opt] string player_name the name of the player that is adding the warp
@tparam[opt] string warp_name the name of the warp that is being added, if omited default is used
@treturn string the uid of the warp which was created
@usage-- Adding a new warp for your force at your position
local player = game.player
local warp_id = Warps.add_warp(player.force.name, player.physical_surface, player.physical_position, player.name)
]]
function Warps.add_warp(force_name, surface, position, player_name, warp_name)
-- Get new warp id
local warp_id = tostring(force_warps._uid)
force_warps._uid = force_warps._uid + 1
warp_name = warp_name or "New warp"
-- Get the existing warps for this force
local warp_ids = force_warps[force_name]
if not warp_ids then
warp_ids = {}
force_warps[force_name] = warp_ids
end
-- Insert the warp id into the force warps
table.insert(warp_ids, warp_id)
-- Create the editing table
local editing = {}
if player_name then
editing[player_name] = true
end
-- Add the new warp to the store
WrapData:set(warp_id, {
warp_id = warp_id,
force_name = force_name,
name = warp_name,
icon = { type = config.default_icon.type, name = config.default_icon.name },
surface = surface,
position = {
x = math.floor(position.x),
y = math.floor(position.y),
},
last_edit_name = player_name or "<server>",
last_edit_time = game.tick,
currently_editing = editing,
updates = 0,
})
return warp_id
end
--[[-- Removes a warp and any data linked to it
@tparam string warp_id the uid of the warp that you want to remove
@usage-- Removing a warp
Warps.remove_warp(warp_id)
]]
function Warps.remove_warp(warp_id)
local warp = WrapData:get(warp_id)
local force_name = warp.force_name
Warps.remove_warp_tag(warp_id)
Warps.remove_warp_area(warp_id)
WrapData:remove(warp_id)
table.remove_element(force_warps[force_name], warp_id)
end
--[[-- Update the name and icon for a warp
@tparam string warp_id the uid of the warp that you want to update
@tparam[opt] string new_name the new name that you want the warp to have
@tparam[opt] string new_icon the new icon that you want the warp to have
@tparam[opt='server'] string player_name the name of the player that made the edit
@usage-- Changing the name and icon for a warp
Warps.update_warp(warp_id, 'My Warp', 'iron-plate', game.player.name)
]]
function Warps.update_warp(warp_id, new_name, new_icon, player_name)
WrapData:update(warp_id, function(_, warp)
-- If the icon is not valid then replace with the old icon
if new_icon and not new_icon.name or not new_icon.type then
new_icon = warp.icon
end
warp.last_edit_name = player_name or "<server>"
warp.last_edit_time = game.tick
warp.name = new_name or warp.name
warp.icon = new_icon or warp.icon
end)
end
--[[-- Set the editing state for a player, can be used as a warning or to display a text field
@tparam string warp_id the uid of the warp that you want to effect
@tparam string player_name the name of the player you want to set the state for
@tparam boolean state the new state to set editing to
@usage-- Setting your editing state to true
Warps.set_editing(warp_id, game.player.name, true)
]]
function Warps.set_editing(warp_id, player_name, state)
WrapData:update(warp_id, function(_, warp)
warp.currently_editing[player_name] = state
end)
end
--[[-- Adds an update handler for when a warp is added, removed, or updated
@tparam function handler the handler which is called when a warp is updated
@usage-- Add a game print when a warp is updated
Warps.on_update(function(warp)
game.print(warp.force_name..' now has the warp: '..warp.name)
end)
]]
function Warps.on_update(handler)
WrapData:on_update(handler)
end
--- Getters.
-- function used to get information about warps
-- @section getters
--[[-- Gets the warp information that is linked with this id
@tparam string warp_id the uid of the warp you want to get
@treturn table the warp information
@usage-- Getting warp information outside of on_update
local warp = Warps.get_warp(warp_id)
]]
function Warps.get_warp(warp_id)
return WrapData:get(warp_id)
end
--[[-- Gets all the warp ids that a force has
@tparam string force_name the name of the force that you want the warp ids for
@treturn table an array of all the warp ids
@usage-- Getting the warp ids for a force
local warp_ids = Warps.get_force_warp_ids(game.player.force.name)
]]
function Warps.get_force_warp_ids(force_name)
return force_warps[force_name] or {}
end
--[[-- Get the id of the spawn warp
@tparam string force_name the name of the force that you want to get the spawn warp for
@treturn ?string|nil the uid of the spawn warp for this force if there is one
@usage-- Getting the spawn warp id
local spawn_id = Warps.get_spawn_warp_id(game.player.force.name)
]]
function Warps.get_spawn_warp_id(force_name)
local warp_ids = force_warps[force_name] or {}
return warp_ids.spawn
end
--[[-- Gets the editing state for a player
@tparam string warp_id the uid of the warp you want to check
@tparam string player_name the name of the player that you want to check
@treturn boolean weather the player is currently editing this warp
@usage-- Check if a player is editing a warp or not
local editing = Warps.get_editing(warp_id, game.player.name)
]]
function Warps.get_editing(warp_id, player_name)
local warp = WrapData:get(warp_id)
return warp.currently_editing[player_name]
end
-- Module return
return Warps
-547
View File
@@ -1,547 +0,0 @@
--[[-- Gui Module - Virtual Layer
- Adds a virtual layer to store power to save space.
@gui Virtual Layer
@alias vlayer_container
]]
local Gui = require("modules/exp_gui")
local Roles = require("modules/exp_roles")
local Event = require("modules/exp_legacy/utils/event") --- @dep utils.event
local format_number = require("util").format_number --- @dep util
local config = require("modules.exp_legacy.config.vlayer") --- @dep config.vlayer
local vlayer = require("modules.exp_legacy.modules.control.vlayer")
local Selection = require("modules/exp_util/selection")
local SelectArea = Selection.connect("ExpGui_VLayer")
--- Align an aabb to the grid by expanding it
local function aabb_align_expand(aabb)
return {
left_top = { x = math.floor(aabb.left_top.x), y = math.floor(aabb.left_top.y) },
right_bottom = { x = math.ceil(aabb.right_bottom.x), y = math.ceil(aabb.right_bottom.y) },
}
end
local vlayer_container --- @type ExpElement
local vlayer_gui_control_type --- @type ExpElement
local vlayer_gui_control_list --- @type ExpElement
local vlayer_control_type_list = {
[1] = "energy",
[2] = "circuit",
[3] = "storage_input",
[4] = "storage_output",
}
local function pos_to_gps_string(pos, surface_name)
return "[gps=" .. string.format("%.1f", pos.x) .. "," .. string.format("%.1f", pos.y) .. "," .. surface_name .. "]"
end
local function format_energy(amount, unit)
if amount < 1 then
return "0 " .. unit
end
local suffix = ""
local suffix_list = {
["P"] = 1000000000000000,
["T"] = 1000000000000,
["G"] = 1000000000,
["M"] = 1000000,
["k"] = 1000,
}
for letter, limit in pairs(suffix_list) do
if math.abs(amount) >= limit then
amount = string.format("%.1f", amount / limit)
suffix = letter
break
end
end
local k
local formatted = amount
while true do
formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", "%1,%2")
if (k == 0) then
break
end
end
return formatted .. " " .. suffix .. unit
end
local ExpUtil = require("modules/exp_util")
--- When an area is selected to add protection to the area
SelectArea:on_selection(function(event)
log(ExpUtil.format_any(event))
local area = aabb_align_expand(event.area)
local player = game.players[event.player_index]
if not player then
return
end
local container = Gui.get_left_element(vlayer_container, player)
local disp = container.frame["vlayer_st_2"].disp.table
local target = vlayer_control_type_list[disp[vlayer_gui_control_type.name].selected_index]
local entities --- @type LuaEntity[]
if config.power_on_space and event.surface and event.surface.platform and target == "energy" then
if (player.force --[[@as LuaForce]]).technologies[config.power_on_space_research.name].level >= config.power_on_space_research.level then
entities = event.surface.find_entities_filtered{ area = area, name = "constant-combinator", force = player.force }
else
player.print{ "vlayer.power-on-space-research", config.power_on_space_research.name, config.power_on_space_research.level }
return
end
else
entities = event.surface.find_entities_filtered{ area = area, name = "steel-chest", force = player.force }
end
if #entities == 0 then
player.print{ "vlayer.steel-chest-detect" }
return
elseif #entities > 1 then
player.print{ "vlayer.result-unable", { "vlayer.control-type-" .. target:gsub("_", "-") }, { "vlayer.result-multiple" } }
return
end
if not entities[1] then
return
end
local e = entities[1]
local e_pos = { x = string.format("%.1f", e.position.x), y = string.format("%.1f", e.position.y) }
local e_circ = nil -- e.get_wire_connectors{ or_create = false }
if e.name and e.name == "steel-chest" and (not assert(e.get_inventory(defines.inventory.chest)).is_empty()) then
player.print{ "vlayer.steel-chest-empty" }
return
end
if (vlayer.get_interface_counts()[target] >= config.interface_limit[target]) then
player.print{ "vlayer.result-unable", { "vlayer.control-type-" .. target:gsub("_", "-") }, { "vlayer.result-limit" } }
return
end
e.destroy()
if target == "energy" then
if not vlayer.create_energy_interface(event.surface, e_pos, player) then
player.print{ "vlayer.result-unable", { "vlayer.control-type-energy" }, { "vlayer.result-space" } }
return
end
elseif target == "circuit" then
vlayer.create_circuit_interface(event.surface, e_pos, e_circ, player)
elseif target == "storage_input" then
vlayer.create_input_interface(event.surface, e_pos, e_circ, player)
elseif target == "storage_output" then
vlayer.create_output_interface(event.surface, e_pos, e_circ, player)
end
game.print{ "vlayer.interface-result", player.name, pos_to_gps_string(e_pos, event.surface.name), { "vlayer.result-build" }, { "vlayer.control-type-" .. target:gsub("_", "-") } }
end)
--- Display label for the number of solar panels
-- @element vlayer_gui_display_item_solar_name
local vlayer_gui_display_item_solar_name = Gui.define("vlayer_gui_display_item_solar_name")
:draw{
type = "label",
name = Gui.from_name,
caption = { "vlayer.display-item-solar" },
style = "heading_2_label",
}:style{
width = 200,
}
local vlayer_gui_display_item_solar_count = Gui.define("vlayer_gui_display_item_solar_count")
:draw{
type = "progressbar",
name = Gui.from_name,
caption = "",
value = 0,
style = "electric_satisfaction_statistics_progressbar",
}:style{
width = 200,
font = "heading-2",
}
--- Display label for the number of accumulators
-- @element vlayer_gui_display_item_accumulator_name
local vlayer_gui_display_item_accumulator_name = Gui.define("vlayer_gui_display_item_accumulator_name")
:draw{
type = "label",
name = Gui.from_name,
caption = { "vlayer.display-item-accumulator" },
style = "heading_2_label",
}:style{
width = 200,
}
local vlayer_gui_display_item_accumulator_count = Gui.define("vlayer_gui_display_item_accumulator_count")
:draw{
type = "progressbar",
name = Gui.from_name,
caption = "",
value = 0,
style = "electric_satisfaction_statistics_progressbar",
}:style{
width = 200,
font = "heading-2",
}
--- Display label for the surface area
-- @element vlayer_gui_display_signal_surface_area_name
local vlayer_gui_display_signal_surface_area_name = Gui.define("vlayer_gui_display_signal_surface_area_name")
:draw{
type = "label",
name = Gui.from_name,
caption = { "vlayer.display-remaining-surface-area" },
tooltip = { "vlayer.display-remaining-surface-area-tooltip" },
style = "heading_2_label",
}:style{
width = 200,
}
local vlayer_gui_display_signal_surface_area_count = Gui.define("vlayer_gui_display_signal_surface_area_count")
:draw{
type = "progressbar",
name = Gui.from_name,
caption = "",
value = 0,
style = "electric_satisfaction_statistics_progressbar",
}:style{
width = 200,
font = "heading-2",
}
--- Display label for the sustained energy production
-- @element vlayer_gui_display_signal_sustained_name
local vlayer_gui_display_signal_sustained_name = Gui.define("vlayer_gui_display_signal_sustained_name")
:draw{
type = "label",
name = Gui.from_name,
caption = { "vlayer.display-sustained-production" },
tooltip = { "vlayer.display-sustained-production-tooltip" },
style = "heading_2_label",
}:style{
width = 200,
}
local vlayer_gui_display_signal_sustained_count = Gui.define("vlayer_gui_display_signal_sustained_count")
:draw{
type = "progressbar",
name = Gui.from_name,
caption = "",
value = 0,
style = "electric_satisfaction_statistics_progressbar",
}:style{
width = 200,
font = "heading-2",
}
--- Display label for the current energy production
-- @element vlayer_gui_display_signal_production_name
local vlayer_gui_display_signal_production_name = Gui.define("vlayer_gui_display_signal_production_name")
:draw{
type = "label",
name = Gui.from_name,
caption = { "vlayer.display-current-production" },
tooltip = { "vlayer.display-current-production-tooltip" },
style = "heading_2_label",
}:style{
width = 200,
}
local vlayer_gui_display_signal_production_count = Gui.define("vlayer_gui_display_signal_production_count")
:draw{
type = "progressbar",
name = Gui.from_name,
caption = "",
value = 0,
style = "electric_satisfaction_statistics_progressbar",
}:style{
width = 200,
font = "heading-2",
}
--- Display label for the sustained energy capacity
-- @element vlayer_gui_display_signal_capacity_name
local vlayer_gui_display_signal_capacity_name = Gui.define("vlayer_gui_display_signal_capacity_name")
:draw{
type = "label",
name = Gui.from_name,
caption = { "vlayer.display-current-capacity" },
tooltip = { "vlayer.display-current-capacity-tooltip" },
style = "heading_2_label",
}:style{
width = 200,
}
local vlayer_gui_display_signal_capacity_count = Gui.define("vlayer_gui_display_signal_capacity_count")
:draw{
type = "progressbar",
name = Gui.from_name,
caption = "",
value = 0,
style = "electric_satisfaction_statistics_progressbar",
}:style{
width = 200,
font = "heading-2",
}
--- A vertical flow containing all the displays labels and their counts
-- @element vlayer_display_set
local vlayer_display_set = Gui.define("vlayer_display_set")
:draw(function(_, parent, name)
local vlayer_set = parent.add{ type = "flow", direction = "vertical", name = name }
local disp = Gui.elements.scroll_table(vlayer_set, 400, 2, "disp")
vlayer_gui_display_item_solar_name(disp)
vlayer_gui_display_item_solar_count(disp)
vlayer_gui_display_item_accumulator_name(disp)
vlayer_gui_display_item_accumulator_count(disp)
vlayer_gui_display_signal_surface_area_name(disp)
vlayer_gui_display_signal_surface_area_count(disp)
vlayer_gui_display_signal_sustained_name(disp)
vlayer_gui_display_signal_sustained_count(disp)
vlayer_gui_display_signal_production_name(disp)
vlayer_gui_display_signal_production_count(disp)
vlayer_gui_display_signal_capacity_name(disp)
vlayer_gui_display_signal_capacity_count(disp)
return vlayer_set
end)
local function vlayer_gui_list_refresh(player)
local container = Gui.get_left_element(vlayer_container, player)
local disp = container.frame["vlayer_st_2"].disp.table
local target = disp[vlayer_gui_control_type.name].selected_index
local full_list = {}
if target then
local interface = vlayer.get_interfaces()[vlayer_control_type_list[target]]
for i = 1, vlayer.get_interface_counts()[vlayer_control_type_list[target]], 1 do
local entity = assert(interface[i])
local entity_position = entity.position
table.insert(full_list, i .. " X " .. entity_position.x .. " Y " .. entity_position.y)
end
disp[vlayer_gui_control_list.name].items = full_list
end
end
--- A drop down list filter by this type
-- @element vlayer_gui_control_type
vlayer_gui_control_type = Gui.define("vlayer_gui_control_type")
:draw{
type = "drop-down",
name = Gui.from_name,
items = { { "vlayer.control-type-energy" }, { "vlayer.control-type-circuit" }, { "vlayer.control-type-storage-input" }, { "vlayer.control-type-storage-output" } },
selected_index = 1,
}:style{
width = 200,
}:on_selection_state_changed(function(def, player, element)
vlayer_gui_list_refresh(player)
end)
--- A drop down list to see the exact item to remove
-- @element vlayer_gui_control_list
vlayer_gui_control_list = Gui.define("vlayer_gui_control_list")
:draw{
type = "drop-down",
name = Gui.from_name,
}:style{
width = 200,
}
--- A button to refresh the remove list
-- @element vlayer_gui_control_refresh
local vlayer_gui_control_refresh = Gui.define("vlayer_gui_control_refresh")
:draw{
type = "button",
name = Gui.from_name,
caption = { "vlayer.control-refresh" },
}:style{
width = 200,
}:on_click(function(def, player, element)
vlayer_gui_list_refresh(player)
end)
--- A button to check if the item is the one wanted to remove
-- @element vlayer_gui_control_see
local vlayer_gui_control_see = Gui.define("vlayer_gui_control_see")
:draw{
type = "button",
name = Gui.from_name,
caption = { "vlayer.control-see" },
}:style{
width = 200,
}:on_click(function(def, player, element, event)
local target = assert(element.parent)[vlayer_gui_control_type.name].selected_index
local n = assert(element.parent)[vlayer_gui_control_list.name].selected_index
if target and vlayer_control_type_list[target] and n > 0 then
local i = vlayer.get_interfaces()
local entity = i[vlayer_control_type_list[target]][n]
if entity and entity.valid then
player.set_controller{ type = defines.controllers.remote, position = entity.position, surface = entity.surface }
player.print{ "vlayer.result-interface-location", { "vlayer.control-type-" .. vlayer_control_type_list[target]:gsub("_", "-") }, pos_to_gps_string(entity.position, entity.surface.name) }
end
end
end)
--- A button used to build the vlayer interface
-- @element vlayer_gui_control_build
local vlayer_gui_control_build = Gui.define("vlayer_gui_control_build")
:draw{
type = "button",
name = Gui.from_name,
caption = { "vlayer.control-build" },
}:style{
width = 200,
}:on_click(function(def, player, element)
if SelectArea:stop(player) then
player.print{ "exp_util.selection_exit", { "vlayer.main-tooltip" } }
else
SelectArea:start(player)
player.print{ "exp_util.selection_enter", { "vlayer.main-tooltip" } }
end
vlayer_gui_list_refresh(player)
end)
--- A button used to remove the vlayer interface
-- @element vlayer_gui_control_remove
local vlayer_gui_control_remove = Gui.define("vlayer_gui_control_remove")
:draw{
type = "button",
name = Gui.from_name,
caption = { "vlayer.control-remove" },
}:style{
width = 200,
}:on_click(function(def, player, element)
local target = assert(element.parent)[vlayer_gui_control_type.name].selected_index
local n = assert(element.parent)[vlayer_gui_control_list.name].selected_index
if target and vlayer_control_type_list[target] and n > 0 then
local i = vlayer.get_interfaces()
if i and i[vlayer_control_type_list[target]] then
local entity = assert(i[vlayer_control_type_list[target]][n])
local interface_type, interface_surface, interface_position = vlayer.remove_interface(entity.surface, entity.position)
if interface_type then
game.print{ "vlayer.interface-result", player.name, pos_to_gps_string(interface_position, interface_surface.name), { "vlayer.result-remove" }, { "vlayer.control-type-" .. interface_type } }
end
end
end
vlayer_gui_list_refresh(player)
end)
--- A vertical flow containing all the control buttons
-- @element vlayer_control_set
local vlayer_control_set = Gui.define("vlayer_control_set")
:draw(function(_, parent, name)
local player = Gui.get_player(parent)
local vlayer_set = parent.add{ type = "flow", direction = "vertical", name = name }
local disp = Gui.elements.scroll_table(vlayer_set, 400, 2, "disp")
vlayer_gui_control_type(disp)
vlayer_gui_control_list(disp)
vlayer_gui_control_refresh(disp)
vlayer_gui_control_see(disp)
local b = vlayer_gui_control_build(disp)
local r = vlayer_gui_control_remove(disp)
local v = Roles.player_has_permission(player, "exp_scenario.gui.vlayer_edit")
b.visible = v
r.visible = v
return vlayer_set
end)
--- The main container for the vlayer gui
-- @element vlayer_container
vlayer_container = Gui.define("vlayer_container")
:draw(function(definition, parent)
local container = Gui.elements.container(parent, 400)
vlayer_display_set(container, "vlayer_st_1")
vlayer_control_set(container, "vlayer_st_2")
return container.parent
end)
--- Add the element to the left flow with a toolbar button
Gui.add_left_element(vlayer_container, false)
Gui.toolbar.create_button{
name = "vlayer_toggle",
left_element = vlayer_container,
sprite = "entity/solar-panel",
tooltip = { "vlayer.main-tooltip" },
visible = function(player, element)
return Roles.player_has_permission(player, "exp_scenario.gui.vlayer")
end
}
--- Update the visibly of the buttons based on a players roles
local function role_update_event(event)
local player = game.players[event.player_index]
local visible = Roles.player_has_permission(player, "exp_scenario.gui.vlayer_edit")
local container = Gui.get_left_element(vlayer_container, player)
local disp = container.frame["vlayer_st_2"].disp.table
disp[vlayer_gui_control_build.name].visible = visible
disp[vlayer_gui_control_remove.name].visible = visible
end
Event.add(Roles.events.on_player_roles_changed, role_update_event)
Event.on_nth_tick(config.update_tick_gui, function(_)
local stats = vlayer.get_statistics()
local items = vlayer.get_items()
local items_alloc = vlayer.get_allocated_items()
local vlayer_display = {
[vlayer_gui_display_item_solar_count.name] = {
val = (items_alloc["solar-panel"] / math.max(items["solar-panel"], 1)),
cap = format_number(items_alloc["solar-panel"], false) .. " / " .. format_number(items["solar-panel"], false),
},
[vlayer_gui_display_item_accumulator_count.name] = {
val = (items_alloc["accumulator"] / math.max(items["accumulator"], 1)),
cap = format_number(items_alloc["accumulator"], false) .. " / " .. format_number(items["accumulator"], false),
},
[vlayer_gui_display_signal_surface_area_count.name] = {
val = (stats.total_surface_area / math.max(stats.surface_area, 1)),
cap = format_number(stats.remaining_surface_area)
},
[vlayer_gui_display_signal_sustained_count.name] = {
val = (stats.energy_sustained / math.max(stats.energy_total_production, 1)),
cap = format_energy(stats.energy_sustained, "W") .. " / " .. format_energy(stats.energy_total_production, "W")
},
[vlayer_gui_display_signal_production_count.name] = {
val = (stats.energy_production / math.max(stats.energy_max, 1)),
cap = format_energy(stats.energy_production, "W") .. " / " .. format_energy(stats.energy_max, "W"),
},
[vlayer_gui_display_signal_capacity_count.name] = {
val = (stats.energy_storage / math.max(stats.energy_capacity, 1)),
cap = format_energy(stats.energy_storage, "J") .. " / " .. format_energy(stats.energy_capacity, "J"),
},
}
for _, player in pairs(game.connected_players) do
local container = Gui.get_left_element(vlayer_container, player)
local disp = container.frame["vlayer_st_1"].disp.table
for k, v in pairs(vlayer_display) do
disp[k].caption = v.cap
if v.val then
disp[k].value = v.val
end
end
end
end)
-909
View File
@@ -1,909 +0,0 @@
--[[-- Gui Module - Warp List
- Adds a warp list gui which allows players to add and remove warp points
@gui Warps-List
@alias warp_list
]]
local ExpUtil = require("modules/exp_util")
local Gui = require("modules/exp_gui")
local Datastore = require("modules.exp_legacy.expcore.datastore") --- @dep expcore.datastore
local Storage = require("modules/exp_util/storage")
local Event = require("modules/exp_legacy/utils/event") --- @dep utils.event
local Roles = require("modules/exp_roles")
local Colors = require("modules/exp_util/include/color")
local config = require("modules.exp_legacy.config.gui.warps") --- @dep config.gui.warps
local Warps = require("modules.exp_legacy.modules.control.warps") --- @dep modules.control.warps
local format_time = ExpUtil.format_time_factory_locale{ format = "short", hours = true, minutes = true }
--- Stores all data for the warp gui
local WrapGuiData = Datastore.connect("WrapGuiData")
WrapGuiData:set_serializer(Datastore.name_serializer)
local PlayerInRange = WrapGuiData:combine("PlayerInRange")
PlayerInRange:set_default(false)
local PlayerCooldown = WrapGuiData:combine("PlayerCooldown")
PlayerCooldown:set_default(0)
--- Table that stores a boolean value of weather to keep the warp gui open
local keep_gui_open = {}
Storage.register(keep_gui_open, function(tbl)
keep_gui_open = tbl
end)
--- Styles used for sprite buttons
local Styles = {
sprite22 = { height = 22, width = 22, padding = -2 },
sprite32 = { height = 32, width = 32, left_margin = 1 },
}
--- Status icon of a warp
local warp_status_icons = {
cooldown = "[img=utility/multiplayer_waiting_icon]",
not_available = "[img=utility/set_bar_slot]",
bypass = "[img=utility/side_menu_bonus_icon]",
current = "[img=utility/side_menu_map_icon]",
connected = "[img=utility/logistic_network_panel_white]",
different = "[img=utility/warning_white]",
}
--- Returns if a player is allowed to edit the given warp
--- If a player is allowed to use the edit buttons
local function check_player_permissions(player, action, warp)
-- Check if the action is allow edit and then check bypass settings
if action == "allow_edit_warp" then
-- Check if the warp is the spawn then it cant be edited
local spawn_id = Warps.get_spawn_warp_id(player.force.name)
if spawn_id == warp.warp_id then
return false
end
-- Check if the player being the last to edit will override existing permisisons
if config.user_can_edit_own_warps and warp.last_edit_name == player.name then
return true
end
end
-- Check player has permission based on value in the config
local action_config = config[action]
if action_config == "all" then
return true
elseif action_config == "admin" then
return player.admin
elseif action_config == "exp_roles" then
return Roles.player_has_permission(player, config["exp_roles_" .. action])
end
-- Return false as all other conditions have not been met
return false
end
--- Will add a new warp to the list, checks if the player is too close to an existing one
-- @element add_new_warp
local add_new_warp = Gui.define("add_new_warp")
:draw{
type = "sprite-button",
sprite = "utility/add",
tooltip = { "warp-list.add-tooltip" },
style = "shortcut_bar_button",
name = Gui.from_name,
}
:style(Styles.sprite22)
:on_click(function(def, player, element)
if player.controller_type ~= defines.controllers.character then return end
-- Add the new warp
local force_name = player.force.name
local surface = player.physical_surface
local position = player.physical_position
-- Check if the warp is too close to water
local water_tiles = surface.find_tiles_filtered{ collision_mask = "water_tile", radius = config.standard_proximity_radius + 1, position = position }
if #water_tiles > 0 then
player.print(
{ "expcore-commands.command-fail", { "warp-list.too-close-to-water", config.standard_proximity_radius + 1 } },
{ color = Colors.orange_red }
)
if game.player then game.player.play_sound{ path = "utility/wire_pickup" } end
for _, tile in pairs(water_tiles) do
rendering.draw_sprite{
sprite = "utility/rail_path_not_possible",
x_scale = 0.5,
y_scale = 0.5,
target = tile.position,
surface = surface,
players = { player },
time_to_live = 60,
}
end
return
end
-- Check if there are player entities in the way (has a bigger radius because the enities that can be placed by a player are larger)
local entities = surface.find_entities_filtered{
radius = config.standard_proximity_radius + 2.5,
position = position,
collision_mask = {
"item", "object", "player", "water_tile",
},
}
-- Remove 1 because that is the current player
if #entities > 1 then
player.print(
{ "expcore-commands.command-fail", { "warp-list.too-close-to-entities", config.standard_proximity_radius + 2.5 } },
{ color = Colors.orange_red }
)
if game.player then game.player.play_sound{ path = "utility/wire_pickup" } end
local character = player.character
for _, entity in pairs(entities) do
if entity ~= character then
rendering.draw_sprite{
sprite = "utility/rail_path_not_possible",
x_scale = 0.5,
y_scale = 0.5,
target = entity,
surface = surface,
players = { player },
time_to_live = 60,
}
end
end
return
end
-- Create the warp
local warp_id = Warps.add_warp(force_name, surface, position, player.name)
Warps.make_warp_tag(warp_id)
Warps.make_warp_area(warp_id)
end)
--- Warp icon button, this will trigger a warp when the player is able to
-- @element warp_icon_button
local warp_icon_button = Gui.define("warp_icon_button")
:draw(function(def, parent, warp)
local warp_position = warp.position
-- The SpritePath type is not the same as the SignalID type
local sprite = warp.icon.type .. "/" .. warp.icon.name
if warp.icon.type == "virtual" then
sprite = "virtual-signal/" .. warp.icon.name
end
-- Draw the element
return parent.add{
type = "sprite-button",
sprite = sprite,
name = def.name,
tooltip = { "warp-list.goto-tooltip", warp_position.x, warp_position.y },
style = "slot_button",
}
end)
:style(Styles.sprite32)
:on_click(function(def, player, element)
if element.type == "choose-elem-button" then return end
local warp_id = assert(element.parent).caption
Warps.teleport_player(warp_id, player)
-- Reset the warp cooldown if the player does not have unlimited warps
if not check_player_permissions(player, "bypass_warp_cooldown") then
PlayerCooldown:set(player, config.update_smoothing * config.cooldown_duration)
end
PlayerInRange:set(player, warp_id)
end)
--- The button that is visible when the warp is in edit state
-- @element warp_icon_editing
local warp_icon_editing = Gui.define("warp_icon_editing")
:draw(function(def, parent, warp)
return parent.add{
name = def.name,
type = "choose-elem-button",
elem_type = "signal",
signal = { type = warp.icon.type, name = warp.icon.name },
tooltip = { "warp-list.goto-edit" },
}
end)
:style(Styles.sprite32)
--- Warp label, visible if the player is not in edit state
-- @element warp_label
local warp_label = Gui.define("warp_label")
:draw(function(def, parent, warp)
local last_edit_name = warp.last_edit_name
local last_edit_time = warp.last_edit_time
-- Draw the element
return parent.add{
type = "label",
caption = warp.name,
tooltip = { "warp-list.last-edit", last_edit_name, format_time(last_edit_time) },
name = def.name,
}
end)
:style{
single_line = true,
left_padding = 2,
right_padding = 2,
horizontally_stretchable = true,
}
:on_click(function(def, player, element)
local warp_id = assert(element.parent).caption
local warp = Warps.get_warp(warp_id)
player.set_controller{ type = defines.controllers.remote, position = warp.position, surface = warp.surface }
end)
--- Warp status, visible if the player is not in edit state
--- This will show if the warp is connected or not
-- @element warp_status
local warp_status = Gui.define("warp_status")
:draw{
type = "label",
caption = "[img=utility/electricity_icon_unplugged]", -- Temporary icon
name = Gui.from_name,
}
:style{
-- When editing mode because textbox is larger the icon would move up.
top_padding = 1,
single_line = false,
}
--- Warp textfield, visible if the player is in edit state
-- @element warp_textfield
local warp_textfield = Gui.define("warp_textfield")
:draw(function(def, parent, warp)
-- Draw the element
return parent.add{
type = "textfield",
text = warp.name,
clear_and_focus_on_right_click = true,
name = def.name,
}
end)
:style{
-- Required fields to make it squashable and strechable.
minimal_width = 10,
maximal_width = 300,
horizontally_squashable = true,
horizontally_stretchable = true,
-- Other styling
height = 22,
padding = -2,
left_margin = 2,
right_margin = 2,
}
:on_confirmed(function(def, player, element)
local warp_id = assert(element.parent).caption
local warp_name = element.text
local warp_icon = assert(element.parent).parent["icon-" .. warp_id][warp_icon_editing.name].elem_value --[[@as SignalID]]
if warp_icon.type == nil then warp_icon.type = "item" end
Warps.set_editing(warp_id, player.name)
Warps.update_warp(warp_id, warp_name, warp_icon, player.name)
end)
--- Confirms the edit to name or icon of the warp
-- @element confirm_edit_button
local confirm_edit_button = Gui.define("confirm_edit_button")
:draw{
type = "sprite-button",
sprite = "utility/confirm_slot",
tooltip = { "warp-list.confirm-tooltip" },
style = "shortcut_bar_button_green",
name = Gui.from_name,
}
:style(Styles.sprite22)
:on_click(function(def, player, element)
local parent = assert(element.parent)
local grandparent = assert(parent.parent)
local warp_id = parent.caption --[[@as string]]
local name_flow = grandparent["name-" .. warp_id]
local icon_flow = grandparent["icon-" .. warp_id]
local warp_name = name_flow[warp_textfield.name].text
local warp_icon = icon_flow[warp_icon_editing.name].elem_value --[[@as SignalID]]
if warp_icon.type == nil then warp_icon.type = "item" end
Warps.set_editing(warp_id, player.name)
Warps.update_warp(warp_id, warp_name, warp_icon, player.name)
end)
--- Cancels the editing changes of the selected warp name or icon
-- @element cancel_edit_button
local cancel_edit_button = Gui.define("cancel_edit_button")
:draw{
type = "sprite-button",
sprite = "utility/close_black",
tooltip = { "warp-list.cancel-tooltip" },
style = "shortcut_bar_button_red",
name = Gui.from_name,
}
:style(Styles.sprite22)
:on_click(function(def, player, element)
local warp_id = assert(element.parent).caption
-- Check if this is the first edit, if so remove the warp.
local warp = Warps.get_warp(warp_id)
if warp.updates == 1 then
Warps.remove_warp(warp_id)
return
end
Warps.set_editing(warp_id, player.name)
end)
--- Removes a warp from the list, including the physical area and map tag
-- @element remove_warp_button
local remove_warp_button = Gui.define("remove_warp_button")
:draw{
type = "sprite-button",
sprite = "utility/trash",
tooltip = { "warp-list.remove-tooltip" },
style = "shortcut_bar_button_red",
name = Gui.from_name,
}
:style(Styles.sprite22)
:on_click(function(def, player, element)
local warp_id = assert(element.parent).caption
Warps.remove_warp(warp_id)
end)
--- Opens edit mode for the warp
-- @element edit_warp_button
local edit_warp_button = Gui.define("edit_warp_button")
:draw{
type = "sprite-button",
sprite = "utility/rename_icon",
tooltip = { "warp-list.edit-tooltip-none" },
style = "shortcut_bar_button",
name = Gui.from_name,
}
:style(Styles.sprite22)
:on_click(function(def, player, element)
local warp_id = assert(element.parent).caption
Warps.set_editing(warp_id, player.name, true)
end)
local update_all_warp_elements
--- Set of three elements which make up each row of the warp table
-- @element add_warp_elements
local add_warp_elements = Gui.define("add_warp_elements")
:draw(function(_, parent, warp)
-- Add icon flow, this will contain the warp button and warp icon edit button
local icon_flow = parent.add{
name = "icon-" .. warp.warp_id,
type = "flow",
caption = warp.warp_id,
}
icon_flow.style.padding = 0
-- Add the button and the icon edit button
warp_icon_button(icon_flow, warp)
warp_icon_editing(icon_flow, warp)
-- Add name flow, this will contain the warp label and textbox
local name_flow = parent.add{
type = "flow",
name = "name-" .. warp.warp_id,
caption = warp.warp_id,
}
name_flow.style.padding = 0
-- Add the label and textfield of the warp
warp_status(name_flow)
warp_label(name_flow, warp)
warp_textfield(name_flow, warp)
-- Add button flow, this will contain buttons to manage this specific warp
local button_flow = parent.add{
type = "flow",
name = "button-" .. warp.warp_id,
caption = warp.warp_id,
}
button_flow.style.padding = 0
-- Add both edit state buttons
confirm_edit_button(button_flow)
cancel_edit_button(button_flow)
edit_warp_button(button_flow)
remove_warp_button(button_flow)
return Gui.no_return()
end)
-- Removes the three elements that are added as part of the warp base
local function remove_warp_elements(parent, warp_id)
Gui.destroy_if_valid(parent["icon-" .. warp_id])
Gui.destroy_if_valid(parent["name-" .. warp_id])
Gui.destroy_if_valid(parent["button-" .. warp_id])
end
--- This timer controls when a player is able to warp, eg every 60 seconds
-- @element warp_timer
local warp_timer = Gui.define("warp_timer")
:draw{
type = "progressbar",
name = Gui.from_name,
tooltip = { "warp-list.timer-tooltip-zero", config.cooldown_duration },
minimum_value = 0,
maximum_value = config.cooldown_duration * config.update_smoothing,
}
:style{
horizontally_stretchable = true,
color = Colors.light_blue,
}
local warp_list_container
-- Helper function to style and enable or disable a button element
local function update_warp_elements(element, warp, warp_player_is_on, on_cooldown, bypass_warp_proximity)
-- Check if button element is valid
if not element or not element.valid then return end
local label_style = assert(element.parent).parent["name-" .. warp.warp_id][warp_label.name].style
local warp_status_element = assert(element.parent).parent["name-" .. warp.warp_id][warp_status.name]
-- If player is not on a warp
if not warp_player_is_on then
-- If player is allowed to warp without being on a warp. If not then disable the warp location
if bypass_warp_proximity then
local position = warp.position
element.tooltip = { "warp-list.goto-bypass", position.x, position.y }
element.enabled = true
warp_status_element.tooltip = { "warp-list.goto-bypass", position.x, position.y }
warp_status_element.caption = warp_status_icons.bypass
label_style.font = "default-semibold"
else
element.tooltip = { "warp-list.goto-disabled" }
element.enabled = false
warp_status_element.tooltip = { "warp-list.goto-disabled" }
warp_status_element.caption = warp_status_icons.not_available
label_style.font = "default"
end
-- If player is on the warp that is being updated
elseif warp_player_is_on.warp_id == warp.warp_id then
element.tooltip = { "warp-list.goto-same-warp" }
element.enabled = false
warp_status_element.tooltip = { "warp-list.goto-same-warp" }
warp_status_element.caption = warp_status_icons.current
label_style.font = "default"
-- If player is on cooldown
elseif on_cooldown then
element.tooltip = { "warp-list.goto-cooldown" }
element.enabled = false
warp_status_element.tooltip = { "warp-list.goto-cooldown" }
warp_status_element.caption = warp_status_icons.cooldown
label_style.font = "default"
else
-- If the warp the player is standing on is the same as the warp that is being updated
local warp_electric_network_id = warp.electric_pole and warp.electric_pole.electric_network_id or -1
local player_warp_electric_network_id = warp_player_is_on.electric_pole and warp_player_is_on.electric_pole.electric_network_id or -2
if warp_electric_network_id == player_warp_electric_network_id then
local position = warp.position
element.tooltip = { "warp-list.goto-tooltip", position.x, position.y }
element.enabled = true
warp_status_element.tooltip = { "warp-list.goto-tooltip", position.x, position.y }
warp_status_element.caption = warp_status_icons.connected
label_style.font = "default-semibold"
-- If the warp is not on the same network but the player is allowed to warp without being on a warp
elseif bypass_warp_proximity then
local position = warp.position
element.tooltip = { "warp-list.goto-bypass-different-network", position.x, position.y }
element.enabled = true
warp_status_element.tooltip = { "warp-list.goto-bypass-different-network", position.x, position.y }
warp_status_element.caption = warp_status_icons.bypass
label_style.font = "default-semibold"
-- If the warp is on a different network than the one the player is standing on
else
element.tooltip = { "warp-list.goto-different-network" }
element.enabled = false
warp_status_element.tooltip = { "warp-list.goto-different-network" }
warp_status_element.caption = warp_status_icons.different
label_style.font = "default"
end
end
end
--- Update the warp buttons for a player
function update_all_warp_elements(player, timer, warp_id)
-- Get the warp table
local container = Gui.get_left_element(warp_list_container, player)
local scroll_table = container.frame.scroll.table
-- Check if the player is currently on cooldown
timer = timer or PlayerCooldown:get(player)
local on_cooldown = timer > 0
-- Get the warp the player is on
warp_id = warp_id or PlayerInRange:get(player)
local warp_player_is_on = warp_id and Warps.get_warp(warp_id) or nil
-- Check player permission
local bypass_warp_proximity = check_player_permissions(player, "bypass_warp_proximity")
-- Change the enabled state of the warp buttons
local warp_ids = Warps.get_force_warp_ids(player.force.name)
for _, next_warp_id in pairs(warp_ids) do
local element = scroll_table["icon-" .. next_warp_id][warp_icon_button.name]
local next_warp = Warps.get_warp(next_warp_id)
update_warp_elements(element, next_warp, warp_player_is_on, on_cooldown, bypass_warp_proximity)
end
end
--- Updates a warp for a player
local function update_warp(player, warp_table, warp_id)
local warp = Warps.get_warp(warp_id)
-- If the warp no longer exists then remove the warp elements from the warp table
if not warp then
remove_warp_elements(warp_table, warp_id)
return
end
-- Create the warp elements if they do not already exist
if not warp_table["icon-" .. warp_id] then
add_warp_elements(warp_table, warp)
end
local icon_flow = warp_table["icon-" .. warp_id]
local name_flow = warp_table["name-" .. warp_id]
local button_flow = warp_table["button-" .. warp_id]
-- Create local references to the elements for this warp
local warp_icon_element = icon_flow[warp_icon_button.name]
local warp_icon_edit_element = icon_flow[warp_icon_editing.name]
local label_element = name_flow[warp_label.name]
local textfield_element = name_flow[warp_textfield.name]
local cancel_edit_element = button_flow[cancel_edit_button.name]
local confirm_edit_element = button_flow[confirm_edit_button.name]
local edit_warp_element = button_flow[edit_warp_button.name]
local remove_warp_element = button_flow[remove_warp_button.name]
-- Hide the edit button if the player is not allowed to edit the warp
local player_allowed_edit = check_player_permissions(player, "allow_edit_warp", warp)
local players_editing = table.get_keys(warp.currently_editing)
edit_warp_element.visible = player_allowed_edit
-- Set the tooltip of the edit button
if #players_editing > 0 then
edit_warp_element.hovered_sprite = "utility/warning_icon"
edit_warp_element.tooltip = { "warp-list.edit-tooltip", table.concat(players_editing, ", ") }
else
edit_warp_element.hovered_sprite = edit_warp_element.sprite
edit_warp_element.tooltip = { "warp-list.edit-tooltip-none" }
end
-- Set the visibility of the warp elements based on whether the user is editing or not
local player_is_editing = warp.currently_editing[player.name]
if player_is_editing then
-- Set the icon elements visibility
warp_icon_element.visible = false
warp_icon_edit_element.visible = true
-- Set the name elements visibility
label_element.visible = false
textfield_element.visible = true
textfield_element.focus()
warp_table.parent.scroll_to_element(textfield_element, "top-third")
-- Set the edit buttons
cancel_edit_element.visible = true
confirm_edit_element.visible = true
-- Set the warp buttons
edit_warp_element.visible = false
remove_warp_element.visible = false
else
-- Set the icon elements visibility
warp_icon_element.visible = true
-- The SpritePath type is not the same as the SignalID type
local sprite = warp.icon.type .. "/" .. warp.icon.name
if warp.icon.type == "virtual" then
sprite = "virtual-signal/" .. warp.icon.name
end
warp_icon_element.sprite = sprite
-- Set icon edit to the warps icon
warp_icon_edit_element.elem_value = warp.icon
warp_icon_edit_element.visible = false
-- Set the name elements visibility
label_element.visible = true
label_element.caption = warp.name
textfield_element.visible = false
textfield_element.text = warp.name
-- Set the edit buttons
cancel_edit_element.visible = false
confirm_edit_element.visible = false
-- Set the warp buttons
edit_warp_element.visible = true and player_allowed_edit
remove_warp_element.visible = true and player_allowed_edit
end
local timer = PlayerCooldown:get(player)
local current_warp_id = PlayerInRange:get(player)
local to_warp = current_warp_id and Warps.get_warp(current_warp_id) or nil
local bypass_warp_proximity = check_player_permissions(player, "bypass_warp_proximity")
update_warp_elements(warp_icon_element, warp, to_warp, timer > 0, bypass_warp_proximity)
end
-- Update all the warps for a player
local function update_all_warps(player, warp_table)
local warp_ids = Warps.get_force_warp_ids(player.force.name)
warp_table.clear()
for _, warp_id in ipairs(warp_ids) do
update_warp(player, warp_table, warp_id)
end
end
-- Update all warps for all players on a force
local function update_all_warp_force(force)
local warp_ids = Warps.get_force_warp_ids(force.name)
for _, player in pairs(force.connected_players) do
local container = Gui.get_left_element(warp_list_container, player)
local warp_table = container.frame.scroll.table
warp_table.clear() -- Needed to re-sort the warps
for _, warp_id in ipairs(warp_ids) do
update_warp(player, warp_table, warp_id)
end
end
end
--- Main warp list container for the left flow
-- @element warp_list_container
warp_list_container = Gui.define("warp_list_container")
:draw(function(def, parent)
local player = Gui.get_player(parent)
-- Check if user has permission to add warps
local allow_add_warp = check_player_permissions(player, "allow_add_warp")
-- Draw the internal container
local container = Gui.elements.container(parent, allow_add_warp and 268 or 220)
-- Draw the header
local header = Gui.elements.header(container, {
name = "header",
caption = { "warp-list.main-caption" },
tooltip = {
"warp-list.sub-tooltip",
config.cooldown_duration,
config.standard_proximity_radius,
{ "warp-list.sub-tooltip-current", warp_status_icons.current },
{ "warp-list.sub-tooltip-connected", warp_status_icons.connected },
{ "warp-list.sub-tooltip-different", warp_status_icons.different },
{ "warp-list.sub-tooltip-cooldown", warp_status_icons.cooldown },
{ "warp-list.sub-tooltip-not_available", warp_status_icons.not_available },
{ "warp-list.sub-tooltip-bypass", warp_status_icons.bypass },
},
})
-- Draw the new warp button
local add_new_warp_element = add_new_warp(header)
add_new_warp_element.visible = allow_add_warp
-- Draw the scroll table for the warps
local scroll_table = Gui.elements.scroll_table(container, 250, 3, "scroll")
-- Set the scroll panel to always show the scrollbar (not doing this will result in a changing gui size)
assert(scroll_table.parent).vertical_scroll_policy = "always"
-- Change the style of the scroll table
local scroll_table_style = scroll_table.style
scroll_table_style.top_cell_padding = 3
scroll_table_style.bottom_cell_padding = 3
-- Draw the warp cooldown progress bar
local warp_timer_element = warp_timer(container)
-- Change the progress of the warp timer
local timer = PlayerCooldown:get(player)
if timer > 0 then
warp_timer_element.tooltip = { "warp-list.timer-tooltip", math.floor(timer / config.update_smoothing) }
warp_timer_element.value = 1 - (timer / config.update_smoothing / config.cooldown_duration)
else
warp_timer_element.tooltip = { "warp-list.timer-tooltip-zero", config.cooldown_duration }
warp_timer_element.value = 1
end
-- Add any existing warps
update_all_warps(player, scroll_table)
-- Return the external container
return container.parent
end)
--- Add the element to the left flow with a toolbar button
Gui.add_left_element(warp_list_container, false)
Gui.toolbar.create_button{
name = "warp_list_toggle",
left_element = warp_list_container,
sprite = config.default_icon.type .. "/" .. config.default_icon.name,
tooltip = { "warp-list.main-tooltip" },
visible = function(player, element)
return Roles.player_has_permission(player, "exp_scenario.gui.warp_list")
end
}:on_click(function(def, player, element)
-- Set gui keep open state for player that clicked the button: true if visible, false if invisible
keep_gui_open[player.name] = Gui.toolbar.get_button_toggled_state(def, player)
end)
--- When the name of a warp is updated this is triggered
Warps.on_update(function(_, warp, old_warp)
-- Get the force to update, warp is nil when removed
if warp then
update_all_warp_force(game.forces[warp.force_name])
else
update_all_warp_force(game.forces[old_warp.force_name])
end
end)
--- When the player leaves or enters range of a warp this is triggered
PlayerInRange:on_update(function(player_name, warp_id)
local player = game.players[player_name]
-- Change if the frame is visible based on if the player is in range
if not keep_gui_open[player.name] then
Gui.toolbar.set_left_element_visible_state(warp_list_container, player, warp_id ~= nil)
end
update_all_warp_elements(player, nil, warp_id)
end)
--- Update the warp cooldown progress bars to match the current cooldown
PlayerCooldown:on_update(function(player_name, player_cooldown)
-- Get the progress bar element
local player = game.players[player_name]
local container = Gui.get_left_element(warp_list_container, player)
local warp_timer_element = container.frame[warp_timer.name]
-- Set the progress
if player_cooldown and player_cooldown > 0 then
warp_timer_element.tooltip = { "warp-list.timer-tooltip", math.floor(player_cooldown / config.update_smoothing) }
warp_timer_element.value = 1 - (player_cooldown / config.update_smoothing / config.cooldown_duration)
else
warp_timer_element.tooltip = { "warp-list.timer-tooltip-zero", config.cooldown_duration }
warp_timer_element.value = 1
end
-- Trigger update of buttons if cooldown is now 0
if player_cooldown == 0 then
update_all_warp_elements(player, player_cooldown, nil)
end
end)
--- Handles updating the timer and checking distance from a warp
local r2 = config.standard_proximity_radius ^ 2
local rs2 = config.spawn_proximity_radius ^ 2
local mr2 = config.minimum_distance ^ 2
Event.on_nth_tick(math.floor(60 / config.update_smoothing), function()
PlayerCooldown:update_all(function(_, player_cooldown)
if player_cooldown > 0 then return player_cooldown - 1 end
end)
local force_warps = {}
local warps = {}
for _, player in pairs(game.connected_players) do
local was_in_range = PlayerInRange:get(player)
-- Get the ids of all the warps on the players force
local force_name = player.force.name
local warp_ids = force_warps[force_name]
if not warp_ids then
warp_ids = Warps.get_force_warp_ids(force_name)
force_warps[force_name] = warp_ids
end
-- Check if the force has any warps
local closest_warp = nil --- @type { warp_id: string, name: string }?
local closest_distance = nil
if #warp_ids > 0 then
local surface = player.surface
local pos = player.physical_position
local px, py = pos.x, pos.y
-- Loop over each warp
for _, warp_id in ipairs(warp_ids) do
-- Check if warp id is cached
local warp = warps[warp_id]
if not warp then
warp = Warps.get_warp(warp_id)
warps[warp_id] = warp
end
-- Check if the player is within range
local warp_pos = warp.position
if warp.surface == surface then
local dx, dy = px - warp_pos.x, py - warp_pos.y
local dist = (dx * dx) + (dy * dy)
if closest_distance == nil or dist < closest_distance then
closest_warp = warp
closest_distance = dist
if dist < r2 then break end
end
end
end
-- Check the dist to the closest warp
local in_range = closest_warp ~= nil and (closest_warp.warp_id == warp_ids.spawn and closest_distance < rs2 or closest_distance < r2)
if was_in_range and not in_range then
PlayerInRange:set(player, nil)
elseif not was_in_range and in_range then
--- @cast closest_warp -nil
PlayerInRange:set(player, closest_warp.warp_id)
end
-- Change the enabled state of the add warp button
local container = Gui.get_left_element(warp_list_container, player)
local add_warp_element = container.frame.header[add_new_warp.name]
local old_closest_warp_name = add_warp_element.tooltip[2] or closest_warp and closest_warp.name
local was_able_to_make_warp = add_warp_element.enabled
local can_make_warp = closest_distance == nil or closest_distance > mr2
if can_make_warp and not was_able_to_make_warp then
add_warp_element.enabled = true
add_warp_element.tooltip = { "warp-list.add-tooltip" }
elseif not can_make_warp and was_able_to_make_warp or closest_warp and (old_closest_warp_name ~= closest_warp.name) then
--- @cast closest_warp -nil
add_warp_element.enabled = false
add_warp_element.tooltip = { "warp-list.too-close", closest_warp.name }
end
end
end
end)
--- When a player is created make sure that there is a spawn warp created
Event.add(defines.events.on_player_created, function(event)
-- If the force has no spawn then make a spawn warp
local player = game.players[event.player_index]
local force = player.force --[[@as LuaForce]]
local spawn_id = Warps.get_spawn_warp_id(force.name)
if not spawn_id then
local spawn_position = force.get_spawn_position(player.surface)
spawn_id = Warps.add_warp(force.name, player.surface, spawn_position, nil, "Spawn")
Warps.set_spawn_warp(spawn_id, force)
Warps.make_warp_tag(spawn_id)
local entities = player.surface.find_entities_filtered{ type = "electric-pole", position = spawn_position, radius = 20, limit = 1 }
if entities and entities[1] then
local warp = Warps.get_warp(spawn_id)
warp.electric_pole = entities[1]
end
end
end)
--- Update the warps when the player joins
Event.add(defines.events.on_player_joined_game, function(event)
local player = game.players[event.player_index]
local container = Gui.get_left_element(warp_list_container, player)
local scroll_table = container.frame.scroll.table
update_all_warps(player, scroll_table)
end)
--- Makes sure the right buttons are present when roles change
local function role_update_event(event)
local player = game.players[event.player_index]
local frame = Gui.get_left_element(warp_list_container, player).frame
-- Check if user has permission to add warps
local allow_add_warp = check_player_permissions(player, "allow_add_warp")
-- Update container size depending on whether the player is allowed to add warps
assert(frame.parent).style.width = allow_add_warp and 268 or 220
-- Update the warps, in case the user can now edit them
local scroll_table = frame.scroll.table
update_all_warps(player, scroll_table)
-- Update the new warp button in case the user can now add them
local add_new_warp_element = frame.header[add_new_warp.name]
add_new_warp_element.visible = allow_add_warp
end
Event.add(Roles.events.on_player_roles_changed, role_update_event)
--- When a chart tag is removed or edited make sure it is not one that belongs to a warp
local function maintain_tag(event)
if not event.player_index then return end
local tag = event.tag
local force_name = event.force.name
local warp_ids = Warps.get_force_warp_ids(force_name)
for _, warp_id in pairs(warp_ids) do
local warp = Warps.get_warp(warp_id)
local warp_tag = warp.tag
if not warp_tag or not warp_tag.valid or warp_tag == tag then
if event.name == defines.events.on_chart_tag_removed then
warp.tag = nil
end
Warps.make_warp_tag(warp_id)
end
end
end
Event.add(defines.events.on_chart_tag_modified, maintain_tag)
Event.add(defines.events.on_chart_tag_removed, maintain_tag)