CircuitModelConfig.java

/*
 * Analogue filter models ported from libresidfp.
 * Copyright 2004,2010 Dag Lem
 * Copyright 2007-2010 Antti Lankila
 * Copyright 2011-2026 Leandro Nini
 * SPDX-License-Identifier: GPL-2.0-or-later
 */
package builder.resid.residfp.circuit;

/** Shared immutable tables; calibration and capacitor states belong to each SID. */
final class CircuitModelConfig {
    private static final double[][] OPAMP_6581 = {
  {  0.81, 10.31 },  // Approximate start of actual range
  {  2.40, 10.31 },
  {  2.60, 10.30 },
  {  2.70, 10.29 },
  {  2.80, 10.26 },
  {  2.90, 10.17 },
  {  3.00, 10.04 },
  {  3.10,  9.83 },
  {  3.20,  9.58 },
  {  3.30,  9.32 },
  {  3.50,  8.69 },
  {  3.70,  8.00 },
  {  4.00,  6.89 },
  {  4.40,  5.21 },
  {  4.54,  4.54 },  // Working point (vi = vo)
  {  4.60,  4.19 },
  {  4.80,  3.00 },
  {  4.90,  2.30 },  // Change of curvature
  {  4.95,  2.03 },
  {  5.00,  1.88 },
  {  5.05,  1.77 },
  {  5.10,  1.69 },
  {  5.20,  1.58 },
  {  5.40,  1.44 },
  {  5.60,  1.33 },
  {  5.80,  1.26 },
  {  6.00,  1.21 },
  {  6.40,  1.12 },
  {  7.00,  1.02 },
  {  7.50,  0.97 },
  {  8.50,  0.89 },
  { 10.00,  0.81 },
  { 10.31,  0.81 },  // Approximate end of actual range
};
    private static final double[][] OPAMP_8580 = {
            {1.30, 8.91}, {4.76, 8.91}, {4.77, 8.90}, {4.78, 8.88},
            {4.785, 8.86}, {4.79, 8.80}, {4.795, 8.60}, {4.80, 8.25},
            {4.805, 7.50}, {4.81, 6.10}, {4.815, 4.05}, {4.82, 2.27},
            {4.825, 1.65}, {4.83, 1.55}, {4.84, 1.47}, {4.85, 1.43},
            {4.87, 1.37}, {4.90, 1.34}, {5.00, 1.30}, {5.10, 1.30}, {8.91, 1.30}
    };
    private static final double[] FEEDBACK = {
        1.4, 1.4 * 15.3 / (1.4 + 15.3), 1.4 * 7.3 / (1.4 + 7.3), 1.4 * 4.7 / (1.4 + 4.7)
    };
    private static final double[] INPUT = {1, 1.4, 2, 2.8};
    private static final class OldHolder { static final CircuitModelConfig INSTANCE = new CircuitModelConfig(true); }
    private static final class NewHolder { static final CircuitModelConfig INSTANCE = new CircuitModelConfig(false); }
    static CircuitModelConfig get(boolean mos6581) { return mos6581 ? OldHolder.INSTANCE : NewHolder.INSTANCE; }

    final boolean mos6581;
    final double vmin, vmax, voltageRange, n16, vddt;
    final int nvddt, nvt, nvmin;
    final char[] opampReverse = new char[65536];
    final char[][] summer = new char[5][], mixer = new char[8][];
    final char[][] resonance = new char[16][], volume = new char[16][];
    final char[] vcrGate;
    final double[] vcrCurrent, cutoffDac, voiceDC;
    private final double[][] points;

    private CircuitModelConfig(boolean old) {
        mos6581 = old;
        points = old ? OPAMP_6581 : OPAMP_8580;
        vmin = points[0][0];
        vddt = (old ? 12 * 1.015 : 9 * 1.01) - (old ? 1.31 : 0.8);
        vmax = Math.max(vddt, points[0][1]);
        voltageRange = vmax - vmin;
        n16 = 65535 / voltageRange;
        nvddt = normalize(vddt);
        nvt = normalize(old ? 1.31 : 0.8);
        nvmin = (int) (n16 * vmin);
        double[][] reversePoints = new double[points.length][2];
        for (int i = 0; i < points.length; i++) {
            reversePoints[i][0] = n16 * (points[i][0] - points[i][1]) / 2 + 32768;
            reversePoints[i][1] = n16 * (points[i][0] - vmin);
        }
        CircuitSpline reverse = new CircuitSpline(reversePoints);
        for (int i = 0; i < 65536; i++) opampReverse[i] = (char) Math.max(0, reverse.value(i));
        OpAmp opamp = new OpAmp();
        for (int i = 0; i < summer.length; i++) summer[i] = table(opamp, i + 2, i + 2);
        for (int i = 0; i < mixer.length; i++) mixer[i] = table(opamp, i, i * (old ? 8.0 / (6 * 1.07) : 8.0 / 5));
        for (int i = 0; i < 16; i++) {
            resonance[i] = table(opamp, 1, resonanceRatio(i));
            volume[i] = table(opamp, 1, i / (old ? 12.0 : 16.0));
        }
        voiceDC = new double[256];
        double[] envDac = old ? dac(8) : null;
        for (int i = 0; i < 256; i++) voiceDC[i] = old ? 5 * 1.015 + 0.2143 * envDac[i] : 4.75 * 1.01;
        cutoffDac = old ? dac(11) : null;
        vcrGate = old ? new char[65536] : null;
        vcrCurrent = old ? new double[65536] : null;
        if (old) {
            double ut = 1.380649e-23 * (27 + 273.15) / 1.602176634e-19;
            double is = 2 * ut * ut * 9;
            double nIs = 32767 / voltageRange * 1e-6 / 470e-12 * is;
            for (int i = 0; i < 65536; i++) {
                vcrGate[i] = (char) (n16 * (vddt - vmin) - Math.sqrt((double) i * 65536));
                double log = Math.log1p(Math.exp((i - 32768) / (n16 * 2 * ut)));
                vcrCurrent[i] = nIs * log * log;
            }
        }
    }

    int normalize(double voltage) { return (int) (n16 * (voltage - vmin)) & 65535; }
    int voice(float value, int envelope) { return normalize(value * (mos6581 ? 1.5 : 0.24) + voiceDC[envelope]); }
    double resonanceRatio(int value) { return mos6581 ? (15 - value) / 8.0 : FEEDBACK[value & 3] / INPUT[value >> 2]; }
    char[][] resonanceTables(double factor) {
        if (factor == 1) return resonance;
        char[][] tables = new char[16][];
        OpAmp opamp = new OpAmp();
        for (int i = 0; i < 16; i++) {
            double ratio = resonanceRatio(i);
            // Scale the progression while retaining the measured zero-resonance endpoint.
            double adjusted = mos6581 ? Math.max(0, resonanceRatio(0) - factor * (resonanceRatio(0) - ratio))
                    : resonanceRatio(0) * Math.pow(ratio / resonanceRatio(0), factor);
            tables[i] = table(opamp, 1, adjusted);
        }
        return tables;
    }

    private char[] table(OpAmp opamp, int inputs, double ratio) {
        int divisor = Math.max(inputs, 1);
        char[] result = new char[inputs == 0 ? 1 : inputs << 16];
        opamp.x = vmin;
        for (int i = 0; i < result.length; i++) result[i] = (char) normalize(opamp.solve(ratio, vmin + i / n16 / divisor));
        return result;
    }

    /** The unterminated 6581 R-2R ladder, including upstream's off-state leakage. */
    static double[] dac(int bits) {
        double[] weights = new double[bits];
        double sum = 0;
        for (int selected = 0; selected < bits; selected++) {
            double voltage = 1, resistance = 1e6;
            int bit;
            for (bit = 0; bit < selected; bit++) resistance = resistance == 1e6 ? 3.2 : 1 + 2.2 * resistance / (2.2 + resistance);
            if (resistance == 1e6) resistance = 2.2;
            else { resistance = 2.2 * resistance / (2.2 + resistance); voltage *= resistance / 2.2; }
            for (++bit; bit < bits; bit++) {
                resistance += 1;
                double current = voltage / resistance;
                resistance = 2.2 * resistance / (2.2 + resistance);
                voltage = resistance * current;
            }
            weights[selected] = voltage;
            sum += voltage;
        }
        for (int i = 0; i < bits; i++) weights[i] /= sum;
        double[] result = new double[1 << bits];
        for (int value = 0; value < result.length; value++)
            for (int bit = 0; bit < bits; bit++) result[value] += weights[bit] * ((value & (1 << bit)) != 0 ? 1 : 0.0075);
        return result;
    }

    private final class OpAmp {
        private final CircuitSpline transfer = new CircuitSpline(points);
        private double x = vmin;
        double solve(double ratio, double input) {
            double lo = vmin, hi = vmax, a = ratio + 1;
            double bvi = Math.max(vddt - input, 0), c = ratio * bvi * bvi;
            for (int iteration = 0; iteration < 128; iteration++) {
                double previous = x;
                double output = transfer.value(x), derivative = transfer.derivative(x);
                double bvx = Math.max(vddt - x, 0), bvo = Math.max(vddt - output, 0);
                double f = a * bvx * bvx - c - bvo * bvo;
                x -= f / (2 * (bvo * derivative - a * bvx));
                if (Math.abs(x - previous) < 1e-8) return transfer.value(x);
                if (f < 0) hi = previous; else lo = previous;
                if (!Double.isFinite(x) || x <= lo || x >= hi) x = (lo + hi) / 2;
            }
            throw new IllegalStateException("SID op-amp solver did not converge");
        }
    }
}