Debian Codegraph @

tools/cso-lut/src/main.cpp

raw symbols SCIP
1 /*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <cmath>
18 #include <cstdlib>
19 #include <ctime>
20 #include <fstream>
21 #include <iomanip>
22 #include <iostream>
23
24 #include <math/scalar.h>
25 #include <math/vec3.h>
26
27 #include <image/LinearImage.h>
28
29 #include <imageio/ImageEncoder.h>
30
31 #include <utils/compiler.h>
32 #include <utils/Path.h>
33
34 #include <getopt/getopt.h>
35
36 using namespace filament::math;
37 using namespace image;
38 using namespace utils;
39
40 static ImageEncoder::Format g_format = ImageEncoder::Format::PNG_LINEAR;
41 static bool g_formatSpecified = false;
42 static bool g_groundTruth = false;
43 static std::string g_compression;
44
45 static void printUsage(const char* name) {
46 std::string execName(Path(name).getName());
47 std::string usage(
48 "CSO-LUT generates a lookup table for cone/sphere occlusions.\n"
49 "Usage:\n"
50 " CSO-LUT [options] <X Y Z> output_file\n"
51 "\n"
52 "Where X, Y and Z are the LUT dimensions on the X, Y and Z axis respectively.\n"
53 "If omitted, the dimensions will be 32 pixels by default."
54 "\n"
55 "Options:\n"
56 " --help, -h\n"
57 " Print this message\n\n"
58 " --license\n"
59 " Print copyright and license information\n\n"
60 " --ground-truth, -g\n"
61 " Uses a Monte Carlo simulation to generate the LUT\n\n"
62 " --format=[exr|hdr|psd|png|dds|inc|h|hpp|c|cpp|txt], -f [exr|hdr|psd|png|dds|inc|h|hpp|c|cpp|txt]\n"
63 " Specify output file format, inferred from file name if omitted\n\n"
64 " --compression=COMPRESSION, -c COMPRESSION\n"
65 " Format specific compression:\n"
66 " PNG: Ignored\n"
67 " Radiance: Ignored\n"
68 " Photoshop: 16 (default), 32\n"
69 " OpenEXR: RAW, RLE, ZIPS, ZIP, PIZ (default)\n"
70 " DDS: 8, 16 (default), 32\n\n"
71 );
72
73 const std::string from("CSO-LUT");
74 for (size_t pos = usage.find(from); pos != std::string::npos; pos = usage.find(from, pos)) {
75 usage.replace(pos, from.length(), execName);
76 }
77 printf("%s", usage.c_str());
78 }
79
80 static void license() {
81 static const char *license[] = {
82 #include "licenses/licenses.inc"
83 nullptr
84 };
85
86 const char **p = &license[0];
87 while (*p)
88 std::cout << *p++ << std::endl;
89 }
90
91 static int handleArguments(int argc, char* argv[]) {
92 static constexpr const char* OPTSTR = "hc:f:g";
93 static const struct option OPTIONS[] = {
94 { "help", no_argument, nullptr, 'h' },
95 { "license", no_argument, nullptr, 's' },
96 { "ground-truth", no_argument, nullptr, 'g' },
97 { "format", required_argument, nullptr, 'f' },
98 { "compression", required_argument, nullptr, 'c' },
99 { nullptr, 0, nullptr, 0 } // termination of the option list
100 };
101
102 int opt;
103 int optionIndex = 0;
104
105 while ((opt = getopt_long(argc, argv, OPTSTR, OPTIONS, &optionIndex)) >= 0) {
106 std::string arg(optarg ? optarg : "");
107 switch (opt) {
108 default:
109 case 'h':
110 printUsage(argv[0]);
111 exit(0);
112 // break;
113 case 's':
114 license();
115 exit(0);
116 // break;
117 case 'f':
118 if (arg == "png") {
119 g_format = ImageEncoder::Format::PNG_LINEAR;
120 g_formatSpecified = true;
121 }
122 if (arg == "hdr") {
123 g_format = ImageEncoder::Format::HDR;
124 g_formatSpecified = true;
125 }
126 if (arg == "exr") {
127 g_format = ImageEncoder::Format::EXR;
128 g_formatSpecified = true;
129 }
130 if (arg == "psd") {
131 g_format = ImageEncoder::Format::PSD;
132 g_formatSpecified = true;
133 }
134 if (arg == "dds") {
135 g_format = ImageEncoder::Format::DDS_LINEAR;
136 g_formatSpecified = true;
137 }
138 break;
139 case 'c':
140 g_compression = arg;
141 break;
142 case 'g':
143 g_groundTruth = true;
144 break;
145 }
146 }
147
148 return optind;
149 }
150
151 static bool isIncludeFile(const Path& filename) {
152 std::string extension(filename.getExtension());
153 return extension == "inc";
154 }
155
156 static bool isTextFile(const utils::Path& filename) {
157 std::string extension(filename.getExtension());
158 return extension == "h" || extension == "hpp" ||
159 extension == "c" || extension == "cpp" ||
160 extension == "inc" || extension == "txt";
161 }
162
163 static float sq(float x) { return x * x; }
164
165 constexpr float PI_F = 3.141592653589793238f;
166
167 static UTILS_UNUSED float sphericalCapsIntersection(float cosCap1, float cosCap2, float cosDistance) {
168 // Oat and Sander 2007, "Ambient Aperture Lighting"
169 float r1 = std::acos(cosCap1);
170 float r2 = std::acos(cosCap2);
171 float d = std::acos(cosDistance);
172
173 if (min(r1, r2) <= max(r1, r2) - d) {
174 return 2.0f * PI_F * (1.0f - max(cosCap1, cosCap2));
175 } else if (r1 + r2 <= d) {
176 return 0.0f;
177 }
178
179 float delta = abs(r1 - r2);
180 float x = 1.0f - saturate((d - delta) / max(r1 + r2 - delta, 1e-5f));
181 // simplified smoothstep()
182 float area = sq(x) * (-2.0f * x + 3.0f);
183 return area * 2.0f * PI_F * (1.0f - max(cosCap1, cosCap2));
184 }
185
186 static float conesIntersection(float cosTheta1, float cosTheta2, float cosAlpha) {
187 // Mazonka 2012, "Solid Angle of Conical Surfaces, Polyhedral Cones, and
188 // Intersecting Spherical Caps"
189 const float sinAlpha = std::sqrt(1.0f - sq(cosAlpha));
190
191 auto omega = [cosAlpha, sinAlpha](float cosTheta1, float cosTheta2) {
192 float sinTheta1 = std::sqrt(1.0f - sq(cosTheta1));
193
194 float ty = cosTheta2 - cosAlpha * cosTheta1;
195 float tx = sinAlpha * cosTheta1;
196
197 float cosPhi = clamp((ty * cosTheta1) / (tx * sinTheta1), -1.0f, 1.0f);
198 float cosBeta = clamp(ty / (sinTheta1 * std::sqrt(sq(tx) + sq(ty))), -1.0f, 1.0f);
199
200 float phi = std::acos(cosPhi);
201 float beta = std::acos(cosBeta);
202
203 return 2.0f * (beta - phi * cosTheta1);
204 };
205
206 const float omega1 = omega(cosTheta1, cosTheta2);
207 const float omega2 = omega(cosTheta2, cosTheta1);
208
209 if (cosAlpha > 0 && std::abs(1.0 - cosAlpha) < 1e-6f) {
210 return min(omega1, omega2);
211 }
212
213 if (cosAlpha < 0 && std::abs(1.0 + cosAlpha) < 1e-6f) {
214 return max(omega1 + omega2 - 4.0f * PI_F, 0.0f);
215 }
216
217 if (std::abs(1.0f - cosTheta1) < 1e-6f || std::abs(1.0f - cosTheta2) < 1e-6f) {
218 auto corrected = [cosAlpha](float omega1, float cosTheta1, float cosTheta2) {
219 float gamma = std::acos(cosAlpha) - std::acos(cosTheta2);
220 float theta1 = std::acos(cosTheta1);
221 if (gamma > theta1) {
222 return 0.0f;
223 } else if (gamma < -theta1) {
224 return omega1;
225 }
226 return omega1 * ((gamma + theta1) / (2.0f * theta1));
227 };
228 if (std::abs(1.0f - cosTheta1) < 1e-6f) {
229 return corrected(omega1, cosTheta1, cosTheta2);
230 }
231 return corrected(omega2, cosTheta2, cosTheta1);
232 }
233
234 if (std::abs(cosTheta1) < 1e-6f && std::abs(cosTheta2) < 1e-6f) {
235 return 2.0f * (PI_F - std::acos(cosAlpha));
236 }
237
238 if (std::abs(cosTheta1) < 1e-6f) {
239 return omega2;
240 }
241
242 if (std::abs(cosTheta2) < 1e-6f) {
243 return omega1;
244 }
245
246 return omega1 + omega2;
247 }
248
249 static void generateSampleRays(float cosAngle, float3* samples, size_t sampleCount) {
250 for (size_t i = 0; i < sampleCount; i++) {
251 float r1 = rand() / float(RAND_MAX);
252 float r2 = rand() / float(RAND_MAX);
253
254 float cosTheta = r1 * (1.0f - cosAngle) + cosAngle;
255 float sinTheta = std::sqrt(1.0f - sq(cosTheta));
256
257 float phi = 2.0f * PI_F * r2 - 1.0f;
258 float cosPhi = std::cos(phi);
259 float sinPhi = std::sin(phi);
260
261 samples[i] = float3{ sinTheta * cosPhi, sinTheta * sinPhi, cosTheta };
262 }
263 }
264
265 static float groundTruthVisibility(float cosTheta, float cosAlpha,
266 float3* samples, size_t sampleCount) {
267
268 float sinAlpha = std::sqrt(1.0f - sq(cosAlpha));
269 float3 occluderDirection{ sinAlpha, 0.0f, cosAlpha };
270
271 size_t hits = 0;
272 for (size_t i = 0; i < sampleCount; i++) {
273 if (dot(occluderDirection, samples[i]) > cosTheta) {
274 hits++;
275 }
276 }
277
278 return 1.0f - hits / float(sampleCount);
279 }
280
281 int main(int argc, char* argv[]) {
282 int optionIndex = handleArguments(argc, argv);
283
284 int numArgs = argc - optionIndex;
285 if (numArgs < 1) {
286 printUsage(argv[0]);
287 return 1;
288 }
289
290 size_t w = 32;
291 size_t h = 32;
292 size_t d = 32;
293
294 Path output;
295
296 if (numArgs >= 4) {
297 try {
298 w = std::stoi(argv[optionIndex]);
299 h = std::stoi(argv[optionIndex + 1]);
300 d = std::stoi(argv[optionIndex + 2]);
301 } catch (std::invalid_argument &e) {
302 // keep default value
303 }
304 output = argv[optionIndex + 3];
305 } else {
306 output = argv[optionIndex];
307 }
308
309 if (!g_formatSpecified) {
310 g_format = ImageEncoder::chooseFormat(output);
311 }
312
313 std::cout << "Generating " << w << "x" << h << "x" << d << " cone/sphere occlusion LUT in " <<
314 output << "..." << std::endl;
315
316 srand(time(nullptr));
317
318 constexpr size_t sampleCount = 1024;
319 float3 samples[sampleCount];
320
321 LinearImage image(w * d, h, 3);
322
323 for (size_t z = 0; z < d; z++) {
324 float cosTheta2 = clamp(z / (d - 1.0f), 1e-6f, 1.0f - 1e-6f);
325
326 if (g_groundTruth) {
327 generateSampleRays(cosTheta2, samples, sampleCount);
328 }
329
330 for (size_t y = 0; y < h; y++) {
331 float cosTheta1 = clamp(y / (h - 1.0f), 1e-6f, 1.0f - 1e-6f);
332 for (size_t x = 0; x < w; x++) {
333 float cosAlpha = clamp(2.0f * (x / (w - 1.0f)) - 1.0f, -1.0f + 1e-6f, 1.0f - 1e-6f);
334
335 float visibility;
336 if (g_groundTruth) {
337 visibility = groundTruthVisibility(cosTheta1, cosAlpha, samples, sampleCount);
338 } else {
339 float area = conesIntersection(cosTheta1, cosTheta2, cosAlpha);
340 visibility = 1.0f - area / (2.0f * PI_F * max(1.0f - cosTheta2, 1e-6f));
341 }
342
343 float3* pixel = image.get<float3>(x + z * w, y);
344 *pixel = float3{ saturate(visibility) };
345 }
346 }
347 }
348
349 if (!isTextFile(output)) {
350 std::ofstream outputStream(output, std::ios::binary | std::ios::trunc);
351 if (!outputStream.good()) {
352 std::cerr << "The output file cannot be opened: " << output << std::endl;
353 exit(1);
354 }
355
356 if (g_format == ImageEncoder::Format::PNG) {
357 g_format = ImageEncoder::Format::PNG_LINEAR;
358 }
359 ImageEncoder::encode(outputStream, g_format, image, g_compression, output.getPath());
360
361 outputStream.close();
362 if (!outputStream.good()) {
363 std::cerr << "An error occurred while writing the output file: " << output << std::endl;
364 exit(1);
365 }
366 } else {
367 const bool isInclude = isIncludeFile(output);
368 std::ofstream outputStream(output, std::ios::trunc);
369
370 outputStream << "// Generated with: cso-lut " << w << " " << h << " " << d << " " <<
371 output.c_str() << std::endl;
372 outputStream << "// LUT stored as a 3D R8 texture, in GL order" << std::endl;
373 outputStream << "// theta1 = angle of the first cone" << std::endl;
374 outputStream << "// theta2 = angle of the second cone" << std::endl;
375 outputStream << "// phi = angle between the two cones" << std::endl;
376 outputStream << "// X = cos(phi) in range -1..1" << std::endl;
377 outputStream << "// Y = cos(theta1) in range 0..1" << std::endl;
378 outputStream << "// Z = cos(theta2) in range 0..1" << std::endl;
379
380 if (!isInclude) {
381 outputStream << "const uint8_t CSO_LUT[] = {";
382 }
383
384 for (size_t z = 0; z < d; z++) {
385 for (size_t y = 0; y < h; y++) {
386 for (size_t x = 0; x < w; x++) {
387 if (x % 4 == 0) outputStream << std::endl << " ";
388 float3* pixel = image.get<float3>(x + z * w, h - 1 - y);
389 const int o = pixel->r * 255.0f;
390 outputStream << "0x" << std::setfill('0') << std::setw(2) << std::hex << o << ", ";
391 }
392 }
393 }
394
395 if (!isInclude) {
396 outputStream << std::endl << "};" << std::endl;
397 }
398
399 outputStream << std::endl;
400 outputStream.flush();
401 outputStream.close();
402 }
403 }