-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimage.cpp
More file actions
86 lines (69 loc) · 1.96 KB
/
image.cpp
File metadata and controls
86 lines (69 loc) · 1.96 KB
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
86
#include <algorithm>
#include <iostream>
#include <fstream>
#include "headers/image.h"
Image::Image(const int width, const int height)
: width(width), height(height)
{
data = new Color[width * height];
depthBuffer = new float[width * height];
shadowBuffer = new float[width * height];
for (int i=0; i<width*height; i++) {
depthBuffer[i] = Image::INF;
shadowBuffer[i] = Image::INF;
}
}
Image::~Image()
{
delete[] data;
delete[] depthBuffer;
}
int Image::getWidth() const
{
return width;
}
int Image::getHeight() const
{
return height;
}
Color Image::getPixel(int x, int y) const
{
return *(data + (x + y * width));
}
void Image::setPixel(int x, int y, const Color c)
{
*(data + (x + y * width)) = c;
}
float Image::getZDepth(int x, int y) const
{
return *(depthBuffer + (x + y * width));
}
float Image::getShadowDepth(int x, int y) const
{
return *(shadowBuffer + (x + y * width));
}
void Image::setZDepth(int x, int y, const float z) {
*(depthBuffer + (x + y * width)) = z;
}
void Image::setShadowDepth(int x, int y, const float z) {
*(shadowBuffer + (x + y * width)) = z;
}
void Image::saveImagePPM(std::string filename) const {
// data[] contains the RGB information with 0 = dark, 1 = full bright
// and the float betn 0 to 1 representing in between color
try {
std::ofstream ofs(filename, std::ios::binary | std::ios::out);
ofs << "P6\n" << width << " " << height << " 255" << std::endl;
for (int i=height-1; i>=0; i--) {
for (int j=0; j<width; j++) {
ofs << (unsigned char)(std::max(0.0f, std::min(data[i*width + j].r, 1.0f)) * 255)
<< (unsigned char)(std::max(0.0f, std::min(data[i*width + j].g, 1.0f)) * 255)
<< (unsigned char)(std::max(0.0f, std::min(data[i*width + j].b, 1.0f)) * 255);
}
}
ofs.close();
} catch(...) {
std::cerr << "Something really terrible happened so " + filename + " file couldn't be created!!" << std::endl;
}
std::cout << "Rendered image to a \"" + filename + "\" file. (SUCCESS)" << std::endl;
}