Skip to content

Instantly share code, notes, and snippets.

@pacmancoder
Created November 18, 2017 22:11
Show Gist options
  • Save pacmancoder/f886e1f92ef86f4f1325ccd2355e6416 to your computer and use it in GitHub Desktop.
Save pacmancoder/f886e1f92ef86f4f1325ccd2355e6416 to your computer and use it in GitHub Desktop.
[Example] [Dcdr] How to write PPM format
// WARNING: this is a deprecated code from dcdr project;
// This can be broken, but still can be used as example how to write ppm file.
// Enjoy.
#include <vector>
#include <ifstream>
namespace Dcdr
{
// ------------- dcdr/Types.h ---------------
namepsace Types
{
typedef size_t Offset;
typedef float Real;
stuct Vec3
{
Real r, g, b;
};
}
// ------------- dcdr/renderer/ISurfaceRasterizer.h ---------------
class ISurfaceRasterizer
{
public:
virutal void set_image_size(Types::Size width, Types::Size height) = 0;
virutal void draw_pixel(Types::Vec3 color, Types::Offset x, Types::Offset y) = 0;
virtual ~ISurfaceRasterizer() = default;
};
// ------------- dcdr/renderer/PpmRasterizer.h ---------------
class PpmRasterizer : public ISurfaceRasterizer
{
public:
PpmRasterizer(Types::Offset width, Types::Offset height) :
width_(width),
height_(height),
pixels_()
{}
void set_image_size(Types::Size width, Types::Size height) override
{
pixels_.resize(width * height);
}
void draw_pixel(Types::Vec3 color, Types::Offset x, Types::Offset y) override
{
pixels_[y * width_ + x][0] = (unsigned char)(color.r * 255);
pixels_[y * width_ + x][1] = (unsigned char)(color.g * 255);
pixels_[y * width_ + x][2] = (unsigned char)(color.b * 255);
}
void save_file(const std::string& filename)
{
std::ofstream file(filename, std::ofstream::binary);
file << "P3" << std::endl;
file << width_ << " " << height_ << std::endl;
file << "255" << std::endl;
for (auto& pixel : pixels_)
file << Types::Offset(pixel[0]) << " "
<< Types::Offset(pixel[1]) << " "
<< Types::Offset(pixel[2])
<< std::endl;
}
private:
Types::Offset width_;
Types::Offset height_;
std::vector<unsigned char[3]> pixels_;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment