-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSnapshot.cpp
85 lines (73 loc) · 1.78 KB
/
Snapshot.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include "Snapshot.hpp"
Snapshot::Snapshot(int width, int height)
:mWidth(width), mHeight(height), mPathToFile("render"+std::to_string(width)+"x"+std::to_string(height)+"px.ppm")
{
mPixels = new Color*[mHeight];
for(int i = 0;i<mHeight;i++)
mPixels[i] = new Color[mWidth];
}
Snapshot::Snapshot(const Snapshot &other)
:Snapshot(other.mWidth, other.mHeight)
{
}
Snapshot::~Snapshot()
{
if(!mWritten){
mPathToFile = "autosave_"+mPathToFile;
writeToImage();
}
for(int i=0;i<mHeight;i++)
delete[] mPixels[i];
delete[] mPixels;
mPixels = nullptr;
}
void Snapshot::clear(Color clearColor)
{
for(int i=mHeight-1;i>=0;i--){
for(int j=0;j<mWidth;j++){
mPixels[i][j] = clearColor;
}
}
}
void Snapshot::putPixel(int x, int y, Color color)
{
mPixels[y][x] = Color(
std::sqrt(color.x),
std::sqrt(color.y),
std::sqrt(color.z)
);
}
Vec3 Snapshot::getPixel(int i, int j)
{
return mPixels[i][j];
}
Vec3 **Snapshot::getPixelData()
{
return mPixels;
}
void Snapshot::writeToImage()
{
std::ofstream file;
file.open(mPathToFile);
file << "P3\n" << mWidth <<' '<< mHeight<<"\n255\n";
for(int i=mHeight-1;i>=0;i--){
for(int j=0;j<mWidth;j++){
auto r = mPixels[i][j].x;
auto g = mPixels[i][j].y;
auto b = mPixels[i][j].z;
file<<static_cast<int>(256*clamp(r, 0.0, 0.999))<<' '
<<static_cast<int>(256*clamp(g, 0.0, 0.999))<<' '
<<static_cast<int>(256*clamp(b, 0.0, 0.999))<<' '<<std::endl;
}
}
file.close();
mWritten = true;
}
int Snapshot::getWidth() const
{
return mWidth;
}
int Snapshot::getHeight() const
{
return mHeight;
}