I'm coding raytracer for linux terminal on C++, first I decided to describe the sphere, here is class and algorithm:
class Sphere
{
public:
float radius;
vector3 center;
bool is_intersect(vector3 camera, vector3 ray)
{
// vector from center to camera
vector3 v = center - camera;
// module of vector
float abs_v = v.length();
// ray must be normalized (in main)
float pr_v_on_ray = ray.dot_product(v);
float l2 = abs_v * abs_v - pr_v_on_ray * pr_v_on_ray;
return l2 - radius * radius <= 0;
}
};
vector2 and vector3 is self-written types for 2D and 3D vectors with all standard vectors operations (like normalization, module, dot product and another).
I'm creating sphere with center(0,0,0) and some Radius and all work:
// because terminal pixels not square
float distortion = (8.0 / 16) * (width / height);
Sphere sphere = {0.5, vector3(0,0,0)};
for (int i = 0; i < width; ++i)
{
for (int j = 0; j < height; ++j)
{
vector2 xy = (vector2((float)i, (float)j) / vector2(width, height))
* vector2(2,2) - vector2(1,1); // x,y Є [-1.0; 1.0]
xy.x *= distortion;
vector3 camera = vector3(0,0,1);
// ray from camera
vector3 ray = vector3(xy.x, xy.y, -1).normalize();
if (sphere.is_intersect(camera, ray)) mvaddch(j,i, '@');
But, when i change coordinates of center distortion appears:
Sphere sphere = {0.5, vector3(-0.5,-0.5,0)};
- Do I understand correctly algorithm of ray "shot"? If i need to "shot" ray from (1,2,3) to (5,2,1) point, then ray coordinates is (5-1,2-2,1-3) = (4,0,-2)?
I understand ray.x and ray.y is all pixels on screen, but what about ray.z?
I don't understand how camera's coordinates work. (x,y,z) is offset relative to the origin, and if i change z then size of sphere projection changes, its work, but if i change x or y all going bad. How to look my sphere from all 6 sides? (I will add rotation matrices if understand how to camera work)
What causes distortion when changing the coordinates of the center of the sphere?
My final target is camera which rotate around sphere. (I will add light later)
Sorry for my bad English, thank you for your patience.