Files
CPU-Raytracer/raytrace.c
T
2026-07-26 20:56:07 +02:00

51 lines
1.7 KiB
C

#include <stdlib.h>
#include "structs.h"
#include "collision.h"
#include "vectorOp.h"
#define MAXSPHERES 100
RGBA raytraceSphere(sphere **objectList, ray *lightray) {
RGBA pixel = (RGBA){0,0,0,1};
const int lightBounces = 1;
sphere **spheresHitList = (sphere **)calloc( (lightBounces + 1),sizeof(sphere*) );
int hitLightIndex = -1;
vec3 sphereNormal;
sphere *nearestSphere = nullptr;
vec3 nearestCollisionPoint = {10000,10000,10000};
for (int j = 0; j <= lightBounces; j++) {
nearestSphere = nullptr;
nearestCollisionPoint = (vec3){10000,10000,10000};
for (int i = 0; i < 100 && objectList[i] != nullptr; i++) {
vec3 collisionPoint = collisionPointSphere(lightray, objectList[i]);
if (collisionPoint.x == -10000000) {
}
else{
if (vec3Length(collisionPoint)< vec3Length(nearestCollisionPoint)) {
nearestCollisionPoint = collisionPoint;
nearestSphere = objectList[i];
}
}
}
if (nearestSphere != nullptr) {
sphereNormal = vec3Normalize(vec3Subtract(nearestCollisionPoint, nearestSphere->origin));////////////////////////////// optimize divide by sphere radius instead
lightray->direction = vec3Add(lightray->direction, vec3Scale(sphereNormal, 2));
lightray->origin = nearestCollisionPoint;
}
else {
sphereNormal = (vec3){1,1,1};
}
}
//pixel.r = -vec3Product(sphereNormal, lightray->direction);
pixel = (RGBA){1 - 0.5 *( sphereNormal.x + 1), 1 - 0.5 * (sphereNormal.y +1), 1 -0.5* (sphereNormal.z + 1),1};
free(spheresHitList);
return pixel;
}