Worldstone
 All Classes Files Functions Variables Enumerations Enumerator Macros Pages
utils.cpp
1 //
2 // Created by Lectem on 05/11/2016.
3 //
4 #include "utils.h"
5 #include <stdio.h>
6 #include <fmt/format.h>
7 #include "Palette.h"
8 
9 namespace WorldStone
10 {
11 namespace Utils
12 {
13 
14 void exportToPGM(const char* output, const uint8_t* data, int width, int height, int maxVal)
15 {
16  assert(width > 0 && height > 0);
17  if (maxVal == -1) {
18  for (int i = 0; i < width * height; ++i)
19  {
20  if (maxVal < data[i]) maxVal = data[i];
21  }
22  }
23  maxVal = maxVal < 1 ? 1 : maxVal;
24  int bpp = maxVal >= 256 ? 2 : 1;
25  FILE* file = fopen(output, "wb");
26  if (file) {
27  fmt::print(file, "P5 {} {} {}\n", width, height, maxVal);
28  fwrite(data, static_cast<size_t>(bpp), static_cast<size_t>(width * height), file);
29  fclose(file);
30  }
31 }
32 
33 void exportToPGM(const char* output, ImageView<const uint8_t> image, int maxVal)
34 {
35  // TODO: just make this the default and use the stride
36  assert(image.width == image.stride);
37  exportToPGM(output, image.buffer, int(image.width), int(image.height), maxVal);
38 }
39 void exportToPPM(const char* output, const uint8_t* data, int width, int height,
40  const Palette& palette)
41 {
42  assert(width > 0 && height > 0);
43  FILE* file = fopen(output, "wb");
44  if (file) {
45  fmt::print(file, "P6 {} {} 255\n", width, height);
46  for (size_t i = 0; i < static_cast<size_t>(width * height); ++i)
47  {
48  const auto& colors = palette.colors;
49  fputc(colors[data[i]].r, file);
50  fputc(colors[data[i]].g, file);
51  fputc(colors[data[i]].b, file);
52  }
53  fclose(file);
54  }
55 }
56 } // namespace Utils
57 } // namespace WorldStone