summaryrefslogtreecommitdiff
path: root/graphics/asymptote/cudareflect/tinyexr/examples/nornalmap/main.cc
blob: 6571739ff33e78eb182ba0a81eec044aa4bd7ae2 (plain)
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
#define TINYEXR_IMPLEMENTATION
#include "tinyexr.h"

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Weverything"
#endif

#define STB_IMAGE_RESIZE_IMPLEMENTATION
#include "stb_image_resize.h"

#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

#include "cxxopts.hpp"

#ifdef __clang__
#pragma clang diagnostic pop
#endif

namespace {

static void vnormalize(float v[3]) {
  const float d2 = v[0] * v[0] + v[1] * v[1] + v[2] * v[2];
  if (d2 > 1.0e-6f) {
    const float inv_d = 1.0f / std::sqrt(d2);
    v[0] *= inv_d;
    v[1] *= inv_d;
    v[2] *= inv_d;
  }
  return;
}


template<typename T>
static inline T clamp(const T v, const T min_v, const T max_v)
{
  return std::max(min_v, std::min(max_v, v));
}

//
// Compute gradient from scalar field.
// dx = (x + 1, y    ) - (x, y) 
// dy = (x    , y + 1) - (x, y) 
//
// TODO(syoyo): Use central difference with texel filtering.
//
static void Gradient(
  const std::vector<float> &src,
  const size_t width,
  const size_t height,
  const size_t x, const size_t y,
  const float bumpness,
  float dir[3])
{
  const size_t x1 = clamp(x + 1, size_t(0), width - 1);
  const size_t y1 = clamp(y + 1, size_t(0), height - 1);


  float v00 = src[y * width + x];
  float v01 = src[y * width + x1];
  float v11 = src[y1 * width + x];

  
  float dx = bumpness * (v01 - v00);
  float dy = bumpness * (v11 - v00);

  dir[0] = dx;
  dir[1] = dy;
  dir[2] = 0.0f;
    
}

///
/// Convert image(bump map for single channel, vector displacement map for 3 channels input) to normal map.
/// @param[in] base Base value fo
///
///
static void ToNormalMap(
  const std::vector<float> &src,
  const size_t width,
  const size_t height,
  const size_t channels,
  const float strength,
  std::vector<float> *dst)
{
  assert((channels == 1) || (channels == 3) || (channels == 4));

  dst->resize(width * height * 3);

  if (channels == 1) {
    // bump map
    for (size_t y = 0; y < height; y++) {
      for (size_t x = 0; x < width; x++) {
        float d[3];
        Gradient(src, width, height, x, y, strength, d);

        (*dst)[3 * (y * width + x) + 0] = d[0];
        (*dst)[3 * (y * width + x) + 1] = d[1];
        (*dst)[3 * (y * width + x) + 2] = d[2];

      }
    }

  } else {
    // vector displacement map

    for (size_t y = 0; y < height; y++) {
      for (size_t x = 0; x < width; x++) {

        float v[3];
        v[0] = src[channels * (y * width + x) + 0];
        v[1] = src[channels * (y * width + x) + 1];
        v[2] = src[channels * (y * width + x) + 2];

        v[0] *= strength;
        v[1] *= strength;
        v[2] *= strength;

        // Add (0, 0, 1)
        v[2] += 1.0f;

        // TODO(syoyo): Add option to not normalize.
        vnormalize(v);

        (*dst)[3 * (y * width + x) + 0] = 0.5f * v[0] + 0.5f;
        (*dst)[3 * (y * width + x) + 1] = 0.5f * v[1] + 0.5f;
        (*dst)[3 * (y * width + x) + 2] = 0.5f * v[2] + 0.5f;

      }
    }

  }

}

inline unsigned char ftouc(float f)
{
  int i = static_cast<int>(f * 255.0f);
  if (i > 255) i = 255;
  if (i < 0) i = 0;

  return static_cast<unsigned char>(i);
}

bool SaveImage(const char* filename, const float* rgb, int width, int height) {

  std::vector<unsigned char> dst(width * height * 3);

  for (size_t i = 0; i < width * height; i++) {
      dst[i * 3 + 0] = ftouc(rgb[i * 3 + 0]);
      dst[i * 3 + 1] = ftouc(rgb[i * 3 + 1]);
      dst[i * 3 + 2] = ftouc(rgb[i * 3 + 2]);
  }

  int ret = stbi_write_png(filename, width, height, 3, static_cast<const void*>(dst.data()), width * 3);

  return (ret > 0);
}

std::string GetFileExtension(const std::string &filename) {
  if (filename.find_last_of(".") != std::string::npos)
    return filename.substr(filename.find_last_of(".") + 1);
  return "";
}

} // namespace

int main(int argc, char **argv)
{
  cxxopts::Options options("normalmap", "help");
  options.add_options()
    ("s,strength", "Strength(scaling) for normal value", cxxopts::value<float>())
    ("i,input", "Input filename", cxxopts::value<std::string>())
    ("o,output", "Output filename", cxxopts::value<std::string>())
    ("r,resize", "Resize image. 0.5 = 50%%, 0.1 = 10%%", cxxopts::value<float>())
    ;

  auto result = options.parse(argc, argv);

  if (result.count("input") == 0) {
    std::cerr << "input filename missing" << std::endl;
    return EXIT_FAILURE;
  }

  if (result.count("output") == 0) {
    std::cerr << "output filename missing" << std::endl;
    return EXIT_FAILURE;
  }

  float strength = 1.0f;
  if (result.count("strength")) {
    strength = result["strength"].as<float>();
  }

  float resize = 1.0f;
  if (result.count("resize")) {
    resize = result["resize"].as<float>();
  }

  std::string input_filename = result["input"].as<std::string>();
  std::string output_filename = result["output"].as<std::string>();

  std::vector<float> src;
  size_t src_width;
  size_t src_height;

  {
    float *rgba = nullptr;
    int width, height;
    const char *err = nullptr;
    int ret = LoadEXR(&rgba, &width, &height, input_filename.c_str(), &err);
    if (TINYEXR_SUCCESS != ret) {
      std::cerr << "Failed to load EXR file [" << input_filename << "] code = " << ret << std::endl;
      if (err) {
        std::cerr << err << std::endl;
        FreeEXRErrorMessage(err);
      }
      
      return EXIT_FAILURE;
    }

    std::cout << "loaded EXR. width x height = " << width << "x" << height << std::endl;
    src.resize(size_t(width * height * 3));

    // ignore alpha for now
    for (size_t i = 0; i < size_t(width * height); i++) {
      src[3 * i + 0] = rgba[4 * i + 0];
      src[3 * i + 1] = rgba[4 * i + 1];
      src[3 * i + 2] = rgba[4 * i + 2];
    }

    src_width  = size_t(width);
    src_height = size_t(height);

    free(rgba);
  }

  std::cout << "strength = " << strength << std::endl;

  std::vector<float> dst;
  ToNormalMap(src, src_width, src_height, 3, strength, &dst);


  std::string ext = GetFileExtension(output_filename);
  if ((ext.compare("png") == 0) ||
      (ext.compare("PNG") == 0)) {
    // Save as LDR image.
    // Do not apply sRGB conversion for PNG(LDR) image.
    if (!SaveImage(output_filename.c_str(), dst.data(), int(src_width), int(src_height))) {
      std::cerr << "Failed to write a file : " << output_filename << std::endl;
      return EXIT_FAILURE;
    } 
  } else {
    // assume EXR.
    float *rgba = nullptr;
    int width, height;
    int ret = SaveEXR(dst.data(), int(src_width), int(src_height), /* component */3, /* fp16 */0, output_filename.c_str(), nullptr);
    if (TINYEXR_SUCCESS != ret) {
      std::cerr << "Failed to save EXR file [" << input_filename << "] code = " << ret << std::endl;
      return EXIT_FAILURE;
    }
  }

  return EXIT_SUCCESS;
}