Code viewer for World: XOR - NN - 3D
AB.screenshotStep = 500;

// -------------------------------------------
// Tweak these
// -------------------------------------------

const gridSize = 10; // lower is faster
const squaresize = 20;

const learningrate = 0.2;

let rotateRate = 0.001;
let angle = 0;

const maxOpacity = 150;
const minOpacity = 50;

// --------------------------------------------

const noinput = 3;
const nohidden = 9;
const nooutput = 1;

function randomWeight() {
    return (AB.randomFloatAtoB(-0.5, 0.5));
}


var nn; // Global neural network variable

let training_data_3d = [
    { inputs: [0, 0, 0], outputs: [0] },
    { inputs: [0, 0, 1], outputs: [1] },
    { inputs: [0, 1, 0], outputs: [1] },
    { inputs: [0, 1, 1], outputs: [0] },
    { inputs: [1, 0, 0], outputs: [1] },
    { inputs: [1, 0, 1], outputs: [0] },
    { inputs: [1, 1, 0], outputs: [0] },
    { inputs: [1, 1, 1], outputs: [1] }
];

function setup() {
    createCanvas(800, 800, WEBGL);
    $.getScript("/uploads/codingtrain/matrix.js", function () {
        $.getScript("/uploads/codingtrain/nn.js", function () {
            nn = new NeuralNetwork(noinput, nohidden, nooutput);
        });
    });
}

function draw() {
    if (typeof nn == 'undefined') return;
    nn.setLearningRate(learningrate);
    background(75, 0, 130);
    orbitControl();

    rotateX(angle);
    rotateY(angle + 0.001);

    for (let i = 0; i < 10; i++) {
        let data = random(training_data_3d);
        nn.train(data.inputs, data.outputs);
    }

    for (let i = 0; i < gridSize; i++) {
        for (let j = 0; j < gridSize; j++) {
            for (let k = 0; k < gridSize; k++) {
                drawCube(i, j, k);
            }
        }
    }

    stroke('black');
    noFill();
    box(gridSize * squaresize);

    angle += rotateRate;
}

function getOpacity(n) {
    return n < 0.3 ? minOpacity : maxOpacity;

    //   const k = 10;
    //   return 1 / (1 + Math.exp(-k * (n - 0.5)));
}

function drawCube(i, j, k) {
    push();
    translate(i * squaresize - 90, j * squaresize - 90, k * squaresize - 90);

    let inputs = [i / gridSize, j / gridSize, k / gridSize];
    let output = nn.predict(inputs);

    // console.log("i: ",inputs,"o: ",output)

    y = output[0];

    fill(color(y * 255, y * 255, y * 255, (1 - y) * 255));
    noStroke();
    box(squaresize);
    pop();
}