RayTracing / raytracing.github.io

Main Web Site (Online Books)
https://raytracing.github.io/
Creative Commons Zero v1.0 Universal
8.68k stars 852 forks source link

[Book 2, Chapter 8.2] Use range-based for-loop #1482

Open dimitry-ishenko opened 5 months ago

dimitry-ishenko commented 5 months ago

In Listing 70, instead of using math tricks to permute between min/max members of bbox, use range-based for-loop that was introduced in C++11. This improves readability and allows people to understand what is actually being done in the loop.


         point3 min( infinity,  infinity,  infinity);
         point3 max(-infinity, -infinity, -infinity);

-        for (int i = 0; i < 2; i++) {
-            for (int j = 0; j < 2; j++) {
-                for (int k = 0; k < 2; k++) {
-                    auto x = i*bbox.x.max + (1-i)*bbox.x.min;
-                    auto y = j*bbox.y.max + (1-j)*bbox.y.min;
-                    auto z = k*bbox.z.max + (1-k)*bbox.z.min;
-
-                    auto newx =  cos_theta*x + sin_theta*z;
-                    auto newz = -sin_theta*x + cos_theta*z;
-
-                    vec3 tester(newx, y, newz);
+        for (auto x : { bbox.x.min, bbox.x.max }) {
+            for (auto y : { bbox.y.min, bbox.y.max }) {
+                for (auto z : { bbox.z.min, bbox.z.max }) {
+
+                    vec3 tester {
+                         cos_theta*x + sin_theta*z,
+                         y,
+                        -sin_theta*x + cos_theta*z
+                    };

                     for (int c = 0; c < 3; c++) {
                         min[c] = fmin(min[c], tester[c]);```
hollasch commented 5 months ago

Thanks Dimitry.

hollasch commented 5 months ago

Ref #819

hollasch commented 5 months ago

Note the echo of this approach in perlin::perlin_interp().