ubuntu20
4 years ago
9 changed files with 107 additions and 12 deletions
-
2Camera.cpp
-
2Ray.cpp
-
2Ray.h
-
31Scene.cpp
-
51Sphere.cpp
-
10Sphere.h
-
13Vector3.h
-
2raytracing.vcxproj
-
6raytracing.vcxproj.filters
@ -0,0 +1,51 @@ |
|||
#include "Sphere.h"
|
|||
#include"Ray.h"
|
|||
#include<math.h>
|
|||
|
|||
Sphere::Sphere(const Vector3 & origin, float radius) { |
|||
mOrigin = origin; |
|||
mRadius = radius; |
|||
} |
|||
|
|||
void Sphere::set(const Vector3 & origin, float radius) |
|||
{ |
|||
mOrigin = origin; |
|||
mRadius = radius; |
|||
} |
|||
|
|||
bool Sphere::HitTest(const Ray& input_ray, float min_distance, float max_distance, HitPoint& hit_point) { |
|||
Vector3 sphere_center_to_ray = input_ray.mOrigin - mOrigin; |
|||
float a = Dot(input_ray.mDirection, input_ray.mDirection); |
|||
float b = 2.0f * Dot(sphere_center_to_ray, input_ray.mDirection); |
|||
float c = Dot(sphere_center_to_ray, sphere_center_to_ray) - mRadius * mRadius; |
|||
float determinant = b * b - 4.0f * a * c; |
|||
|
|||
bool isHited = false; |
|||
float distance = -1.0f; |
|||
if (determinant > 0.0f) { |
|||
distance = (-b - sqrtf(determinant))/ 2.0f; |
|||
if (distance > min_distance && distance < max_distance) { |
|||
isHited = true; |
|||
} |
|||
distance = (-b + sqrtf(determinant)) / 2.0f; |
|||
if (distance > min_distance && distance < max_distance) { |
|||
isHited = true; |
|||
} |
|||
} |
|||
else if (determinant == 0.0f) { |
|||
distance = -b / 2.0f; |
|||
if (distance > min_distance && distance < max_distance) { |
|||
isHited = true; |
|||
} |
|||
} |
|||
|
|||
if (isHited) { |
|||
hit_point.mPosition = input_ray.PointAt(distance); |
|||
Vector3 normal = hit_point.mPosition - mOrigin; |
|||
normal.Normalize(); |
|||
hit_point.mDistance = distance; |
|||
hit_point.mNormal = normal; |
|||
} |
|||
|
|||
return isHited; |
|||
} |
@ -0,0 +1,10 @@ |
|||
#pragma once |
|||
#include "Vector3.h" |
|||
class Sphere : public Geometry { |
|||
public: |
|||
Vector3 mOrigin; |
|||
float mRadius; |
|||
Sphere(const Vector3& origin, float radius); |
|||
void set(const Vector3& origin, float radius); |
|||
bool HitTest(const Ray& input_ray, float min_distance, float max_distance, HitPoint& hit_point); |
|||
}; |
Write
Preview
Loading…
Cancel
Save
Reference in new issue