Replace spaces with tabs for Lua, and more (#399)

Convert code indents to tabs to be consistent with the rest of the
JavaScript code.  This commits covers all of the lua code, some of the
hand written JSON code and the lone HTML and CSS files that were not
using tabs.
This commit is contained in:
Hornwitser authored and GitHub committed 2021-07-13 17:18:44 +02:00
1 parent dbe01c6c23
commit dbe623c9a7
18 files changed
+673 -673

No files matched your search

+2 -2
View File
@@ -224,9 +224,9 @@ JavaScript template literals may also be used where appropriate.
### Indenting ### Indenting
JavaScript code should be indented with tabs. JavaScript and Lua code should be indented with tabs.
Lua code should be indented with 4 spaces. Other files types should prefer tabs for indents where reasonable with the exception of Markdown.
### Line Length ### Line Length
+21 -21
View File
@@ -1,23 +1,23 @@
{ {
"plugins": [ "plugins": [
"plugins/markdown" "plugins/markdown"
], ],
"tags": { "tags": {
"allowUnknownTags": false "allowUnknownTags": false
}, },
"opts": { "opts": {
"destination": "docs/api", "destination": "docs/api",
"recurse": true "recurse": true
}, },
"source": { "source": {
"include": [ "include": [
"packages/master/src/", "packages/master/src/",
"packages/master/master.js", "packages/master/master.js",
"packages/slave/slave.js", "packages/slave/slave.js",
"packages/ctl/ctl.js", "packages/ctl/ctl.js",
"packages/lib/", "packages/lib/",
"plugins/" "plugins/"
], ],
"excludePattern": "node_modules" "excludePattern": "node_modules"
} }
} }
+14 -14
View File
@@ -1,17 +1,17 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#2a2a2a" /> <meta name="theme-color" content="#2a2a2a" />
<title>Clusterio</title> <title>Clusterio</title>
<script> <script>
window.webRoot = new URL("__WEB_ROOT__", document.location).pathname; window.webRoot = new URL("__WEB_ROOT__", document.location).pathname;
</script> </script>
</head> </head>
<body> <body>
<noscript>You need to enable JavaScript to run this app.</noscript> <noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div> <div id="root"></div>
<script src="__WEB_ROOT__bundle.js"></script> <script src="__WEB_ROOT__bundle.js"></script>
</body> </body>
</html> </html>
+40 -40
View File
@@ -4,63 +4,63 @@ local api = {}
local initialized = false local initialized = false
function api.init() function api.init()
if initialized then if initialized then
return return
end end
initialized = true initialized = true
if remote.interfaces.clusterio_api then if remote.interfaces.clusterio_api then
api.events = remote.call("clusterio_api", "get_events") api.events = remote.call("clusterio_api", "get_events")
else else
local null_event = script.generate_event_name() local null_event = script.generate_event_name()
api.events = { api.events = {
on_instance_updated = null_event, on_instance_updated = null_event,
on_server_startup = null_event, on_server_startup = null_event,
} }
end end
end end
local function call_api(fn, ...) local function call_api(fn, ...)
if remote.interfaces.clusterio_api and remote.interfaces.clusterio_api[fn] then if remote.interfaces.clusterio_api and remote.interfaces.clusterio_api[fn] then
return remote.call("clusterio_api", fn, ...) return remote.call("clusterio_api", fn, ...)
else else
return nil return nil
end end
end end
function api.get_instance_name() function api.get_instance_name()
return call_api("get_instance_name") return call_api("get_instance_name")
end end
function api.get_instance_id() function api.get_instance_id()
return call_api("get_instance_id") return call_api("get_instance_id")
end end
function api.send_json(channel, data) function api.send_json(channel, data)
if not remote.interfaces.clusterio_api then if not remote.interfaces.clusterio_api then
return return
end end
-- Escape bad characters. The question mark is used for separating the -- Escape bad characters. The question mark is used for separating the
-- channel name from the payload. -- channel name from the payload.
channel = channel:gsub("([\x00-\x1f?\\])", function(match) channel = channel:gsub("([\x00-\x1f?\\])", function(match)
return "\\x" .. string.format("%02x", match:byte()) return "\\x" .. string.format("%02x", match:byte())
end) end)
data = game.table_to_json(data) data = game.table_to_json(data)
-- If there's more than about 4kB of data users running with the Windows -- If there's more than about 4kB of data users running with the Windows
-- console open will start to experience stuttering, otherwise we could -- console open will start to experience stuttering, otherwise we could
-- output about 1 MB of data at a time through stdout. -- output about 1 MB of data at a time through stdout.
if #data < 4000 then if #data < 4000 then
print("\f$ipc:" .. channel .. "?j" .. data) print("\f$ipc:" .. channel .. "?j" .. data)
else else
local file_no = remote.call("clusterio_api", "get_file_no") local file_no = remote.call("clusterio_api", "get_file_no")
local file_name = "clst_" .. file_no .. ".json" local file_name = "clst_" .. file_no .. ".json"
game.write_file(file_name, data, false, 0) game.write_file(file_name, data, false, 0)
print("\f$ipc:" .. channel .. "?f" .. file_name) print("\f$ipc:" .. channel .. "?f" .. file_name)
end end
end end
+22 -22
View File
@@ -1,24 +1,24 @@
{ {
"name": "clusterio_lib", "name": "clusterio_lib",
"variants": [ "variants": [
{ {
"version": "0.1.0", "version": "0.1.0",
"factorio_version": "0.17" "factorio_version": "0.17"
}, },
{ {
"version": "0.1.1", "version": "0.1.1",
"factorio_version": "0.18" "factorio_version": "0.18"
}, },
{ {
"version": "0.1.2", "version": "0.1.2",
"factorio_version": "1.1" "factorio_version": "1.1"
} }
], ],
"title": "Clusterio Library (Alpha)", "title": "Clusterio Library (Alpha)",
"author": "Clusterio Team", "author": "Clusterio Team",
"homepage": "https://github.com/clusterio/clusterio", "homepage": "https://github.com/clusterio/clusterio",
"description": "Library for interfacing with Clusterio. Warning: work in progress alpha.", "description": "Library for interfacing with Clusterio. Warning: work in progress alpha.",
"additional_files": { "additional_files": {
"serialize.lua": ["..", "..", "modules", "clusterio", "serialize.lua"] "serialize.lua": ["..", "..", "modules", "clusterio", "serialize.lua"]
} }
} }
+3 -3
View File
@@ -1,8 +1,8 @@
local function send_json(channel, data) local function send_json(channel, data)
data = game.table_to_json(data) data = game.table_to_json(data)
print("\f$ipc:" .. channel .. "?j" .. data) print("\f$ipc:" .. channel .. "?j" .. data)
end end
script.on_init(function() script.on_init(function()
send_json("mod_list", game.active_mods) send_json("mod_list", game.active_mods)
end) end)
+76 -76
View File
@@ -1,104 +1,104 @@
local item_types = { local item_types = {
-- Item categories -- Item categories
"item", "item",
"ammo", "ammo",
"capsule", "capsule",
"gun", "gun",
"item-with-entity-data", "item-with-entity-data",
"item-with-label", "item-with-label",
"item-with-inventory", "item-with-inventory",
"blueprint-book", "blueprint-book",
"item-with-tags", "item-with-tags",
"selection-tool", "selection-tool",
"blueprint", "blueprint",
"deconstruction-item", "deconstruction-item",
"copy-paste-tool", "copy-paste-tool",
"upgrade-item", "upgrade-item",
"module", "module",
"rail-planner", "rail-planner",
"tool", "tool",
"armor", "armor",
"mining-tool", "mining-tool",
"repair-tool", "repair-tool",
-- Fluids -- Fluids
"fluid", "fluid",
} }
local function is_array(t) local function is_array(t)
local count = 0 local count = 0
for k in pairs(t) do for k in pairs(t) do
if type(k) ~= "number" then if type(k) ~= "number" then
return false return false
end end
count = count + 1 count = count + 1
end end
for i = 1, count do for i = 1, count do
if not t[i] then if not t[i] then
return false return false
end end
end end
return count ~= 0 return count ~= 0
end end
-- no game.table_to_json here :( -- no game.table_to_json here :(
local function table_to_json(data) local function table_to_json(data)
if type(data) == "number" then if type(data) == "number" then
if data == math.huge then return "1e500" end -- Inf is not representable in JSON, but 1e500 will overflow to it. if data == math.huge then return "1e500" end -- Inf is not representable in JSON, but 1e500 will overflow to it.
if data == -math.huge then return "-1e500" end if data == -math.huge then return "-1e500" end
if data ~= data then return "0" end -- NaN is not representable in JSON, treat as 0 instead. if data ~= data then return "0" end -- NaN is not representable in JSON, treat as 0 instead.
return string.format("%.17g", data) return string.format("%.17g", data)
elseif type(data) == "string" then elseif type(data) == "string" then
data = data:gsub('([\x00-\x1f\\"])', function(match) data = data:gsub('([\x00-\x1f\\"])', function(match)
return "\\u00" .. string.format("%02x", match:byte()) return "\\u00" .. string.format("%02x", match:byte())
end) end)
return '"' .. data .. '"' return '"' .. data .. '"'
elseif data == nil then elseif data == nil then
return "null" return "null"
elseif data == true then elseif data == true then
return "true" return "true"
elseif data == false then elseif data == false then
return "false" return "false"
elseif type(data) == "table" then elseif type(data) == "table" then
local r local r
if is_array(data) then if is_array(data) then
r = {"["} r = {"["}
for i=1, #data do for i=1, #data do
r[#r+1] = table_to_json(data[i]) r[#r+1] = table_to_json(data[i])
r[#r+1] = "," r[#r+1] = ","
end end
-- overwrite last comma, empty table is an object -- overwrite last comma, empty table is an object
r[#r] = "]" r[#r] = "]"
else else
r = {"{"} r = {"{"}
for k, v in pairs(data) do for k, v in pairs(data) do
r[#r+1] = table_to_json(tostring(k)) r[#r+1] = table_to_json(tostring(k))
r[#r+1] = ":" r[#r+1] = ":"
r[#r+1] = table_to_json(v) r[#r+1] = table_to_json(v)
r[#r+1] = "," r[#r+1] = ","
end end
r[#r + (r[#r] == "," and 0 or 1)] = "}" r[#r + (r[#r] == "," and 0 or 1)] = "}"
end end
return table.concat(r) return table.concat(r)
end end
end end
local function send_json(channel, data) local function send_json(channel, data)
data = table_to_json(data) data = table_to_json(data)
print("\f$ipc:" .. channel .. "?j" .. data) print("\f$ipc:" .. channel .. "?j" .. data)
end end
for _, group in ipairs(item_types) do for _, group in ipairs(item_types) do
for _, item in pairs(data.raw[group]) do for _, item in pairs(data.raw[group]) do
send_json("item_export", item) send_json("item_export", item)
end end
end end
+6 -6
View File
@@ -1,8 +1,8 @@
{ {
"name": "export", "name": "export",
"version": "0.0.0", "version": "0.0.0",
"title": "Icon exporter", "title": "Icon exporter",
"author": "Clusterio Team", "author": "Clusterio Team",
"homepage": "https://github.com/clusterio/clusterio", "homepage": "https://github.com/clusterio/clusterio",
"description": "Exports item prototypes on stdout during the data stage." "description": "Exports item prototypes on stdout during the data stage."
} }
+21 -21
View File
@@ -3,39 +3,39 @@ local api = {}
api.events = { api.events = {
on_instance_updated = script.generate_event_name(), on_instance_updated = script.generate_event_name(),
on_server_startup = script.generate_event_name(), on_server_startup = script.generate_event_name(),
} }
function api.get_instance_name() function api.get_instance_name()
return global.clusterio.instance_name return global.clusterio.instance_name
end end
function api.get_instance_id() function api.get_instance_id()
return global.clusterio.instance_id return global.clusterio.instance_id
end end
function api.send_json(channel, data) function api.send_json(channel, data)
-- Escape bad characters. The question mark is used for separating the -- Escape bad characters. The question mark is used for separating the
-- channel name from the payload. -- channel name from the payload.
channel = channel:gsub("([\x00-\x1f?\\])", function(match) channel = channel:gsub("([\x00-\x1f?\\])", function(match)
return "\\x" .. string.format("%02x", match:byte()) return "\\x" .. string.format("%02x", match:byte())
end) end)
data = game.table_to_json(data) data = game.table_to_json(data)
-- If there's more than about 4kB of data users running with the Windows -- If there's more than about 4kB of data users running with the Windows
-- console open will start to experience stuttering, otherwise we could -- console open will start to experience stuttering, otherwise we could
-- output about 1 MB of data at a time through stdout. -- output about 1 MB of data at a time through stdout.
if #data < 4000 then if #data < 4000 then
print("\f$ipc:" .. channel .. "?j" .. data) print("\f$ipc:" .. channel .. "?j" .. data)
else else
global.clusterio_file_no = (global.clusterio_file_no or 0) + 1 global.clusterio_file_no = (global.clusterio_file_no or 0) + 1
local file_name = "clst_" .. global.clusterio_file_no .. ".json" local file_name = "clst_" .. global.clusterio_file_no .. ".json"
game.write_file(file_name, data, false, 0) game.write_file(file_name, data, false, 0)
print("\f$ipc:" .. channel .. "?f" .. file_name) print("\f$ipc:" .. channel .. "?f" .. file_name)
end end
end end
+36 -36
View File
@@ -5,69 +5,69 @@ local impl = {}
impl.events = {} impl.events = {}
impl.events[defines.events.on_tick] = function() impl.events[defines.events.on_tick] = function()
if global.clusterio_patch_number ~= clusterio_patch_number then if global.clusterio_patch_number ~= clusterio_patch_number then
global.clusterio_patch_number = clusterio_patch_number global.clusterio_patch_number = clusterio_patch_number
script.raise_event(api.events.on_server_startup, {}) script.raise_event(api.events.on_server_startup, {})
end end
end end
impl.events[api.events.on_server_startup] = function() impl.events[api.events.on_server_startup] = function()
if not global.clusterio then if not global.clusterio then
global.clusterio = { global.clusterio = {
instance_id = nil, instance_id = nil,
instance_name = nil, instance_name = nil,
} }
end end
-- Replay will just desync after the save is patched -- Replay will just desync after the save is patched
game.disable_replay() game.disable_replay()
end end
impl.events[defines.events.on_player_joined_game] = function(event) impl.events[defines.events.on_player_joined_game] = function(event)
local player = game.players[event.player_index] local player = game.players[event.player_index]
api.send_json("player_event", { type = "join", name = player.name }) api.send_json("player_event", { type = "join", name = player.name })
end end
impl.events[defines.events.on_player_left_game] = function(event) impl.events[defines.events.on_player_left_game] = function(event)
local player = game.players[event.player_index] local player = game.players[event.player_index]
api.send_json("player_event", { type = "leave", name = player.name }) api.send_json("player_event", { type = "leave", name = player.name })
end end
-- Internal API -- Internal API
clusterio_private = {} clusterio_private = {}
function clusterio_private.update_instance(new_id, new_name) function clusterio_private.update_instance(new_id, new_name)
global.clusterio.instance_id = new_id global.clusterio.instance_id = new_id
global.clusterio.instance_name = new_name global.clusterio.instance_name = new_name
script.raise_event(api.events.on_instance_updated, { script.raise_event(api.events.on_instance_updated, {
instance_id = new_id, instance_id = new_id,
instance_name = new_name, instance_name = new_name,
}) })
end end
-- This is not part of the add_remote_interface callback to ensure it is -- This is not part of the add_remote_interface callback to ensure it is
-- available when the clusterio_lib mod is loaded. The reason this is -- available when the clusterio_lib mod is loaded. The reason this is
-- neccessary is that on_init for newly added mods happen before on_load -- neccessary is that on_init for newly added mods happen before on_load
-- for existing mods, and the add_remote_interface callback is done in -- for existing mods, and the add_remote_interface callback is done in
-- on_load. See https://forums.factorio.com/viewtopic.php?f=25&t=81552 for -- on_load. See https://forums.factorio.com/viewtopic.php?f=25&t=81552 for
-- more details. -- more details.
remote.add_interface('clusterio_api', { remote.add_interface('clusterio_api', {
get_events = function() get_events = function()
return api.events return api.events
end, end,
get_instance_id = function() get_instance_id = function()
return global.clusterio.instance_id return global.clusterio.instance_id
end, end,
get_instance_name = function() get_instance_name = function()
return global.clusterio.instance_name return global.clusterio.instance_name
end, end,
get_file_no = function() get_file_no = function()
global.clusterio_file_no = (global.clusterio_file_no or 0) + 1 global.clusterio_file_no = (global.clusterio_file_no or 0) + 1
return global.clusterio_file_no return global.clusterio_file_no
end, end,
}) })
+4 -4
View File
@@ -1,6 +1,6 @@
{ {
"name": "clusterio", "name": "clusterio",
"version": "0.0.0", "version": "0.0.0",
"dependencies": {}, "dependencies": {},
"load": ["impl.lua"] "load": ["impl.lua"]
} }
+237 -237
View File
@@ -3,38 +3,38 @@
local serialize = {} local serialize = {}
local function version_to_table(version) local function version_to_table(version)
local t = {} local t = {}
for p in string.gmatch(version, "%d+") do for p in string.gmatch(version, "%d+") do
t[#t + 1] = tonumber(p) t[#t + 1] = tonumber(p)
end end
return t return t
end end
-- 0.17 compatibility -- 0.17 compatibility
local supports_bar, get_bar, has_bar, version local supports_bar, get_bar, has_bar, version
if (pcall(function() local mods = script.active_mods end)) then if (pcall(function() local mods = script.active_mods end)) then
supports_bar = "supports_bar" supports_bar = "supports_bar"
get_bar = "get_bar" get_bar = "get_bar"
set_bar = "set_bar" set_bar = "set_bar"
version = version_to_table(script.active_mods.base) version = version_to_table(script.active_mods.base)
else else
supports_bar = "hasbar" supports_bar = "hasbar"
get_bar = "getbar" get_bar = "getbar"
set_bar = "setbar" set_bar = "setbar"
version = version_to_table("0.17.69") version = version_to_table("0.17.69")
end end
-- returns true if the game version is greater than or equal to the given version -- returns true if the game version is greater than or equal to the given version
local function version_ge(comp) local function version_ge(comp)
comp = version_to_table(comp) comp = version_to_table(comp)
for i=1, 3 do for i=1, 3 do
if comp[i] > version[i] then if comp[i] > version[i] then
return false return false
elseif comp[i] < version[i] then elseif comp[i] < version[i] then
return true return true
end end
end end
return true return true
end end
local has_create_grid = version_ge("1.1.7") local has_create_grid = version_ge("1.1.7")
@@ -42,265 +42,265 @@ local has_create_grid = version_ge("1.1.7")
-- Equipment Grids are serialized into an array of equipment entries -- Equipment Grids are serialized into an array of equipment entries
-- where ench entry is a table with the following fields: -- where ench entry is a table with the following fields:
-- n: name -- n: name
-- p: position (array of 2 numbers corresponding to x and y) -- p: position (array of 2 numbers corresponding to x and y)
-- s: shield (optional) -- s: shield (optional)
-- e: energy (optional) -- e: energy (optional)
-- If the equipment is a burner the following is also present: -- If the equipment is a burner the following is also present:
-- i: burner inventory -- i: burner inventory
-- r: result inventory -- r: result inventory
-- b: curently burning (optional) -- b: curently burning (optional)
-- f: remaining_burning_fuel (optional) -- f: remaining_burning_fuel (optional)
function serialize.serialize_equipment_grid(grid) function serialize.serialize_equipment_grid(grid)
local serialized = {} local serialized = {}
local processed = {} local processed = {}
for y = 0, grid.height - 1 do for y = 0, grid.height - 1 do
for x = 0, grid.width - 1 do for x = 0, grid.width - 1 do
local equipment = grid.get({x, y}) local equipment = grid.get({x, y})
if equipment ~= nil then if equipment ~= nil then
local pos = equipment.position local pos = equipment.position
local combined_pos = pos.x + pos.y * grid.width + 1 local combined_pos = pos.x + pos.y * grid.width + 1
if not processed[combined_pos] then if not processed[combined_pos] then
processed[combined_pos] = true processed[combined_pos] = true
local entry = { local entry = {
n = equipment.name, n = equipment.name,
p = {pos.x, pos.y}, p = {pos.x, pos.y},
} }
if equipment.shield > 0 then entry.s = equipment.shield end if equipment.shield > 0 then entry.s = equipment.shield end
if equipment.energy > 0 then entry.e = equipment.energy end if equipment.energy > 0 then entry.e = equipment.energy end
-- TODO: Test with Industrial Revolution -- TODO: Test with Industrial Revolution
if equipment.burner then if equipment.burner then
local burner = equipment.burner local burner = equipment.burner
entry.i = serialize.serialize_inventory(burner.inventory) entry.i = serialize.serialize_inventory(burner.inventory)
entry.r = serialize.serialize_inventory(burner.burnt_result_inventory) entry.r = serialize.serialize_inventory(burner.burnt_result_inventory)
if burner.curently_burning then if burner.curently_burning then
entry.b = {} entry.b = {}
serialize.serialize_item_stack(burner.curently_burning, entry.b) serialize.serialize_item_stack(burner.curently_burning, entry.b)
entry.f = burner.remaining_burning_fuel entry.f = burner.remaining_burning_fuel
end end
end end
table.insert(serialized, entry) table.insert(serialized, entry)
end end
end end
end end
end end
return serialized return serialized
end end
function serialize.deserialize_equipment_grid(grid, serialized) function serialize.deserialize_equipment_grid(grid, serialized)
grid.clear() grid.clear()
for _, entry in ipairs(serialized) do for _, entry in ipairs(serialized) do
local equipment = grid.put({ local equipment = grid.put({
name = entry.n, name = entry.n,
position = entry.p, position = entry.p,
}) })
if equipment then if equipment then
if entry.s then equipment.shield = entry.s end if entry.s then equipment.shield = entry.s end
if entry.e then equipment.energy = entry.e end if entry.e then equipment.energy = entry.e end
if entry.i then if entry.i then
if entry.b then serialize.deserialize_item_stack(burner.currently_burning, entry.b) end if entry.b then serialize.deserialize_item_stack(burner.currently_burning, entry.b) end
if entry.f then burner.remaining_burning_fuel = entry.f end if entry.f then burner.remaining_burning_fuel = entry.f end
serialize.deserialize_inventory(burner.burnt_result_inventory, entry.r) serialize.deserialize_inventory(burner.burnt_result_inventory, entry.r)
serialize.deserialize_inventory(burner.inventory, entry.i) serialize.deserialize_inventory(burner.inventory, entry.i)
end end
end end
end end
end end
-- Item stacks are serialized into a table with the following fields: -- Item stacks are serialized into a table with the following fields:
-- n: name -- n: name
-- c: count -- c: count
-- h: health (optional) -- h: health (optional)
-- d: durability (optional) -- d: durability (optional)
-- a: ammo count (optional) -- a: ammo count (optional)
-- l: label (optional) -- l: label (optional)
-- g: equipment grid (optional) -- g: equipment grid (optional)
-- i: item inventory (optional) -- i: item inventory (optional)
-- If the item stack is exportable it has the following property instead -- If the item stack is exportable it has the following property instead
-- e: export string -- e: export string
-- Label is a table with the following fields: -- Label is a table with the following fields:
-- t: label text (optional) -- t: label text (optional)
-- c: color (optional) -- c: color (optional)
-- a: allow manual label change -- a: allow manual label change
function serialize.serialize_item_stack(slot, entry) function serialize.serialize_item_stack(slot, entry)
if if
slot.is_blueprint slot.is_blueprint
or slot.is_blueprint_book or slot.is_blueprint_book
or slot.is_upgrade_item or slot.is_upgrade_item
or slot.is_deconstruction_item or slot.is_deconstruction_item
or slot.is_item_with_tags or slot.is_item_with_tags
then then
local call_success, call_return = pcall(slot.export_stack) local call_success, call_return = pcall(slot.export_stack)
if not call_success then if not call_success then
print("Error: '" .. call_return .. "' thrown exporting '" .. slot.name .. "'") print("Error: '" .. call_return .. "' thrown exporting '" .. slot.name .. "'")
else else
entry.e = call_return entry.e = call_return
end end
return return
end end
entry.n = slot.name entry.n = slot.name
entry.c = slot.count entry.c = slot.count
if slot.health < 1 then entry.h = slot.health end if slot.health < 1 then entry.h = slot.health end
if slot.durability then entry.d = slot.durability end if slot.durability then entry.d = slot.durability end
if slot.type == "ammo" then entry.a = slot.ammo end if slot.type == "ammo" then entry.a = slot.ammo end
if slot.is_item_with_label then if slot.is_item_with_label then
local label = {} local label = {}
if slot.label then label.t = slot.label end if slot.label then label.t = slot.label end
if slot.label_color then label.c = slot.label_color end if slot.label_color then label.c = slot.label_color end
label.a = slot.allow_manual_label_change label.a = slot.allow_manual_label_change
entry.l = label entry.l = label
end end
if slot.grid then if slot.grid then
entry.g = serialize.serialize_equipment_grid(slot.grid) entry.g = serialize.serialize_equipment_grid(slot.grid)
end end
if slot.is_item_with_inventory then if slot.is_item_with_inventory then
local sub_inventory = slot.get_inventory(defines.inventory.item_main) local sub_inventory = slot.get_inventory(defines.inventory.item_main)
entry.i = serialize.serialize_inventory(sub_inventory) entry.i = serialize.serialize_inventory(sub_inventory)
end end
end end
function serialize.deserialize_item_stack(slot, entry) function serialize.deserialize_item_stack(slot, entry)
if entry.e then if entry.e then
local success = slot.import_stack(entry.e) local success = slot.import_stack(entry.e)
if success == 1 then if success == 1 then
print("Error: import of '" .. entry.e .. "' succeeded with errors") print("Error: import of '" .. entry.e .. "' succeeded with errors")
elseif success == -1 then elseif success == -1 then
print("Error: import of '" .. entry.e .. "' failed") print("Error: import of '" .. entry.e .. "' failed")
end end
return return
end end
local item_stack = { local item_stack = {
name = entry.n, name = entry.n,
count = entry.c, count = entry.c,
} }
if entry.h then item_stack.health = entry.h end if entry.h then item_stack.health = entry.h end
if entry.d then item_stack.durability = entry.d end if entry.d then item_stack.durability = entry.d end
if entry.a then item_stack.ammo = entry.a end if entry.a then item_stack.ammo = entry.a end
local call_success, call_return = pcall(slot.set_stack, item_stack) local call_success, call_return = pcall(slot.set_stack, item_stack)
if not call_success then if not call_success then
print("Error: '" .. call_return .. "' thrown setting stack ".. serpent.line(entry)) print("Error: '" .. call_return .. "' thrown setting stack ".. serpent.line(entry))
elseif not call_return then elseif not call_return then
print("Error: Failed to set stack " .. serpent.line(entry)) print("Error: Failed to set stack " .. serpent.line(entry))
else else
if entry.l then if entry.l then
-- TODO test this with AAI's unit-remote-control -- TODO test this with AAI's unit-remote-control
local label = entry.l local label = entry.l
if label.t then slot.label = label.t end if label.t then slot.label = label.t end
if label.c then slot.label_color = label.c end if label.c then slot.label_color = label.c end
slot.allow_manual_label_change = label.a slot.allow_manual_label_change = label.a
end end
if entry.g then if entry.g then
if slot.grid then if slot.grid then
serialize.deserialize_equipment_grid(slot.grid, entry.g) serialize.deserialize_equipment_grid(slot.grid, entry.g)
elseif slot.type == "item-with-entity-data" and has_create_grid then elseif slot.type == "item-with-entity-data" and has_create_grid then
slot.create_grid() slot.create_grid()
serialize.deserialize_equipment_grid(slot.grid, entry.g) serialize.deserialize_equipment_grid(slot.grid, entry.g)
else else
print("Error: Attempt to deserialize equipment grid on an unsupported entity") print("Error: Attempt to deserialize equipment grid on an unsupported entity")
end end
end end
if entry.i then if entry.i then
local sub_inventory = slot.get_inventory(defines.inventory.item_main) local sub_inventory = slot.get_inventory(defines.inventory.item_main)
serialize.deserialize_inventory(sub_inventory, entry.i) serialize.deserialize_inventory(sub_inventory, entry.i)
end end
end end
end end
-- Inventories are serialized into a table with the following fields: -- Inventories are serialized into a table with the following fields:
-- i: array of item stack or exportable item entries -- i: array of item stack or exportable item entries
-- b: bar position (optional) -- b: bar position (optional)
-- Each item entry has the following fields -- Each item entry has the following fields
-- s: index (optional, equals to previous plus one if not present) -- s: index (optional, equals to previous plus one if not present)
-- r: repeat count (optional) -- r: repeat count (optional)
-- f: slot filter (optional) -- f: slot filter (optional)
-- Pluss all the fields for item stacks (see deserialize_item_stack) -- Pluss all the fields for item stacks (see deserialize_item_stack)
-- It's also possible that the slot is empty but has a slot filter. -- It's also possible that the slot is empty but has a slot filter.
function serialize.serialize_inventory(inventory) function serialize.serialize_inventory(inventory)
local serialized = {} local serialized = {}
if inventory[supports_bar]() and inventory[get_bar]() <= #inventory then if inventory[supports_bar]() and inventory[get_bar]() <= #inventory then
serialized.b = inventory[get_bar]() serialized.b = inventory[get_bar]()
end end
serialized.i = {} serialized.i = {}
local previous_index = 0 local previous_index = 0
local previous_serialized = nil local previous_serialized = nil
for i = 1, #inventory do for i = 1, #inventory do
local item = {} local item = {}
local slot = inventory[i] local slot = inventory[i]
if inventory.supports_filters() then if inventory.supports_filters() then
item.f = inventory.get_filter(i) item.f = inventory.get_filter(i)
end end
if slot.valid_for_read then if slot.valid_for_read then
serialize.serialize_item_stack(slot, item) serialize.serialize_item_stack(slot, item)
end end
if item.n or item.f or item.e then if item.n or item.f or item.e then
local item_serialized = game.table_to_json(item) local item_serialized = game.table_to_json(item)
if item_serialized == previous_serialized then if item_serialized == previous_serialized then
local previous_item = serialized.i[#serialized.i] local previous_item = serialized.i[#serialized.i]
previous_item.r = (previous_item.r or 0) + 1 previous_item.r = (previous_item.r or 0) + 1
previous_index = i previous_index = i
else else
if i ~= previous_index + 1 then if i ~= previous_index + 1 then
item.s = i item.s = i
end end
previous_index = i previous_index = i
previous_serialized = item_serialized previous_serialized = item_serialized
table.insert(serialized.i, item) table.insert(serialized.i, item)
end end
else else
-- Either an empty slot or serilization failed -- Either an empty slot or serilization failed
previous_index = 0 previous_index = 0
previous_serialized = nil previous_serialized = nil
end end
end end
return serialized return serialized
end end
function serialize.deserialize_inventory(inventory, serialized) function serialize.deserialize_inventory(inventory, serialized)
if serialized.b and inventory[supports_bar]() then if serialized.b and inventory[supports_bar]() then
inventory[set_bar](serialized.b) inventory[set_bar](serialized.b)
end end
local last_slot_index = 0 local last_slot_index = 0
for _, entry in ipairs(serialized.i) do for _, entry in ipairs(serialized.i) do
local base_index = entry.s or last_slot_index + 1 local base_index = entry.s or last_slot_index + 1
local repeat_count = entry.r or 0 local repeat_count = entry.r or 0
for offset = 0, repeat_count do for offset = 0, repeat_count do
-- XXX what if the inventory is smaller on this instance? -- XXX what if the inventory is smaller on this instance?
local index = base_index + offset local index = base_index + offset
local slot = inventory[index] local slot = inventory[index]
if entry.f then if entry.f then
local call_success, call_return = pcall(inventory.set_filter, index, entry.f) local call_success, call_return = pcall(inventory.set_filter, index, entry.f)
if not call_success then if not call_success then
print("Error: '" .. call_return .. "' thrown setting filter " .. entry.f) print("Error: '" .. call_return .. "' thrown setting filter " .. entry.f)
elseif not call_return then elseif not call_return then
print("Error: Failed to set filter " .. entry.f) print("Error: Failed to set filter " .. entry.f)
end end
end end
if entry.n or entry.e then if entry.n or entry.e then
serialize.deserialize_item_stack(slot, entry) serialize.deserialize_item_stack(slot, entry)
end end
end end
last_slot_index = base_index + repeat_count last_slot_index = base_index + repeat_count
end end
end end
+2 -2
View File
@@ -1,4 +1,4 @@
{ {
"name": "player_auth", "name": "player_auth",
"load": ["auth.lua"] "load": ["auth.lua"]
} }
+2 -2
View File
@@ -1,4 +1,4 @@
{ {
"name": "research_sync", "name": "research_sync",
"load": ["sync.lua"] "load": ["sync.lua"]
} }
+156 -156
View File
@@ -4,216 +4,216 @@ local sync = {}
local function get_technology_progress(tech) local function get_technology_progress(tech)
if tech == tech.force.current_research then if tech == tech.force.current_research then
return tech.force.research_progress return tech.force.research_progress
else else
return tech.force.get_saved_technology_progress(tech.name) return tech.force.get_saved_technology_progress(tech.name)
end end
end end
local function set_technology_progress(tech, progress) local function set_technology_progress(tech, progress)
if tech == tech.force.current_research then if tech == tech.force.current_research then
tech.force.research_progress = progress tech.force.research_progress = progress
else else
tech.force.set_saved_technology_progress(tech.name, progress) tech.force.set_saved_technology_progress(tech.name, progress)
end end
end end
sync.events = {} sync.events = {}
sync.events[clusterio_api.events.on_server_startup] = function(event) sync.events[clusterio_api.events.on_server_startup] = function(event)
if not global.research_sync then if not global.research_sync then
global.research_sync = { global.research_sync = {
technologies = {}, technologies = {},
} }
end end
-- Used when syncing completed technologies from the master -- Used when syncing completed technologies from the master
global.research_sync.ignore_research_finished = false global.research_sync.ignore_research_finished = false
local force = game.forces["player"] local force = game.forces["player"]
for _, tech in pairs(force.technologies) do for _, tech in pairs(force.technologies) do
if tech.enabled then if tech.enabled then
local progress = get_technology_progress(tech) local progress = get_technology_progress(tech)
global.research_sync.technologies[tech.name] = { global.research_sync.technologies[tech.name] = {
level = tech.level, level = tech.level,
researched = tech.researched, researched = tech.researched,
progress = progress, progress = progress,
} }
end end
end end
end end
local function get_contribution(tech) local function get_contribution(tech)
local progress = get_technology_progress(tech) local progress = get_technology_progress(tech)
if not progress then if not progress then
return 0, nil return 0, nil
end end
local prev_tech = global.research_sync.technologies[tech.name] local prev_tech = global.research_sync.technologies[tech.name]
if prev_tech.progress and prev_tech.level == tech.level then if prev_tech.progress and prev_tech.level == tech.level then
return progress - prev_tech.progress, progress return progress - prev_tech.progress, progress
else else
return progress, progress return progress, progress
end end
end end
local function send_contribution(tech) local function send_contribution(tech)
local contribution, progress = get_contribution(tech) local contribution, progress = get_contribution(tech)
if contribution ~= 0 then if contribution ~= 0 then
clusterio_api.send_json("research_sync:contribution", { clusterio_api.send_json("research_sync:contribution", {
name = tech.name, name = tech.name,
level = tech.level, level = tech.level,
contribution = contribution, contribution = contribution,
}) })
global.research_sync.technologies[tech.name].progress = progress global.research_sync.technologies[tech.name].progress = progress
end end
end end
sync.events[defines.events.on_research_started] = function(event) sync.events[defines.events.on_research_started] = function(event)
local tech = event.last_research local tech = event.last_research
if tech then if tech then
send_contribution(tech) send_contribution(tech)
end end
end end
sync.events[defines.events.on_research_finished] = function(event) sync.events[defines.events.on_research_finished] = function(event)
if global.research_sync.ignore_research_finished then if global.research_sync.ignore_research_finished then
return return
end end
local tech = event.research local tech = event.research
global.research_sync.technologies[tech.name] = { global.research_sync.technologies[tech.name] = {
level = tech.level, level = tech.level,
researched = tech.researched, researched = tech.researched,
} }
local level = tech.level local level = tech.level
if not tech.researched then if not tech.researched then
level = level - 1 level = level - 1
end end
clusterio_api.send_json("research_sync:finished", { clusterio_api.send_json("research_sync:finished", {
name = tech.name, name = tech.name,
level = level, level = level,
}) })
end end
sync.on_nth_tick = {} sync.on_nth_tick = {}
sync.on_nth_tick[79] = function(event) sync.on_nth_tick[79] = function(event)
local tech = game.forces["player"].current_research local tech = game.forces["player"].current_research
if tech then if tech then
send_contribution(tech) send_contribution(tech)
end end
end end
research_sync = {} research_sync = {}
function research_sync.dump_technologies() function research_sync.dump_technologies()
local force = game.forces["player"] local force = game.forces["player"]
local techs = {} local techs = {}
for _, tech in pairs(force.technologies) do for _, tech in pairs(force.technologies) do
if tech.enabled then if tech.enabled then
table.insert(techs, { table.insert(techs, {
name = tech.name, name = tech.name,
level = tech.level, level = tech.level,
progress = get_technology_progress(tech), progress = get_technology_progress(tech),
researched = tech.researched, researched = tech.researched,
}) })
end end
end end
if #techs == 0 then if #techs == 0 then
rcon.print("[]") rcon.print("[]")
else else
rcon.print(game.table_to_json(techs)) rcon.print(game.table_to_json(techs))
end end
end end
function research_sync.sync_technologies(data) function research_sync.sync_technologies(data)
local force = game.forces["player"] local force = game.forces["player"]
local nameIndex = 1 local nameIndex = 1
local levelIndex = 2 local levelIndex = 2
local progressIndex = 3 local progressIndex = 3
local researchedIndex = 4 local researchedIndex = 4
global.research_sync.ignore_research_finished = true global.research_sync.ignore_research_finished = true
for _, tech_data in pairs(game.json_to_table(data)) do for _, tech_data in pairs(game.json_to_table(data)) do
local tech = force.technologies[tech_data[nameIndex]] local tech = force.technologies[tech_data[nameIndex]]
if tech and tech.enabled and tech.level <= tech_data[levelIndex] then if tech and tech.enabled and tech.level <= tech_data[levelIndex] then
tech.level = math.min(tech_data[levelIndex], tech.prototype.max_level) tech.level = math.min(tech_data[levelIndex], tech.prototype.max_level)
local progress local progress
if tech_data[researchedIndex] then if tech_data[researchedIndex] then
tech.researched = true tech.researched = true
progress = nil progress = nil
elseif tech_data[progressIndex] then elseif tech_data[progressIndex] then
send_contribution(tech) send_contribution(tech)
progress = tech_data[progressIndex] progress = tech_data[progressIndex]
set_technology_progress(tech, progress) set_technology_progress(tech, progress)
else else
progress = get_technology_progress(tech) progress = get_technology_progress(tech)
end end
global.research_sync.technologies[tech.name] = { global.research_sync.technologies[tech.name] = {
level = tech.level, level = tech.level,
researched = tech.researched, researched = tech.researched,
progress = progress, progress = progress,
} }
end end
end end
global.research_sync.ignore_research_finished = false global.research_sync.ignore_research_finished = false
end end
function research_sync.update_progress(data) function research_sync.update_progress(data)
local techs = game.json_to_table(data) local techs = game.json_to_table(data)
local force = game.forces["player"] local force = game.forces["player"]
for _, masterTech in ipairs(techs) do for _, masterTech in ipairs(techs) do
local tech = force.technologies[masterTech.name] local tech = force.technologies[masterTech.name]
if tech and tech.enabled and tech.level == masterTech.level then if tech and tech.enabled and tech.level == masterTech.level then
send_contribution(tech) send_contribution(tech)
set_technology_progress(tech, masterTech.progress) set_technology_progress(tech, masterTech.progress)
global.research_sync.technologies[tech.name] = { global.research_sync.technologies[tech.name] = {
level = tech.level, level = tech.level,
progress = masterTech.progress progress = masterTech.progress
} }
end end
end end
end end
function research_sync.research_technology(name, level) function research_sync.research_technology(name, level)
local force = game.forces["player"] local force = game.forces["player"]
local tech = force.technologies[name] local tech = force.technologies[name]
if not tech or not tech.enabled or tech.level > level then if not tech or not tech.enabled or tech.level > level then
return return
end end
if level > tech.prototype.max_level then if level > tech.prototype.max_level then
level = tech.prototype.max_level level = tech.prototype.max_level
end end
global.research_sync.ignore_research_finished = true global.research_sync.ignore_research_finished = true
if tech == force.current_research and tech.level == level then if tech == force.current_research and tech.level == level then
force.research_progress = 1 force.research_progress = 1
elseif tech.level < level or tech.level == level and not tech.researched then elseif tech.level < level or tech.level == level and not tech.researched then
tech.level = level tech.level = level
tech.researched = true tech.researched = true
if tech.name:find("-%d+$") then if tech.name:find("-%d+$") then
game.print {"", "Researched ", {"technology-name." .. tech.name:gsub("-%d+$", "")}, " ", level} game.print {"", "Researched ", {"technology-name." .. tech.name:gsub("-%d+$", "")}, " ", level}
else else
game.print {"", "Researched ", {"technology-name." .. tech.name}} game.print {"", "Researched ", {"technology-name." .. tech.name}}
end end
game.play_sound { path = "utility/research_completed" } game.play_sound { path = "utility/research_completed" }
end end
global.research_sync.ignore_research_finished = false global.research_sync.ignore_research_finished = false
global.research_sync.technologies[tech.name] = { global.research_sync.technologies[tech.name] = {
level = tech.level, level = tech.level,
researched = tech.researched, researched = tech.researched,
} }
end end
+26 -26
View File
@@ -1,34 +1,34 @@
local statistics = { local statistics = {
"item_production_statistics", "item_production_statistics",
"fluid_production_statistics", "fluid_production_statistics",
"kill_count_statistics", "kill_count_statistics",
"entity_build_count_statistics", "entity_build_count_statistics",
} }
statistics_exporter = {} statistics_exporter = {}
function statistics_exporter.export() function statistics_exporter.export()
local stats = { local stats = {
game_tick = game.tick, game_tick = game.tick,
player_count = #game.connected_players, player_count = #game.connected_players,
game_flow_statistics = { game_flow_statistics = {
pollution_statistics = { pollution_statistics = {
input = game.pollution_statistics.input_counts, input = game.pollution_statistics.input_counts,
output = game.pollution_statistics.output_counts, output = game.pollution_statistics.output_counts,
}, },
}, },
force_flow_statistics = {} force_flow_statistics = {}
} }
for _, force in pairs(game.forces) do for _, force in pairs(game.forces) do
local flow_statistics = {} local flow_statistics = {}
for _, statName in pairs(statistics) do for _, statName in pairs(statistics) do
flow_statistics[statName] = { flow_statistics[statName] = {
input = force[statName].input_counts, input = force[statName].input_counts,
output = force[statName].output_counts, output = force[statName].output_counts,
} }
end end
stats.force_flow_statistics[force.name] = flow_statistics stats.force_flow_statistics[force.name] = flow_statistics
end end
rcon.print(game.table_to_json(stats)) rcon.print(game.table_to_json(stats))
end end
@@ -1,4 +1,4 @@
{ {
"name": "statistics_exporter", "name": "statistics_exporter",
"require": ["export.lua"] "require": ["export.lua"]
} }
+3 -3
View File
@@ -1,5 +1,5 @@
.factorio-icon { .factorio-icon {
display: inline-block; display: inline-block;
vertical-align: middle; vertical-align: middle;
margin-right: 0.5em; margin-right: 0.5em;
} }