Naddox

MineColonies Research Supplier

Sep 2nd, 2026 (edited)
76
0
Never
2
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 37.97 KB | Gaming | 0 0
  1. -- ============================================================
  2. -- MineColonies Research Supplier v3.2
  3. -- ATM10 / Minecraft 1.21.1
  4. -- CC:Tweaked + Advanced Peripherals + AE2 + MineColonies
  5. -- ============================================================
  6. --
  7. -- PURPOSE
  8. --   1. Finds the ME Bridge whose custom name is "Research".
  9. --   2. Finds the inventory directly touching that ME Bridge.
  10. --   3. Reads MineColonies research through Colony Integrator.
  11. --   4. Finds research which is currently available to start:
  12. --        status == NOT_STARTED
  13. --        all requirements are fulfilled
  14. --        parent research path is already finished
  15. --   5. Totals the item costs for ALL currently-available research.
  16. --   6. Pulls those items from AE2 into the Research inventory.
  17. --   7. If AE2 is short but an item is craftable, requests an
  18. --      AE2 autocraft and stages it on a later pass.
  19. --   8. When research availability changes, items previously staged
  20. --      by this program are pulled back into AE2 and the exact new
  21. --      requirement set is staged.
  22. --
  23. -- IMPORTANT
  24. --   The inventory touching the Research ME Bridge should be used as
  25. --   a dedicated research-material buffer. The program only pulls back
  26. --   quantities that IT previously exported, so unrelated items are
  27. --   left alone.
  28. --
  29. --   The program does NOT start research. MineColonies/Advanced
  30. --   Peripherals exposes research information, but no research-start
  31. --   method. You still click the research manually in the University.
  32. --
  33. -- ============================================================
  34.  
  35.  
  36. -- ============================================================
  37. -- CONFIG
  38. -- ============================================================
  39.  
  40. local RESEARCH_BRIDGE_NAME = "Research"
  41.  
  42. -- nil = automatically probe all six faces of the Research ME Bridge.
  43. -- If automatic detection ever chooses the wrong face, set this to:
  44. -- "north", "south", "east", "west", "up", or "down"
  45. local OUTPUT_SIDE = nil
  46.  
  47. -- How often to completely reconcile the research buffer.
  48. -- This includes reclaiming the program's prior staged quantities and
  49. -- restaging the exact current requirement set.
  50. local POLL_SECONDS = 30
  51.  
  52. -- Prevents one pass from submitting an absurd number of simultaneous
  53. -- new AE2 craft jobs. Existing jobs do not count against this limit.
  54. local MAX_NEW_CRAFTS_PER_PASS = 12
  55.  
  56. -- Probe items used only to discover which ME Bridge face touches an
  57. -- inventory. One item is exported and immediately imported back.
  58. local PROBE_ITEMS = {
  59.     "minecraft:cobblestone",
  60.     "minecraft:stone",
  61.     "minecraft:dirt",
  62.     "minecraft:iron_ingot",
  63.     "minecraft:oak_planks",
  64.     "minecraft:glass"
  65. }
  66.  
  67. local SIDES = {
  68.     "north",
  69.     "south",
  70.     "east",
  71.     "west",
  72.     "up",
  73.     "down"
  74. }
  75.  
  76. local STATE_FILE = "research_supplier_state"
  77.  
  78.  
  79. -- ============================================================
  80. -- GENERIC HELPERS
  81. -- ============================================================
  82.  
  83. local function parseTransferred(result)
  84.     if type(result) == "number" then
  85.         return result
  86.     end
  87.  
  88.     if type(result) == "table" then
  89.         if type(result.count) == "number" then
  90.             return result.count
  91.         end
  92.  
  93.         if type(result.amount) == "number" then
  94.             return result.amount
  95.         end
  96.  
  97.         if type(result.transferred) == "number" then
  98.             return result.transferred
  99.         end
  100.     end
  101.  
  102.     return 0
  103. end
  104.  
  105.  
  106. local function storedCount(result)
  107.     if type(result) ~= "table" then
  108.         return 0
  109.     end
  110.  
  111.     if type(result.count) == "number" then
  112.         return result.count
  113.     end
  114.  
  115.     if type(result.amount) == "number" then
  116.         return result.amount
  117.     end
  118.  
  119.     return 0
  120. end
  121.  
  122.  
  123. local function cleanDisplayName(value)
  124.     if value == nil then
  125.         return "Unknown Item"
  126.     end
  127.  
  128.     local text = tostring(value)
  129.     text = text:gsub("^%[", "")
  130.     text = text:gsub("%]$", "")
  131.  
  132.     return text
  133. end
  134.  
  135.  
  136. -- Makes a serialization-safe independent copy of nested AP tables.
  137. -- This avoids CC:Tweaked's "Cannot serialize table with repeated
  138. -- entries" problem.
  139. local function serializableCopy(value, ancestors)
  140.     local valueType = type(value)
  141.  
  142.     if valueType == "nil"
  143.     or valueType == "boolean"
  144.     or valueType == "number"
  145.     or valueType == "string" then
  146.         return value
  147.     end
  148.  
  149.     if valueType ~= "table" then
  150.         return nil
  151.     end
  152.  
  153.     ancestors = ancestors or {}
  154.  
  155.     if ancestors[value] then
  156.         return nil
  157.     end
  158.  
  159.     ancestors[value] = true
  160.  
  161.     local result = {}
  162.  
  163.     for key, child in pairs(value) do
  164.         local keyType = type(key)
  165.  
  166.         if keyType == "string"
  167.         or keyType == "number"
  168.         or keyType == "boolean" then
  169.             local cleanChild =
  170.                 serializableCopy(
  171.                     child,
  172.                     ancestors
  173.                 )
  174.  
  175.             if cleanChild ~= nil then
  176.                 result[key] = cleanChild
  177.             end
  178.         end
  179.     end
  180.  
  181.     ancestors[value] = nil
  182.  
  183.     return result
  184. end
  185.  
  186.  
  187. local function snapshotItem(item)
  188.     if type(item) ~= "table" then
  189.         return nil
  190.     end
  191.  
  192.     local result = {
  193.         name = item.name,
  194.         fingerprint = item.fingerprint
  195.     }
  196.  
  197.     if type(item.components) == "table"
  198.     and next(item.components) then
  199.         result.components =
  200.             serializableCopy(
  201.                 item.components
  202.             )
  203.     end
  204.  
  205.     -- Some AP/MineColonies versions expose legacy NBT rather than
  206.     -- components. Preserve it if present.
  207.     if item.nbt ~= nil then
  208.         result.nbt =
  209.             serializableCopy(
  210.                 item.nbt
  211.             )
  212.     end
  213.  
  214.     return result
  215. end
  216.  
  217.  
  218. local function itemKey(item)
  219.     if type(item) ~= "table"
  220.     or not item.name then
  221.         return nil
  222.     end
  223.  
  224.     -- Research costs are normally ordinary items. Prefer a stable
  225.     -- name/components/NBT identity rather than a MineColonies
  226.     -- fingerprint so AE2 autocrafting can use it.
  227.     local extra = ""
  228.  
  229.     if type(item.components) == "table"
  230.     and next(item.components) then
  231.         extra =
  232.             ":components="
  233.             .. textutils.serialize(
  234.                 serializableCopy(
  235.                     item.components
  236.                 )
  237.             )
  238.     elseif item.nbt ~= nil then
  239.         extra =
  240.             ":nbt="
  241.             .. textutils.serialize(
  242.                 serializableCopy(
  243.                     item.nbt
  244.                 )
  245.             )
  246.     end
  247.  
  248.     return tostring(item.name) .. extra
  249. end
  250.  
  251.  
  252. local function makeStorageFilter(item, count)
  253.     local filter = {}
  254.  
  255.     -- Exact fingerprint is useful when AP provides one for a stored
  256.     -- stack. Research costs usually do not, so name/components is the
  257.     -- normal route.
  258.     if item.fingerprint then
  259.         filter.fingerprint = item.fingerprint
  260.     else
  261.         filter.name = item.name
  262.  
  263.         if type(item.components) == "table"
  264.         and next(item.components) then
  265.             filter.components = item.components
  266.         elseif item.nbt ~= nil then
  267.             filter.nbt = item.nbt
  268.         end
  269.     end
  270.  
  271.     if count then
  272.         filter.count = count
  273.     end
  274.  
  275.     return filter
  276. end
  277.  
  278.  
  279. local function makeCraftFilter(item, count)
  280.     -- IMPORTANT:
  281.     -- In this ATM10/AP setup, craftability/crafting should use the
  282.     -- registry name/components rather than a MineColonies fingerprint.
  283.     local filter = {
  284.         name = item.name
  285.     }
  286.  
  287.     if type(item.components) == "table"
  288.     and next(item.components) then
  289.         filter.components = item.components
  290.     elseif item.nbt ~= nil then
  291.         filter.nbt = item.nbt
  292.     end
  293.  
  294.     if count then
  295.         filter.count = count
  296.     end
  297.  
  298.     return filter
  299. end
  300.  
  301.  
  302. -- ============================================================
  303. -- PERSISTENT STATE
  304. -- ============================================================
  305.  
  306. local STATE = {
  307.     outputSides = {},
  308.  
  309.     -- [itemKey] = {
  310.     --     item = serialization-safe item identity,
  311.     --     displayName = string,
  312.     --     count = amount this program most recently staged
  313.     -- }
  314.     staged = {}
  315. }
  316.  
  317.  
  318. local function loadState()
  319.     if not fs.exists(STATE_FILE) then
  320.         return
  321.     end
  322.  
  323.     local handle = fs.open(STATE_FILE, "r")
  324.  
  325.     if not handle then
  326.         return
  327.     end
  328.  
  329.     local raw = handle.readAll()
  330.     handle.close()
  331.  
  332.     local ok, decoded =
  333.         pcall(
  334.             textutils.unserialize,
  335.             raw
  336.         )
  337.  
  338.     if ok and type(decoded) == "table" then
  339.         STATE.outputSides =
  340.             type(decoded.outputSides) == "table"
  341.             and decoded.outputSides
  342.             or (
  343.                 decoded.outputSide
  344.                 and {decoded.outputSide}
  345.                 or {}
  346.             )
  347.  
  348.         STATE.staged =
  349.             type(decoded.staged) == "table"
  350.             and decoded.staged
  351.             or {}
  352.     else
  353.         print("[STATE] Old/invalid state ignored.")
  354.     end
  355. end
  356.  
  357.  
  358. local function saveState()
  359.     local clean =
  360.         serializableCopy(
  361.             STATE
  362.         )
  363.  
  364.     local ok, encoded =
  365.         pcall(
  366.             textutils.serialize,
  367.             clean,
  368.             {compact = true}
  369.         )
  370.  
  371.     if not ok then
  372.         print(
  373.             "[STATE ERROR] "
  374.             .. tostring(encoded)
  375.         )
  376.         return
  377.     end
  378.  
  379.     local temp = STATE_FILE .. ".tmp"
  380.     local handle = fs.open(temp, "w")
  381.  
  382.     if not handle then
  383.         print("[STATE ERROR] Could not open temp state file.")
  384.         return
  385.     end
  386.  
  387.     handle.write(encoded)
  388.     handle.close()
  389.  
  390.     if fs.exists(STATE_FILE) then
  391.         fs.delete(STATE_FILE)
  392.     end
  393.  
  394.     fs.move(temp, STATE_FILE)
  395. end
  396.  
  397.  
  398. loadState()
  399.  
  400.  
  401. -- ============================================================
  402. -- FIND COLONY INTEGRATOR
  403. -- ============================================================
  404.  
  405. local colony = peripheral.find("colony_integrator")
  406.  
  407. if not colony then
  408.     error("No colony_integrator found on the wired network.")
  409. end
  410.  
  411.  
  412. -- ============================================================
  413. -- FIND CUSTOM-NAMED RESEARCH ME BRIDGE
  414. -- ============================================================
  415.  
  416. local function findResearchBridge()
  417.     local target =
  418.         string.lower(
  419.             RESEARCH_BRIDGE_NAME
  420.         )
  421.  
  422.     for _, name in ipairs(peripheral.getNames()) do
  423.         if peripheral.getType(name) == "me_bridge" then
  424.             local bridge = peripheral.wrap(name)
  425.  
  426.             local ok, customName =
  427.                 pcall(
  428.                     bridge.getName
  429.                 )
  430.  
  431.             if ok
  432.             and type(customName) == "string"
  433.             and string.lower(customName) == target then
  434.                 return bridge, name, customName
  435.             end
  436.         end
  437.     end
  438.  
  439.     return nil
  440. end
  441.  
  442.  
  443. local me,
  444.       mePeripheralName,
  445.       meCustomName =
  446.     findResearchBridge()
  447.  
  448. if not me then
  449.     error(
  450.         'Could not find an ME Bridge custom-named "'
  451.         .. RESEARCH_BRIDGE_NAME
  452.         .. '".'
  453.     )
  454. end
  455.  
  456.  
  457. -- ============================================================
  458. -- OUTPUT-INVENTORY FACE DETECTION (ALL VALID FACES)
  459. -- ============================================================
  460.  
  461. local function getProbeItem()
  462.     for _, itemName in ipairs(PROBE_ITEMS) do
  463.         local ok, result =
  464.             pcall(
  465.                 me.getItem,
  466.                 {name = itemName}
  467.             )
  468.  
  469.         if ok
  470.         and storedCount(result) > 0 then
  471.             return itemName
  472.         end
  473.     end
  474.  
  475.     return nil
  476. end
  477.  
  478.  
  479. local function probeSide(side, probeItem)
  480.     local ok, result =
  481.         pcall(
  482.             me.exportItem,
  483.             {
  484.                 name = probeItem,
  485.                 count = 1
  486.             },
  487.             side
  488.         )
  489.  
  490.     if not ok then
  491.         return false
  492.     end
  493.  
  494.     local moved =
  495.         parseTransferred(result)
  496.  
  497.     if moved <= 0 then
  498.         return false
  499.     end
  500.  
  501.     -- Immediately put the probe back into AE2.
  502.     local importOK, importResult =
  503.         pcall(
  504.             me.importItem,
  505.             {
  506.                 name = probeItem,
  507.                 count = moved
  508.             },
  509.             side
  510.         )
  511.  
  512.     local restored =
  513.         importOK
  514.         and parseTransferred(importResult)
  515.         or 0
  516.  
  517.     if restored < moved then
  518.         print(
  519.             "[PROBE WARNING] "
  520.             .. tostring(moved - restored)
  521.             .. " probe item(s) remained on "
  522.             .. side
  523.             .. "."
  524.         )
  525.     end
  526.  
  527.     return true
  528. end
  529.  
  530.  
  531. local function detectOutputSides()
  532.     if OUTPUT_SIDE then
  533.         return {OUTPUT_SIDE}
  534.     end
  535.  
  536.     local probeItem =
  537.         getProbeItem()
  538.  
  539.     if not probeItem then
  540.         error(
  541.             "Could not auto-detect the Research inventories because "
  542.             .. "none of the configured probe items exist in AE2. "
  543.             .. "Either put cobblestone/stone/dirt in AE2 or set "
  544.             .. "OUTPUT_SIDE manually near the top of the script."
  545.         )
  546.     end
  547.  
  548.     local found = {}
  549.  
  550.     for _, side in ipairs(SIDES) do
  551.         if probeSide(side, probeItem) then
  552.             table.insert(found, side)
  553.         end
  554.     end
  555.  
  556.     if #found == 0 then
  557.         error(
  558.             "No inventory detected directly beside the Research ME Bridge."
  559.         )
  560.     end
  561.  
  562.     STATE.outputSides = found
  563.     saveState()
  564.  
  565.     return found
  566. end
  567.  
  568.  
  569. local outputSides =
  570.     detectOutputSides()
  571.  
  572.  
  573.  
  574. -- ============================================================
  575. -- RESEARCH TREE
  576. -- ============================================================
  577.  
  578. local function normalizedStatus(status)
  579.     local text =
  580.         string.upper(
  581.             tostring(status or "")
  582.         )
  583.  
  584.     text =
  585.         text:gsub(
  586.             "%s+",
  587.             "_"
  588.         )
  589.  
  590.     return text
  591. end
  592.  
  593.  
  594. local function requirementsFulfilled(research)
  595.     for _, requirement
  596.     in pairs(research.requirements or {}) do
  597.  
  598.         if requirement.fulfilled ~= true then
  599.             return false
  600.         end
  601.     end
  602.  
  603.     return true
  604. end
  605.  
  606.  
  607. local function collectAvailableResearch()
  608.     local tree =
  609.         colony.getResearch()
  610.         or {}
  611.  
  612.     local available = {}
  613.     local unknownStatuses = {}
  614.  
  615.  
  616.     local function walk(branch, list, depth)
  617.         if type(list) ~= "table" then
  618.             return
  619.         end
  620.  
  621.         for _, research in pairs(list) do
  622.             if type(research) == "table" then
  623.                 local status =
  624.                     normalizedStatus(
  625.                         research.status
  626.                     )
  627.  
  628.                 if status == "FINISHED" then
  629.  
  630.                     -- Only walk further down a research chain once
  631.                     -- the parent research is actually complete.
  632.                     walk(
  633.                         branch,
  634.                         research.children,
  635.                         depth + 1
  636.                     )
  637.  
  638.                 elseif status == "NOT_STARTED"
  639.                 or status == "NOTSTARTED" then
  640.  
  641.                     if requirementsFulfilled(research) then
  642.                         table.insert(
  643.                             available,
  644.                             {
  645.                                 branch = branch,
  646.                                 depth = depth,
  647.                                 research = research
  648.                             }
  649.                         )
  650.                     end
  651.  
  652.                 elseif status == "IN_PROGRESS"
  653.                 or status == "INPROGRESS" then
  654.  
  655.                     -- Do not stage its cost. MineColonies has already
  656.                     -- accepted/consumed what was required to start it.
  657.  
  658.                 else
  659.                     unknownStatuses[status] = true
  660.                 end
  661.             end
  662.         end
  663.     end
  664.  
  665.  
  666.     for branch, list in pairs(tree) do
  667.         walk(
  668.             tostring(branch),
  669.             list,
  670.             0
  671.         )
  672.     end
  673.  
  674.  
  675.     return available,
  676.            unknownStatuses
  677. end
  678.  
  679.  
  680. -- ============================================================
  681. -- TOTAL CURRENT RESEARCH COSTS
  682. -- ============================================================
  683.  
  684. -- Build ONE AE2 snapshot per polling pass.
  685. --
  686. -- The previous version queried me.getItem()/isCraftable() once for
  687. -- every entry in every MineColonies validItems list. Some research
  688. -- costs have very large validItems lists, so that could make the
  689. -- program appear frozen immediately after "Starting...".
  690. --
  691. -- On the 1.21.1 AP storage API, getItems({}) and
  692. -- getCraftableItems({}) let us fetch the whole picture once.
  693. local function buildAESnapshot()
  694.     local snapshot = {
  695.         storedByName = {},
  696.         craftableByName = {},
  697.         hasStoredSnapshot = false,
  698.         hasCraftableSnapshot = false
  699.     }
  700.  
  701.     -- Current 1.21.1 / AP storage-system API.
  702.     if type(me.getItems) == "function" then
  703.         local ok, items =
  704.             pcall(
  705.                 me.getItems,
  706.                 {}
  707.             )
  708.  
  709.         if ok
  710.         and type(items) == "table" then
  711.             snapshot.hasStoredSnapshot = true
  712.  
  713.             for _, item in pairs(items) do
  714.                 if type(item) == "table"
  715.                 and item.name then
  716.                     local count =
  717.                         storedCount(item)
  718.  
  719.                     snapshot.storedByName[item.name] =
  720.                         (snapshot.storedByName[item.name] or 0)
  721.                         + count
  722.  
  723.                     if item.isCraftable == true then
  724.                         snapshot.craftableByName[item.name] = true
  725.                     end
  726.                 end
  727.             end
  728.         end
  729.     end
  730.  
  731.     if type(me.getCraftableItems) == "function" then
  732.         local ok, items =
  733.             pcall(
  734.                 me.getCraftableItems,
  735.                 {}
  736.             )
  737.  
  738.         if ok
  739.         and type(items) == "table" then
  740.             snapshot.hasCraftableSnapshot = true
  741.  
  742.             for _, item in pairs(items) do
  743.                 if type(item) == "table"
  744.                 and item.name then
  745.                     snapshot.craftableByName[item.name] = true
  746.                 end
  747.             end
  748.         end
  749.     end
  750.  
  751.     -- Compatibility with older bridge method names, just in case.
  752.     if not snapshot.hasStoredSnapshot
  753.     and type(me.listItems) == "function" then
  754.         local ok, items =
  755.             pcall(
  756.                 me.listItems
  757.             )
  758.  
  759.         if ok
  760.         and type(items) == "table" then
  761.             snapshot.hasStoredSnapshot = true
  762.  
  763.             for _, item in pairs(items) do
  764.                 if type(item) == "table"
  765.                 and item.name then
  766.                     snapshot.storedByName[item.name] =
  767.                         (snapshot.storedByName[item.name] or 0)
  768.                         + storedCount(item)
  769.  
  770.                     if item.isCraftable == true then
  771.                         snapshot.craftableByName[item.name] = true
  772.                     end
  773.                 end
  774.             end
  775.         end
  776.     end
  777.  
  778.     if not snapshot.hasCraftableSnapshot
  779.     and type(me.listCraftableItems) == "function" then
  780.         local ok, items =
  781.             pcall(
  782.                 me.listCraftableItems
  783.             )
  784.  
  785.         if ok
  786.         and type(items) == "table" then
  787.             snapshot.hasCraftableSnapshot = true
  788.  
  789.             for _, item in pairs(items) do
  790.                 if type(item) == "table"
  791.                 and item.name then
  792.                     snapshot.craftableByName[item.name] = true
  793.                 end
  794.             end
  795.         end
  796.     end
  797.  
  798.     return snapshot
  799. end
  800.  
  801.  
  802. local function chooseCostItem(validItems, aeSnapshot)
  803.     if type(validItems) ~= "table" then
  804.         return nil
  805.     end
  806.  
  807.     local candidates = {}
  808.  
  809.     for _, candidate in pairs(validItems) do
  810.         if type(candidate) == "table"
  811.         and candidate.name then
  812.             table.insert(
  813.                 candidates,
  814.                 snapshotItem(candidate)
  815.             )
  816.         end
  817.     end
  818.  
  819.     if #candidates == 0 then
  820.         return nil
  821.     end
  822.  
  823.     -- Prefer the acceptable alternative with the greatest quantity
  824.     -- already in AE2. This is now just local table lookup, not a
  825.     -- peripheral call for every candidate.
  826.     local bestStored = nil
  827.     local bestCount = 0
  828.  
  829.     if aeSnapshot
  830.     and aeSnapshot.hasStoredSnapshot then
  831.         for _, candidate in ipairs(candidates) do
  832.             local count =
  833.                 aeSnapshot.storedByName[candidate.name]
  834.                 or 0
  835.  
  836.             if count > bestCount then
  837.                 bestCount = count
  838.                 bestStored = candidate
  839.             end
  840.         end
  841.     end
  842.  
  843.     if bestStored
  844.     and bestCount > 0 then
  845.         return bestStored
  846.     end
  847.  
  848.     -- If none are currently stored, prefer one AE2 can autocraft.
  849.     if aeSnapshot then
  850.         for _, candidate in ipairs(candidates) do
  851.             if aeSnapshot.craftableByName[candidate.name] then
  852.                 return candidate
  853.             end
  854.         end
  855.     end
  856.  
  857.     -- Last fallback: choose the first MineColonies-valid option.
  858.     -- The normal reconcile stage will still perform the live
  859.     -- getItem()/isCraftable() check for this ONE selected item.
  860.     return candidates[1]
  861. end
  862.  
  863.  
  864.  
  865. local function collectDesiredCosts(available, aeSnapshot)
  866.     local desired = {}
  867.  
  868.  
  869.     local function addChosenItem(item, count, research)
  870.         if not item
  871.         or not item.name then
  872.             return
  873.         end
  874.  
  875.         local key =
  876.             itemKey(item)
  877.  
  878.         count =
  879.             tonumber(count)
  880.             or 1
  881.  
  882.         if not key
  883.         or count <= 0 then
  884.             return
  885.         end
  886.  
  887.         local demand =
  888.             desired[key]
  889.  
  890.         if not demand then
  891.             demand = {
  892.                 item = item,
  893.                 displayName =
  894.                     cleanDisplayName(
  895.                         item.displayName
  896.                         or item.name
  897.                     ),
  898.                 count = 0,
  899.                 researches = {}
  900.             }
  901.  
  902.             desired[key] = demand
  903.         end
  904.  
  905.         demand.count =
  906.             demand.count
  907.             + count
  908.  
  909.         table.insert(
  910.             demand.researches,
  911.             cleanDisplayName(
  912.                 research.name
  913.                 or research.id
  914.                 or "Unknown Research"
  915.             )
  916.         )
  917.     end
  918.  
  919.  
  920.     for _, entry in ipairs(available) do
  921.         local research =
  922.             entry.research
  923.  
  924.         local cost =
  925.             research.cost
  926.  
  927.         if type(cost) == "table" then
  928.  
  929.             -- Live ATM10 / MineColonies structure:
  930.             --
  931.             -- research.cost = {
  932.             --   {
  933.             --     validItems = {
  934.             --       { name=..., fingerprint=..., components=..., ... },
  935.             --       ...
  936.             --     },
  937.             --     count = 16
  938.             --   },
  939.             --   ...
  940.             -- }
  941.             --
  942.             -- validItems are alternatives. We need ONE valid item for
  943.             -- each cost entry, not every item in the list.
  944.             if type(cost.validItems) == "table" then
  945.                 local chosen =
  946.                     chooseCostItem(
  947.                         cost.validItems,
  948.                         aeSnapshot
  949.                     )
  950.  
  951.                 addChosenItem(
  952.                     chosen,
  953.                     cost.count,
  954.                     research
  955.                 )
  956.  
  957.             elseif cost.name then
  958.                 addChosenItem(
  959.                     snapshotItem(cost),
  960.                     cost.count,
  961.                     research
  962.                 )
  963.  
  964.             else
  965.                 for _, costEntry in pairs(cost) do
  966.                     if type(costEntry) == "table" then
  967.  
  968.                         if type(costEntry.validItems) == "table" then
  969.                             local chosen =
  970.                                 chooseCostItem(
  971.                                     costEntry.validItems,
  972.                                     aeSnapshot
  973.                                 )
  974.  
  975.                             addChosenItem(
  976.                                 chosen,
  977.                                 costEntry.count,
  978.                                 research
  979.                             )
  980.  
  981.                         elseif type(costEntry.item) == "table" then
  982.                             addChosenItem(
  983.                                 snapshotItem(costEntry.item),
  984.                                 costEntry.count
  985.                                     or costEntry.item.count,
  986.                                 research
  987.                             )
  988.  
  989.                         elseif costEntry.name then
  990.                             addChosenItem(
  991.                                 snapshotItem(costEntry),
  992.                                 costEntry.count,
  993.                                 research
  994.                             )
  995.                         end
  996.                     end
  997.                 end
  998.             end
  999.         end
  1000.     end
  1001.  
  1002.  
  1003.     return desired
  1004. end
  1005.  
  1006.  
  1007.  
  1008. -- ============================================================
  1009. -- AE2 HELPERS
  1010. -- ============================================================
  1011.  
  1012. local function getStored(item)
  1013.     local ok, result =
  1014.         pcall(
  1015.             me.getItem,
  1016.             makeStorageFilter(item)
  1017.         )
  1018.  
  1019.     if not ok then
  1020.         return 0
  1021.     end
  1022.  
  1023.     return storedCount(result)
  1024. end
  1025.  
  1026.  
  1027. local function isCraftable(item)
  1028.     local ok, result =
  1029.         pcall(
  1030.             me.isCraftable,
  1031.             makeCraftFilter(item)
  1032.         )
  1033.  
  1034.     return ok
  1035.         and result == true
  1036. end
  1037.  
  1038.  
  1039. local function isCrafting(item)
  1040.     local ok, result =
  1041.         pcall(
  1042.             me.isCrafting,
  1043.             makeCraftFilter(item)
  1044.         )
  1045.  
  1046.     return ok
  1047.         and result == true
  1048. end
  1049.  
  1050.  
  1051. local function startCraft(item, count)
  1052.     if count <= 0 then
  1053.         return false, "Nothing to craft"
  1054.     end
  1055.  
  1056.     local ok, result, err =
  1057.         pcall(
  1058.             me.craftItem,
  1059.             makeCraftFilter(
  1060.                 item,
  1061.                 count
  1062.             )
  1063.         )
  1064.  
  1065.     if not ok then
  1066.         return false,
  1067.                tostring(result)
  1068.     end
  1069.  
  1070.     if result == true then
  1071.         return true
  1072.     end
  1073.  
  1074.     return false,
  1075.            tostring(err or result)
  1076. end
  1077.  
  1078.  
  1079. local function importPriorStage(entry)
  1080.     local remaining =
  1081.         tonumber(entry.count)
  1082.         or 0
  1083.  
  1084.     if remaining <= 0 then
  1085.         return true, 0
  1086.     end
  1087.  
  1088.     local totalMoved = 0
  1089.     local allOK = true
  1090.  
  1091.     for _, side in ipairs(outputSides) do
  1092.         if remaining <= 0 then
  1093.             break
  1094.         end
  1095.  
  1096.         local ok, result =
  1097.             pcall(
  1098.                 me.importItem,
  1099.                 makeStorageFilter(
  1100.                     entry.item,
  1101.                     remaining
  1102.                 ),
  1103.                 side
  1104.             )
  1105.  
  1106.         if ok then
  1107.             local moved =
  1108.                 parseTransferred(result)
  1109.  
  1110.             totalMoved =
  1111.                 totalMoved
  1112.                 + moved
  1113.  
  1114.             remaining =
  1115.                 math.max(
  1116.                     0,
  1117.                     remaining - moved
  1118.                 )
  1119.         else
  1120.             allOK = false
  1121.  
  1122.             print(
  1123.                 "[RECALL ERROR]["
  1124.                 .. side
  1125.                 .. "] "
  1126.                 .. tostring(result)
  1127.             )
  1128.         end
  1129.     end
  1130.  
  1131.     -- Whatever was actually present has now been reconciled. If a
  1132.     -- player already took some of the staged material, it simply
  1133.     -- will not be found and therefore will not be pulled back.
  1134.     entry.count = 0
  1135.  
  1136.     return allOK,
  1137.            totalMoved
  1138. end
  1139.  
  1140.  
  1141. local function exportDesired(item, count)
  1142.     local remaining =
  1143.         count
  1144.  
  1145.     local totalMoved = 0
  1146.  
  1147.     for _, side in ipairs(outputSides) do
  1148.         if remaining <= 0 then
  1149.             break
  1150.         end
  1151.  
  1152.         local ok, result =
  1153.             pcall(
  1154.                 me.exportItem,
  1155.                 makeStorageFilter(
  1156.                     item,
  1157.                     remaining
  1158.                 ),
  1159.                 side
  1160.             )
  1161.  
  1162.         if ok then
  1163.             local moved =
  1164.                 parseTransferred(result)
  1165.  
  1166.             totalMoved =
  1167.                 totalMoved
  1168.                 + moved
  1169.  
  1170.             remaining =
  1171.                 math.max(
  1172.                     0,
  1173.                     remaining - moved
  1174.                 )
  1175.         else
  1176.             print(
  1177.                 "[EXPORT ERROR]["
  1178.                 .. side
  1179.                 .. "] "
  1180.                 .. tostring(result)
  1181.             )
  1182.         end
  1183.     end
  1184.  
  1185.     return totalMoved
  1186. end
  1187.  
  1188.  
  1189.  
  1190. -- ============================================================
  1191. -- RECONCILE RESEARCH BUFFER
  1192. -- ============================================================
  1193.  
  1194. local lastActions = {}
  1195.  
  1196.  
  1197. local function addAction(text)
  1198.     table.insert(
  1199.         lastActions,
  1200.         text
  1201.     )
  1202.  
  1203.     if #lastActions > 12 then
  1204.         table.remove(
  1205.             lastActions,
  1206.             1
  1207.         )
  1208.     end
  1209. end
  1210.  
  1211.  
  1212. local function reconcile(desired)
  1213.     lastActions = {}
  1214.  
  1215.     -- --------------------------------------------------------
  1216.     -- 1. Pull back exactly what this script believes it staged
  1217.     --    last pass.
  1218.     --
  1219.     --    This serves three purposes:
  1220.     --      * cleans materials for research no longer available
  1221.     --      * detects items the player already removed
  1222.     --      * lets us restage exact current totals without duplicates
  1223.     -- --------------------------------------------------------
  1224.  
  1225.     for key, entry in pairs(STATE.staged) do
  1226.         local ok, moved =
  1227.             importPriorStage(entry)
  1228.  
  1229.         if ok then
  1230.             if moved > 0 then
  1231.                 addAction(
  1232.                     "RECALL "
  1233.                     .. entry.displayName
  1234.                     .. " x"
  1235.                     .. tostring(moved)
  1236.                 )
  1237.             end
  1238.  
  1239.             if not desired[key] then
  1240.                 STATE.staged[key] = nil
  1241.             end
  1242.         else
  1243.             addAction(
  1244.                 "RECALL ERROR "
  1245.                 .. entry.displayName
  1246.             )
  1247.         end
  1248.     end
  1249.  
  1250.  
  1251.     -- --------------------------------------------------------
  1252.     -- 2. Stage what exists now. Ask AE2 to craft shortages.
  1253.     -- --------------------------------------------------------
  1254.  
  1255.     local craftStarts = 0
  1256.  
  1257.     local sorted = {}
  1258.  
  1259.     for key, demand in pairs(desired) do
  1260.         demand.key = key
  1261.         table.insert(sorted, demand)
  1262.     end
  1263.  
  1264.     table.sort(
  1265.         sorted,
  1266.         function(a, b)
  1267.             return string.lower(a.displayName)
  1268.                 < string.lower(b.displayName)
  1269.         end
  1270.     )
  1271.  
  1272.  
  1273.     for _, demand in ipairs(sorted) do
  1274.         local wanted =
  1275.             demand.count
  1276.  
  1277.         local stored =
  1278.             getStored(
  1279.                 demand.item
  1280.             )
  1281.  
  1282.         local attempt =
  1283.             math.min(
  1284.                 wanted,
  1285.                 stored
  1286.             )
  1287.  
  1288.         local moved =
  1289.             exportDesired(
  1290.                 demand.item,
  1291.                 attempt
  1292.             )
  1293.  
  1294.         STATE.staged[demand.key] = {
  1295.             item =
  1296.                 snapshotItem(
  1297.                     demand.item
  1298.                 ),
  1299.             displayName =
  1300.                 demand.displayName,
  1301.             count =
  1302.                 moved
  1303.         }
  1304.  
  1305.  
  1306.         if moved > 0 then
  1307.             addAction(
  1308.                 "STAGE "
  1309.                 .. demand.displayName
  1310.                 .. " x"
  1311.                 .. tostring(moved)
  1312.                 .. "/"
  1313.                 .. tostring(wanted)
  1314.             )
  1315.         end
  1316.  
  1317.  
  1318.         local missing =
  1319.             math.max(
  1320.                 0,
  1321.                 wanted - moved
  1322.             )
  1323.  
  1324.  
  1325.         if missing > 0 then
  1326.             if isCraftable(demand.item) then
  1327.  
  1328.                 if isCrafting(demand.item) then
  1329.                     addAction(
  1330.                         "CRAFTING "
  1331.                         .. demand.displayName
  1332.                         .. " x"
  1333.                         .. tostring(missing)
  1334.                     )
  1335.  
  1336.                 elseif craftStarts
  1337.                     < MAX_NEW_CRAFTS_PER_PASS then
  1338.  
  1339.                     local started,
  1340.                           err =
  1341.                         startCraft(
  1342.                             demand.item,
  1343.                             missing
  1344.                         )
  1345.  
  1346.                     if started then
  1347.                         craftStarts =
  1348.                             craftStarts + 1
  1349.  
  1350.                         addAction(
  1351.                             "CRAFT "
  1352.                             .. demand.displayName
  1353.                             .. " x"
  1354.                             .. tostring(missing)
  1355.                         )
  1356.                     else
  1357.                         addAction(
  1358.                             "CRAFT FAIL "
  1359.                             .. demand.displayName
  1360.                             .. " x"
  1361.                             .. tostring(missing)
  1362.                         )
  1363.  
  1364.                         if err then
  1365.                             print(
  1366.                                 "[CRAFT FAIL] "
  1367.                                 .. demand.displayName
  1368.                                 .. ": "
  1369.                                 .. tostring(err)
  1370.                             )
  1371.                         end
  1372.                     end
  1373.  
  1374.                 else
  1375.                     addAction(
  1376.                         "CRAFT QUEUED NEXT PASS "
  1377.                         .. demand.displayName
  1378.                         .. " x"
  1379.                         .. tostring(missing)
  1380.                     )
  1381.                 end
  1382.  
  1383.             else
  1384.                 addAction(
  1385.                     "MISSING "
  1386.                     .. demand.displayName
  1387.                     .. " x"
  1388.                     .. tostring(missing)
  1389.                 )
  1390.             end
  1391.         end
  1392.     end
  1393.  
  1394.  
  1395.     saveState()
  1396. end
  1397.  
  1398.  
  1399. -- ============================================================
  1400. -- TERMINAL DASHBOARD
  1401. -- ============================================================
  1402.  
  1403. local function drawDashboard(
  1404.     available,
  1405.     desired,
  1406.     unknownStatuses
  1407. )
  1408.     term.clear()
  1409.     term.setCursorPos(1, 1)
  1410.  
  1411.     local colonyName =
  1412.         colony.getColonyName()
  1413.         or "Unknown Colony"
  1414.  
  1415.     print("========================================")
  1416.     print(" MINECOLONIES RESEARCH SUPPLIER v3.2")
  1417.     print("========================================")
  1418.     print("Colony: " .. tostring(colonyName))
  1419.     print("ME Bridge: " .. tostring(meCustomName))
  1420.     print("Output sides: " .. table.concat(outputSides, ", "))
  1421.     print("Poll: " .. tostring(POLL_SECONDS) .. "s")
  1422.     print("")
  1423.  
  1424.     print(
  1425.         "Available research: "
  1426.         .. tostring(#available)
  1427.     )
  1428.  
  1429.     for _, entry in ipairs(available) do
  1430.         local name =
  1431.             cleanDisplayName(
  1432.                 entry.research.name
  1433.                 or entry.research.id
  1434.             )
  1435.  
  1436.         print("  + " .. name)
  1437.     end
  1438.  
  1439.     print("")
  1440.  
  1441.     local itemKinds = 0
  1442.     local totalItems = 0
  1443.  
  1444.     for _, demand in pairs(desired) do
  1445.         itemKinds = itemKinds + 1
  1446.         totalItems =
  1447.             totalItems
  1448.             + demand.count
  1449.     end
  1450.  
  1451.     print(
  1452.         "Required item types: "
  1453.         .. tostring(itemKinds)
  1454.     )
  1455.  
  1456.     print(
  1457.         "Total research items: "
  1458.         .. tostring(totalItems)
  1459.     )
  1460.  
  1461.     print("")
  1462.     print("Last actions:")
  1463.  
  1464.     if #lastActions == 0 then
  1465.         print("  No item movement needed.")
  1466.     else
  1467.         for _, action in ipairs(lastActions) do
  1468.             print("  " .. action)
  1469.         end
  1470.     end
  1471.  
  1472.  
  1473.     local unknown = {}
  1474.  
  1475.     for status in pairs(unknownStatuses or {}) do
  1476.         if status ~= "" then
  1477.             table.insert(
  1478.                 unknown,
  1479.                 status
  1480.             )
  1481.         end
  1482.     end
  1483.  
  1484.     if #unknown > 0 then
  1485.         table.sort(unknown)
  1486.  
  1487.         print("")
  1488.         print(
  1489.             "Unknown research status value(s): "
  1490.             .. table.concat(unknown, ", ")
  1491.         )
  1492.     end
  1493.  
  1494.     print("")
  1495.     print("Ctrl+T to stop.")
  1496. end
  1497.  
  1498.  
  1499. -- ============================================================
  1500. -- STARTUP
  1501. -- ============================================================
  1502.  
  1503. print("MineColonies Research Supplier v3.2")
  1504. print("Research bridge: " .. mePeripheralName)
  1505. print("Custom name: " .. meCustomName)
  1506. print("Output sides: " .. table.concat(outputSides, ", "))
  1507. print("Starting...")
  1508. sleep(1)
  1509.  
  1510.  
  1511. -- ============================================================
  1512. -- MAIN LOOP
  1513. -- ============================================================
  1514.  
  1515. while true do
  1516.     local ok, err =
  1517.         pcall(
  1518.             function()
  1519.                 term.clear()
  1520.                 term.setCursorPos(1, 1)
  1521.                 print("Research Supplier v3.2")
  1522.                 print("")
  1523.                 print("Reading MineColonies research...")
  1524.  
  1525.                 local available,
  1526.                       unknownStatuses =
  1527.                     collectAvailableResearch()
  1528.  
  1529.                 print(
  1530.                     "Found "
  1531.                     .. tostring(#available)
  1532.                     .. " available research entries."
  1533.                 )
  1534.                 print("Reading AE2 inventory/craftable snapshot...")
  1535.  
  1536.                 local aeSnapshot =
  1537.                     buildAESnapshot()
  1538.  
  1539.                 print("Resolving research costs...")
  1540.  
  1541.                 local desired =
  1542.                     collectDesiredCosts(
  1543.                         available,
  1544.                         aeSnapshot
  1545.                     )
  1546.  
  1547.                 print("Staging/crafting materials...")
  1548.  
  1549.                 reconcile(desired)
  1550.  
  1551.                 drawDashboard(
  1552.                     available,
  1553.                     desired,
  1554.                     unknownStatuses
  1555.                 )
  1556.             end
  1557.         )
  1558.  
  1559.     if not ok then
  1560.         term.clear()
  1561.         term.setCursorPos(1, 1)
  1562.  
  1563.         print("RESEARCH SUPPLIER ERROR")
  1564.         print("")
  1565.         print(tostring(err))
  1566.         print("")
  1567.         print(
  1568.             "Retrying in "
  1569.             .. tostring(POLL_SECONDS)
  1570.             .. " seconds..."
  1571.         )
  1572.     end
  1573.  
  1574.     sleep(POLL_SECONDS)
  1575. end
  1576.  
Advertisement
Comments
  • User was banned
  • User was banned
Add Comment
Please, Sign In to add comment