TinyRaytracer 0.1
A simple C++ raytracer
Loading...
Searching...
No Matches
vec3.hpp
Go to the documentation of this file.
1
12#ifndef VEC3_H
13#define VEC3_H
14#include <cmath>
15#include <iostream>
16
17/*vector direction of a ray*/
18class vec3{
19public:
20 double x = 0.0;
21 double y = 0.0;
22 double z = 0.0;
23
24 vec3(){};
25
26 vec3(double a,double b,double c): x(a),y(b),z(c) {};
27
28 bool operator==(const vec3& other) const {
29 return (x == other.x && y == other.y && z==other.z);
30 }
31
32 double operator[](size_t index) const{
33 if (index == 0) return x;
34 else if (index == 1) return y;
35 else if (index == 2) return z;
36 throw std::out_of_range("Index out of range");
37 }
38
39
40 vec3 operator+(const vec3& other) const {
41 return vec3(x+other.x,y+other.y,z+other.z);
42 }
43
44 vec3 operator-(const vec3& other) const {
45 return vec3(x-other.x,y-other.y,z-other.z);
46 }
47
48 vec3 operator*(double scalar) const {
49 return vec3(x * scalar,y * scalar,z * scalar);
50 }
51
52 vec3 operator/(double scalar) const {
53 return vec3(x / scalar,y / scalar,z / scalar);
54 }
55
56 friend vec3 operator*(double scalar, const vec3& other) {
57 return vec3(other.x * scalar, other.y * scalar, other.z * scalar);
58 }
59
60 double dot(const vec3& other) const {
61 return x * other.x + y * other.y + z * other.z;
62 }
63
64 double length() const {
65 return std::sqrt(x * x + y * y + z * z);
66 }
67
68 vec3 normalize() const {
69 double mag = length();
70 if (mag == 0) {
71 return vec3(0.0, 0.0, 0.0);
72 }
73 return vec3(x / mag, y / mag, z / mag);
74 }
75
80 vec3 operator-() const {
81 return vec3(-x, -y, -z);
82 }
83};
84
85using point3 = vec3;
86
87inline double dot(const vec3& a, const vec3& b) {
88 return a.x * b.x + a.y * b.y + a.z * b.z;
89}
90
91inline vec3 cross(const vec3& a, const vec3& b) {
92 return vec3(
93 a.y * b.z - a.z * b.y,
94 a.z * b.x - a.x * b.z,
95 a.x * b.y - a.y * b.x
96 );
97}
98
99#endif
Definition: vec3.hpp:18
vec3 operator-() const
Inverts the vector.
Definition: vec3.hpp:80