Skip to content

Commit

Permalink
Added support for loading images
Browse files Browse the repository at this point in the history
  • Loading branch information
Pedro Jorquera committed Mar 13, 2024
1 parent 1d283b5 commit 316f4d3
Show file tree
Hide file tree
Showing 6 changed files with 8,089 additions and 1 deletion.
Binary file added resources/earthmap.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
35 changes: 35 additions & 0 deletions src/image.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#include "image.h"

#define STB_IMAGE_IMPLEMENTATION
#define STBI_FAILURE_USERMSG
#include "stb_image.h"

inline int clamp(int x, int low, int high) {
return (x < low) ? low : ((x < high) ? x : high - 1);
}

Image::Image(const std::string& filename) {
load(filename);
}

Image::~Image() {
STBI_FREE(_data);
}

bool Image::load(const std::string& filename) {
auto n = _bytesPerPixel;
_data = stbi_load(filename.c_str(), &_width, &_height, &n, _bytesPerPixel);
_bytesPerScanline = _width * _bytesPerPixel;
return _data != nullptr;
}

const unsigned char* Image::pixelData(int x, int y) const {
// Return the address of the three bytes of the pixel at x,y (or magenta if no data).
static unsigned char magenta[] = { 255, 0, 255 };
if (_data == nullptr) return magenta;

x = clamp(x, 0, _width);
y = clamp(y, 0, _height);

return _data + y * _bytesPerScanline + x * _bytesPerPixel;
}
27 changes: 27 additions & 0 deletions src/image.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#pragma once

#include <string>

class Image {

private:

const int _bytesPerPixel = 3;
unsigned char* _data;
int _width;
int _height;
int _bytesPerScanline;

public:

Image():_data(nullptr) {}
~Image();
Image(const std::string& filename);
bool load(const std::string& filename);

inline auto width() const { return _width; }
inline auto height() const { return _height; }

const unsigned char* pixelData(int x, int y) const;

};
16 changes: 15 additions & 1 deletion src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,24 @@ void twoSpheres() {
camera.render(scene, "image.ppm");
}

void earth() {
const auto earth_texture = make_shared<ImageTexture>("earthmap.jpg");
const auto earth_surface = make_shared<Lambertian>(earth_texture);
const auto globe = make_shared<Sphere>(Point(0.0, 0.0, 0.0), 2.0, earth_surface);

shared_ptr<Scene> scene = make_shared<Scene>();
scene->add(globe);

Camera camera(16.0 / 9.0, 100, 50, 400, 20.0, Vector(0.0, 0.0, 12.0), Vector(0.0, 0.0, 0.0), Vector(0.0, 1.0, 0.0), 0.0, 10.0);

camera.render(scene, "image.ppm");
}

int main() {
switch (1) {
switch (3) {
case 1: randomSpheres(); break;
case 2: twoSpheres(); break;
case 3: earth(); break;
}
return 0;
}
Loading

0 comments on commit 316f4d3

Please sign in to comment.