Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local component = require("component")
- local computer = require("computer")
- local event = require("event")
- local keyboard = require("keyboard")
- local tty = require("tty")
- -- Wrap Reactor Components -------------------------------------------------
- if not component.isAvailable("draconic_reactor") then
- print("Reactor not connected. Please connect the computer to the reactor with an Adapter block.")
- os.exit()
- end
- local reactor = component.draconic_reactor
- -- This is 1 by default, but changes based on modpack.
- -- Check "Mod Options > Draconic Evolution > Tweaks > reactorOutputMultiplier"
- -- and change this value to match.
- local reactorOutputMultiplier = 1.0
- ----------------------------------------------------------------------------
- -- Gate helpers -------------------------------------------------------------
- local MAX_GATE_FLOW = 2147000000.0
- local STARTUP_CHARGE_FLOW = 5000000.0
- -- PID only engages within 50C of target. Outside that window the base math
- -- runs free and the bias is reset, giving a clean handoff on entry.
- local PID_TEMP_WINDOW = 150.0
- local PID_FIELD_WINDOW = 2.0
- local function clamp(value, minValue, maxValue)
- if value ~= value then return minValue end
- if value < minValue then return minValue end
- if value > maxValue then return maxValue end
- return value
- end
- local function setGateFlow(gate, value)
- value = tonumber(value) or 0.0
- value = clamp(value, 0.0, MAX_GATE_FLOW)
- value = value + 0.0
- if gate.setFlowOverride then
- return gate.setFlowOverride(value)
- elseif gate.setSignalLowFlow then
- return gate.setSignalLowFlow(math.floor(value + 0.5))
- else
- error("Flux gate does not expose setFlowOverride or setSignalLowFlow.")
- end
- end
- local function getGateFlow(gate)
- if gate.getFlowOverride then
- return gate.getFlowOverride()
- elseif gate.getSignalLowFlow then
- return gate.getSignalLowFlow()
- elseif gate.getFlow then
- return gate.getFlow()
- end
- return 0.0
- end
- local function enableGateOverride(gate)
- if gate.setOverrideEnabled then
- pcall(gate.setOverrideEnabled, true)
- end
- end
- local function safeReactorCall(name)
- if reactor[name] then
- pcall(reactor[name])
- end
- end
- -- DC14-style smart gate lookup.
- local function smartGateLookup()
- local fluxGates = {}
- for address in pairs(component.list("flux_gate")) do
- fluxGates[#fluxGates + 1] = address
- end
- if #fluxGates < 2 then
- print("Not enough flux gates connected; please connect inflow and outflow flux gates with Adapter blocks.")
- os.exit()
- end
- local inputFlux = component.proxy(fluxGates[1])
- local outputFlux = component.proxy(fluxGates[2])
- if not inputFlux or not outputFlux then
- print("Not enough flux gates connected; please connect inflow and outflow flux gates with Adapter blocks.")
- os.exit()
- end
- enableGateOverride(outputFlux)
- enableGateOverride(inputFlux)
- local infoOne = reactor.getReactorInfo()
- local satOne = infoOne.energySaturation or 0.0
- local fieldOne = infoOne.fieldStrength or 0.0
- safeReactorCall("chargeReactor")
- setGateFlow(inputFlux, 1.0)
- os.sleep(0.5)
- local infoTwo = reactor.getReactorInfo()
- local satTwo = infoTwo.energySaturation or 0.0
- local fieldTwo = infoTwo.fieldStrength or 0.0
- setGateFlow(inputFlux, 0.0)
- safeReactorCall("stopReactor")
- if satTwo <= satOne or fieldTwo <= fieldOne then
- local oldAddr = inputFlux.address
- inputFlux = component.proxy(outputFlux.address)
- outputFlux = component.proxy(oldAddr)
- end
- enableGateOverride(outputFlux)
- enableGateOverride(inputFlux)
- return inputFlux, outputFlux
- end
- local input_flux, output_flux = smartGateLookup()
- local keyStatus = "Keys: [S] swap flux gates [X] force close [Up/Down] temp +/-100C [Left/Right] field +/-0.25%"
- local targetTemp = nil
- local targetShield = nil
- local function swapFluxGates()
- local oldGate = input_flux
- input_flux = output_flux
- output_flux = oldGate
- enableGateOverride(input_flux)
- enableGateOverride(output_flux)
- keyStatus = "Flux gates swapped. Keys: [S] swap flux gates [X] force close [Up/Down] temp +/-100C [Left/Right] field +/-0.25%"
- end
- local function adjustTargetTemp(offset)
- targetTemp = clamp((tonumber(targetTemp) or 8000.0) + offset, 2500.0, 15000.0)
- keyStatus = string.format("Target temp now %.0fC. Keys: [S] swap [X] exit [Up/Down] temp +/-100C [Left/Right] field +/-0.25%%", targetTemp)
- end
- local function adjustTargetField(offsetPercent)
- local currentPercent = (tonumber(targetShield) or 0.5) * 100.0
- currentPercent = clamp(currentPercent + offsetPercent, 1.0, 100.0)
- targetShield = currentPercent / 100.0
- keyStatus = string.format("Target field now %.2f%%. Keys: [S] swap [X] exit [Up/Down] temp +/-100C [Left/Right] field +/-0.25%%", currentPercent)
- end
- local function handleKeys(timeout)
- local ev, _, char, code = event.pull(timeout or 0.025)
- if ev == "key_down" then
- if char == string.byte("s") or char == string.byte("S") then
- swapFluxGates()
- elseif char == string.byte("x") or char == string.byte("X") then
- tty.clear()
- print("Force closed.")
- os.exit()
- elseif code == keyboard.keys.up then
- adjustTargetTemp(100.0)
- elseif code == keyboard.keys.down then
- adjustTargetTemp(-100.0)
- elseif code == keyboard.keys.right then
- adjustTargetField(0.25)
- elseif code == keyboard.keys.left then
- adjustTargetField(-0.25)
- end
- end
- end
- -- This script has no GUI start button, so after the DC14 gate probe stops
- -- the reactor, immediately arm a real startup cycle.
- local startupChargeArmed = true
- -- Persistent temp correction in raw RF/t.
- -- Two-way: trim may subtract output when hot, or add output when cool.
- local tempOutputBias = 0.0
- local tempLastError = nil
- -- PID only activates within PID_TEMP_WINDOW of target. Base math handles
- -- everything outside that range and resets bias for a clean handoff.
- local TEMP_P_RF = 0.0
- local TEMP_I_RF_PER_SEC = 50000.0
- local TEMP_BIAS_LEAK = 0.9994
- local TEMP_RELEASE_LEAK = 0.5000
- local TEMP_HOLD_LEAK = 0.9998
- local TEMP_TRIM_DEADBAND = 0.0
- local TRIM_EPSILON_RF = 1.0
- -- Persistent field correction in raw RF/t.
- -- One-way only: field trim may only subtract input. It cannot force field rise.
- local fieldInputBias = 0.0
- local fieldLastError = nil
- -- Extra damped field trim. Still scaled from inputBase, just less twitchy.
- local FIELD_TRIM_DEADBAND = 0.00005
- local FIELD_P_INPUT_FRACTION = 0.95
- local FIELD_I_INPUT_FRACTION_PER_SEC = 0.20
- local FIELD_BIAS_LEAK = 0.9925
- local FIELD_RELEASE_LEAK = 0.9850
- local FIELD_HOLD_LEAK = 0.9920
- local FIELD_MAX_TRIM_FRACTION = 0.65
- ----------------------------------------------------------------------------
- -- Control Variables --------------------------------------------------------
- local tArgs = {...}
- targetTemp = tonumber(tArgs[1]) or 8000.0
- targetShield = tonumber(tArgs[2]) or 0.5
- if targetTemp < 2500.0 then
- targetTemp = 2500.0
- elseif targetTemp > 15000.0 then
- targetTemp = 15000.0
- end
- if targetShield < 0.01 then
- targetShield = 0.01
- elseif targetShield > 1.0 then
- targetShield = 1.0
- end
- ----------------------------------------------------------------------------
- local function resetTempBias()
- tempOutputBias = 0.0
- tempLastError = nil
- end
- local function resetFieldBias()
- fieldInputBias = 0.0
- fieldLastError = nil
- end
- ----------------------------------------------------------------------------
- -- EMA state for display smoothing only. Never used for reactor control.
- local EMA_ALPHA = 0.05
- local emaGrossOutput = nil
- local emaNetOutput = nil
- local emaEfficiency = nil
- local function emaUpdate(current, newValue)
- if current == nil then return newValue end
- return current + EMA_ALPHA * (newValue - current)
- end
- -- Last known gate values for display. Updated after gates are set each tick.
- local displayInputFlow = 0.0
- local displayOutputFlow = 0.0
- local function update()
- local lastTick = computer.uptime()
- while true do
- tty.clear()
- local now = computer.uptime()
- local dt = clamp(now - lastTick, 0.001, 0.25)
- lastTick = now
- local reactorInfo = reactor.getReactorInfo()
- -- One-tick projected field ---------------------------------------------
- -- The reactor info appears one tick behind the flux gate effect.
- -- Control/readout use projected field = raw field + one tick input - one tick drain.
- local rawFieldStrength = reactorInfo.fieldStrength
- local lastInputFlow = getGateFlow(input_flux)
- local oneTickFieldDelta = lastInputFlow - reactorInfo.fieldDrainRate
- local projectedFieldStrength = clamp(
- rawFieldStrength + oneTickFieldDelta,
- 0.0,
- reactorInfo.maxFieldStrength
- )
- local rawFieldPercent = (rawFieldStrength / reactorInfo.maxFieldStrength) * 100.0
- local projectedFieldPercent = (projectedFieldStrength / reactorInfo.maxFieldStrength) * 100.0
- local oneTickFieldDeltaPercent = (oneTickFieldDelta / reactorInfo.maxFieldStrength) * 100.0
- -- Generation stats EMA — display only, never used for control.
- local rawGross = reactorInfo.generationRate
- local rawNet = rawGross - displayInputFlow
- local rawEff = 0.0
- if displayInputFlow > 0.0 then
- rawEff = ((displayOutputFlow - displayInputFlow) / displayInputFlow) * 100.0
- end
- emaGrossOutput = emaUpdate(emaGrossOutput, rawGross)
- emaNetOutput = emaUpdate(emaNetOutput, rawNet)
- emaEfficiency = emaUpdate(emaEfficiency, rawEff)
- -- Field display values (not gate-dependent)
- local RELATIVE_FIELD_SAFETY = 3.0
- local minFieldFraction = (reactorInfo.fieldDrainRate / reactorInfo.maxFieldStrength) * RELATIVE_FIELD_SAFETY
- local relativeField = 0.0
- if (1.0 - minFieldFraction) > 0.0 then
- relativeField = ((rawFieldPercent / 100.0) - minFieldFraction) / (1.0 - minFieldFraction) * 100.0
- end
- relativeField = clamp(relativeField, 0.0, 100.0)
- -- Adjusted = what the DE UI shows (raw + one tick of drain offset)
- local adjustedDisplayField = rawFieldPercent + (reactorInfo.fieldDrainRate / reactorInfo.maxFieldStrength * 100.0)
- local targetSatPercent = 0.0
- -- CALCULATIONS ---------------------------------------
- local targetTemp50 = math.min((targetTemp / 10000.0) * 50.0, 99.0)
- local coreSat = reactorInfo.energySaturation / reactorInfo.maxEnergySaturation
- local convLVL = (reactorInfo.fuelConversion / reactorInfo.maxFuelConversion * 1.3) - 0.3
- local targetTempResist = ((targetTemp50^4) / (100.0 - targetTemp50))
- local targetTempExpo = -(targetTempResist * convLVL) - 1000.0 * convLVL + targetTempResist
- local term1 = 1334.1 - (3.0 * targetTempExpo)
- local term2 = (1200690.0 - (2700.0 * targetTempExpo))^2
- local term3 = ((-1350.0 * targetTempExpo) + (((-4.0 * term1^3 + term2)^(1.0 / 2.0)) / 2.0) + 600345.0)^(1.0 / 3.0)
- local targetNegCSat = -(term1 / (3.0 * term3)) - (term3 / 3.0)
- local targetCoreSat = 1.0 - (targetNegCSat / 99.0)
- local targetSat = targetCoreSat * reactorInfo.maxEnergySaturation
- targetSatPercent = targetCoreSat * 100.0
- local saturationError = reactorInfo.energySaturation - targetSat
- local tempDrainFactor = 0.0
- if reactorInfo.temperature > 8000.0 then
- tempDrainFactor = 1.0 + ((reactorInfo.temperature - 8000.0)^2 * 0.0000025)
- elseif reactorInfo.temperature > 2000.0 then
- tempDrainFactor = 1.0
- elseif reactorInfo.temperature > 1000.0 then
- tempDrainFactor = (reactorInfo.temperature - 1000.0) / 1000.0
- end
- local baseMaxRFt = (reactorInfo.maxEnergySaturation / 1000.0) * reactorOutputMultiplier * 1.5
- local fieldDrain = math.min(tempDrainFactor * math.max(0.01, (1.0 - coreSat)) * (baseMaxRFt / 10.923556), MAX_GATE_FLOW)
- local fieldNegPercent = 1.0 - targetShield
- -- Subtract one tick of drain from target to compensate for DE UI display lag.
- -- DE reads one tick ahead of what the script sees, so it always shows slightly high.
- local adjustedShield = targetShield - (reactorInfo.fieldDrainRate / reactorInfo.maxFieldStrength)
- local fieldStrengthError = (reactorInfo.maxFieldStrength * adjustedShield) - rawFieldStrength
- local availableField = math.max(1.0, reactorInfo.maxFieldStrength - rawFieldStrength)
- local requiredInput = math.min((reactorInfo.maxFieldStrength * reactorInfo.fieldDrainRate) / availableField, availableField)
- -- Print the clean UI now that all values are computed
- local currentSatPercent = (reactorInfo.energySaturation / reactorInfo.maxEnergySaturation) * 100.0
- print("=== Generation Statistics ===")
- print(string.format(" Gross Output: %.0f RF/t", emaGrossOutput or 0.0))
- print(string.format(" Net Output: %.0f RF/t", emaNetOutput or 0.0))
- print(string.format(" Efficiency: %.1f%%", emaEfficiency or 0.0))
- print("")
- print("=== Reactor Stats ===")
- print(string.format(" Target Temp: %.0f C", targetTemp))
- print(string.format(" Temperature: %.1f C", reactorInfo.temperature))
- print(string.format(" Target Sat: %.2f%%", targetSatPercent))
- print(string.format(" Saturation: %.2f%%", currentSatPercent))
- print("")
- print("=== Field Strength ===")
- print(string.format(" Adjusted: %.4f%%", adjustedDisplayField))
- print(string.format(" Tickback: %.4f%%", rawFieldPercent))
- print(string.format(" Relative: %.2f%%", relativeField))
- print("")
- print("=== Gates ===")
- print(string.format(" Input Gate ID: %s", tostring(input_flux.address)))
- print(string.format(" Reactor Input: %.0f RF/t", displayInputFlow))
- print(string.format(" Output Gate ID: %s", tostring(output_flux.address)))
- print(string.format(" Reactor Output: %.0f RF/t", displayOutputFlow))
- print("")
- print(keyStatus)
- print("")
- -------------------------------------------------------
- if reactorInfo.temperature >= 2000.0 and reactorInfo.status == "warming_up" then
- safeReactorCall("activateReactor")
- end
- if reactorInfo.status == "running" then
- startupChargeArmed = false
- end
- if startupChargeArmed and reactorInfo.status ~= "running" then
- resetTempBias()
- resetFieldBias()
- safeReactorCall("chargeReactor")
- setGateFlow(output_flux, 0.0)
- setGateFlow(input_flux, STARTUP_CHARGE_FLOW)
- print("Startup charge armed.")
- print(string.format("Setting output flux gate to %.0f RF/t", 0.0))
- print(string.format("Setting input flux gate to %.0f RF/t", STARTUP_CHARGE_FLOW))
- elseif reactorInfo.status == "running" then
- if reactorInfo.fuelConversion / reactorInfo.maxFuelConversion > 0.85 then
- reactor.stopReactor()
- end
- local outputBase = math.min(saturationError, (reactorInfo.maxEnergySaturation / 40.0))
- -- Temperature trim:
- -- PID only activates within PID_TEMP_WINDOW (50C) of target.
- -- Outside that window resetTempBias() keeps bias clean for handoff.
- -- Two-way: negative error (hot) subtracts output, positive error (cool) adds output.
- local tempError = targetTemp - reactorInfo.temperature
- local tempPidTrim = 0.0
- if math.abs(tempError) <= PID_TEMP_WINDOW then
- -- Accumulate bias in whichever direction error points.
- if tempLastError ~= nil and (tempLastError * tempError < 0.0) then
- -- Error crossed zero, reset bias for clean handoff.
- tempOutputBias = 0.0
- end
- tempOutputBias = (tempOutputBias * TEMP_BIAS_LEAK) + (tempError * TEMP_I_RF_PER_SEC * dt)
- if math.abs(tempOutputBias) < TRIM_EPSILON_RF then
- tempOutputBias = 0.0
- end
- tempPidTrim = (tempError * TEMP_P_RF) + tempOutputBias
- tempLastError = tempError
- else
- resetTempBias()
- end
- local outputNeeded = clamp(outputBase + tempPidTrim, 0.0, MAX_GATE_FLOW)
- setGateFlow(output_flux, outputNeeded)
- local inputBase = math.min(fieldStrengthError + requiredInput, reactorInfo.maxFieldStrength)
- local currentFieldPercent = rawFieldPercent
- local targetFieldPercent = adjustedShield * 100.0
- -- Field trim:
- -- Above target field = negative error = subtract input.
- -- Below target field = positive error = PID is NOT allowed to add input.
- local fieldPercentError = targetFieldPercent - currentFieldPercent
- local fieldPidTrim = 0.0
- local fieldTrimLimit = math.max(1000.0, inputBase * FIELD_MAX_TRIM_FRACTION)
- if math.abs(fieldPercentError) <= PID_FIELD_WINDOW then
- if fieldPercentError < -FIELD_TRIM_DEADBAND then
- -- Field is high. Accumulate negative input trim.
- if fieldLastError ~= nil and fieldLastError > 0.0 then
- fieldInputBias = 0.0
- end
- fieldInputBias = (fieldInputBias * FIELD_BIAS_LEAK) +
- (fieldPercentError * inputBase * FIELD_I_INPUT_FRACTION_PER_SEC * dt)
- fieldInputBias = clamp(fieldInputBias, -fieldTrimLimit, 0.0)
- fieldPidTrim = (fieldPercentError * inputBase * FIELD_P_INPUT_FRACTION) + fieldInputBias
- fieldPidTrim = clamp(fieldPidTrim, -fieldTrimLimit, 0.0)
- elseif fieldPercentError > FIELD_TRIM_DEADBAND then
- -- Field is low. PID cannot add input.
- -- Release negative trim and let base math handle field recovery.
- fieldInputBias = fieldInputBias * FIELD_RELEASE_LEAK
- fieldInputBias = clamp(fieldInputBias, -fieldTrimLimit, 0.0)
- if math.abs(fieldInputBias) < TRIM_EPSILON_RF then
- fieldInputBias = 0.0
- end
- fieldPidTrim = fieldInputBias
- if fieldPidTrim > 0.0 then
- fieldPidTrim = 0.0
- end
- else
- -- Very close to target. Hold trim briefly, but bleed faster than before.
- fieldInputBias = fieldInputBias * FIELD_HOLD_LEAK
- fieldInputBias = clamp(fieldInputBias, -fieldTrimLimit, 0.0)
- if math.abs(fieldInputBias) < TRIM_EPSILON_RF then
- fieldInputBias = 0.0
- end
- fieldPidTrim = fieldInputBias
- if fieldPidTrim > 0.0 then
- fieldPidTrim = 0.0
- end
- end
- fieldLastError = fieldPercentError
- else
- resetFieldBias()
- end
- local inputNeeded = clamp(inputBase + fieldPidTrim, 0.0, reactorInfo.maxFieldStrength)
- setGateFlow(input_flux, inputNeeded)
- displayInputFlow = inputNeeded
- displayOutputFlow = outputNeeded
- elseif reactorInfo.status == "warming_up" then
- resetTempBias()
- resetFieldBias()
- setGateFlow(output_flux, 0.0)
- setGateFlow(input_flux, STARTUP_CHARGE_FLOW)
- displayInputFlow = STARTUP_CHARGE_FLOW
- displayOutputFlow = 0.0
- print("Reactor Charging; flooding reactor")
- elseif reactorInfo.status == "stopping" then
- resetTempBias()
- resetFieldBias()
- setGateFlow(output_flux, 0.0)
- setGateFlow(input_flux, requiredInput)
- displayInputFlow = requiredInput
- displayOutputFlow = 0.0
- print(string.format("Setting input flux gate to %.0f RF/t", getGateFlow(input_flux)))
- else
- resetTempBias()
- resetFieldBias()
- end
- handleKeys(0.025)
- end
- end
- update()
Advertisement