//
// Created by ary on 29.07.2026.
//

#include "helper.h"
#include <stdlib.h>
#include <math.h>
#include "structs.h"
#include "vectorOp.h"
#define EPSILON 1e-8

vec3 randUnitVector() {
    double x1,x2,lengthSquared;
    do {
        x1 = (rand() / (double) RAND_MAX) * 2 - 1; //random zahl zwischen -1 und 1
        x2 = (rand() / (double) RAND_MAX) * 2 - 1;
        lengthSquared = x1 * x1 + x2 * x2;
    }while (lengthSquared >= 1);

    double weirdFactor = 2.0 * sqrt(1.0 - lengthSquared);
    return (vec3){
        x1 * weirdFactor,
        x2 * weirdFactor,
        1.0 - 2.0 * lengthSquared};
}

int epsilonCheck(vec3 p1, vec3 p2) { //if distance is to small, the test fails (return 0)
    vec3 distanceVector = vec3Subtract(p1, p2);
    double sumVector = fabs(distanceVector.x) + fabs(distanceVector.y) + fabs(distanceVector.z);
    if (sumVector <= EPSILON) {
        return 0;
    }
    return 1;
}

cube createCuboid(vec3 origin, vec3 right, vec3 up, vec3 forward, RGBA color) {
    cube object;
    object.quad1.origin = origin;
    object.quad1.v1 = right;
    object.quad1.v2 = up;
    object.quad1.normal = vec3Normalize(vec3Cross(object.quad1.v2, object.quad1.v1));
    object.quad1.color = color;

    object.quad2.origin = vec3Add(origin, forward);
    object.quad2.v1 = vec3Scale(forward, -1);
    object.quad2.v2 = up;
    object.quad2.normal = vec3Normalize(vec3Cross(object.quad2.v2, object.quad2.v1));
    object.quad2.color = color;

    object.quad3.origin = vec3Add(object.quad2.origin, right);
    object.quad3.v1 = vec3Scale(right, -1);
    object.quad3.v2 = up;
    object.quad3.normal = vec3Normalize(vec3Cross(object.quad3.v2, object.quad3.v1));
    object.quad3.color = color;

    object.quad4.origin = vec3Add(origin, right);
    object.quad4.v1 = forward;
    object.quad4.v2 = up;
    object.quad4.normal = vec3Normalize(vec3Cross(object.quad4.v2, object.quad4.v1));
    object.quad4.color = color;

    object.quad5.origin = origin;
    object.quad5.v1 = forward;
    object.quad5.v2 = right;
    object.quad5.normal = vec3Normalize(vec3Cross(object.quad5.v2, object.quad5.v1));
    object.quad5.color = color;

    object.quad6.origin = vec3Add(origin, up);
    object.quad6.v1 = right;
    object.quad6.v2 = forward;
    object.quad6.normal = vec3Normalize(vec3Cross(object.quad6.v2, object.quad6.v1));
    object.quad6.color = color;

    return object;
}

cube createCube(vec3 origin, double size, double pitch, double yaw, double roll) {
    vec3 right, up, forward;
    right = vec3Scale((vec3){1,0,0}, size);
    up = vec3Scale((vec3){0,1,0}, size);
    forward = vec3Scale((vec3){0,0,1}, size);


}