summaryrefslogtreecommitdiffstats
path: root/src/3rdparty/resonance-audio/resonance_audio/geometrical_acoustics/reflection_kernel_test.cc
blob: bf1806996306b19ae0b1fc44d5e2621acc9d6e1b (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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/*
Copyright 2018 Google Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include "geometrical_acoustics/reflection_kernel.h"

#include <cmath>
#include <functional>
#include <random>

#include "third_party/googletest/googletest/include/gtest/gtest.h"
#include "Eigen/Dense"
#include "geometrical_acoustics/test_util.h"

namespace vraudio {

namespace {

using Eigen::Quaternionf;
using Eigen::Vector3f;

class ReflectionKernelTest : public testing::Test {
 public:
  ReflectionKernelTest()
      : incident_ray_(Vector3f(0.0f, 0.0f, 0.0f).data(),
                      Vector3f(1.0f, 1.0f, 1.0f).normalized().data(), 0.0f,
                      AcousticRay::kInfinity, kEnergies,
                      AcousticRay::RayType::kSpecular, 0.0f),
        random_engine_(0),
        distribution_(0.0f, 1.0f) {}

  void SetUp() override {
    // Reseed the random number generator for every test to be deterministic
    // and remove flakiness in tests.
    random_engine_.seed(0);
    random_number_generator_ = [this] { return distribution_(random_engine_); };
  }

 protected:
  const std::array<float, kNumReverbOctaveBands> kEnergies = {
      {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f}};
  const std::array<float, kNumReverbOctaveBands> kUnitAbsorptionCoefficients = {
      {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f}};
  const std::array<float, kNumReverbOctaveBands> kZeroAbsorptionCoefficients = {
      {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}};

  AcousticRay incident_ray_;
  std::default_random_engine random_engine_;
  std::uniform_real_distribution<float> distribution_;
  std::function<float()> random_number_generator_;
};

TEST_F(ReflectionKernelTest, EnergyAbsorptionTest) {
  const std::array<float, kNumReverbOctaveBands>& original_energies =
      incident_ray_.energies();
  {
    // An absorption coefficient of 1 means that no energy is reflected.
    const ReflectionKernel reflection(kUnitAbsorptionCoefficients, 0.0f,
                                      random_number_generator_);
    const AcousticRay reflected_ray = reflection.Reflect(incident_ray_);
    for (size_t i = 0; i < kNumReverbOctaveBands; ++i) {
      EXPECT_FLOAT_EQ(reflected_ray.energies().at(i), 0.0f);
    }
  }
  {
    // An absorption coefficient of 0 means that all energy is reflected.
    const ReflectionKernel reflection(kZeroAbsorptionCoefficients, 0.0f,
                                      random_number_generator_);
    const AcousticRay reflected_ray = reflection.Reflect(incident_ray_);
    for (size_t i = 0; i < kNumReverbOctaveBands; ++i) {
      EXPECT_FLOAT_EQ(reflected_ray.energies().at(i), original_energies.at(i));
    }
  }
  {
    // An absorption coefficient of x means that only (1.0 - x) of the energy
    // would be reflected.
    std::array<float, kNumReverbOctaveBands> absorption_coefficients = {
        {0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f}};
    const ReflectionKernel reflection(absorption_coefficients, 0.0f,
                                      random_number_generator_);
    const AcousticRay reflected_ray = reflection.Reflect(incident_ray_);
    for (size_t i = 0; i < kNumReverbOctaveBands; ++i) {
      EXPECT_FLOAT_EQ(
          reflected_ray.energies().at(i),
          (1.0f - absorption_coefficients.at(i)) * original_energies.at(i));
    }
  }
}

TEST_F(ReflectionKernelTest, ScatteringCoefficientTest) {
  // Setting the scattering coefficient to 0.3 means 30% of the rays are
  // reflected diffusely while 70% are reflected specularly.
  const ReflectionKernel reflection(kUnitAbsorptionCoefficients, 0.3f,
                                    random_number_generator_);

  float specular_fraction = 0.0f;
  float diffuse_fraction = 0.0f;
  const int num_samples = 10000;
  const float fraction_per_sample = 1.0f / static_cast<float>(num_samples);
  for (int i = 0; i < num_samples; ++i) {
    const AcousticRay reflected_ray = reflection.Reflect(incident_ray_);
    (reflected_ray.type() == AcousticRay::RayType::kDiffuse
         ? diffuse_fraction
         : specular_fraction) += fraction_per_sample;
  }
  EXPECT_NEAR(diffuse_fraction, 0.3f, 0.01f);
  EXPECT_NEAR(specular_fraction, 0.7f, 0.01f);
}

TEST_F(ReflectionKernelTest, MultipleReflectionsTest) {
  const ReflectionKernel reflection(kUnitAbsorptionCoefficients, 0.0f,
                                    random_number_generator_);

  // Reflect |num_reflections| times. Validate that each reflected ray starts
  // where its incident ray ends. This is to simulate the effect of a typical
  // path tracer.
  const size_t num_reflections = 5;
  const float t_between_intersections = 2.0f;
  const float distance_between_intersections = t_between_intersections *
      Vector3f(incident_ray_.direction()).norm();

  AcousticRay ray = incident_ray_;
  float expected_prior_distance = 0.0f;
  for (size_t i = 0; i < num_reflections; ++i) {
    // Emulate an intersection at t = 2, with a plane whose (unnormalized)
    // normal being (0, 0, -1) for even iterations and (0, 0, 1) for odd
    // iterations.
    ray.set_t_far(t_between_intersections);
    const float even_normal[3] = {0.0f, 0.0f, -1.0f};
    const float odd_normal[3] = {0.0f, 0.0f, 1.0f};
    ray.set_intersected_geometry_normal((i % 2 == 0) ? even_normal
                                                     : odd_normal);
    const AcousticRay reflected_ray = reflection.Reflect(ray);

    // Check that the reflected ray starts where the original ray ends.
    const Vector3f& expected_reflected_ray_origin =
        Vector3f(ray.origin()) + ray.t_far() * Vector3f(ray.direction());
    ExpectFloat3Close(reflected_ray.origin(),
                      expected_reflected_ray_origin.data());
    EXPECT_FLOAT_EQ(reflected_ray.t_near(), AcousticRay::kRayEpsilon);

    // Check that the |prior_distance| field accumulates the distance traveled.
    expected_prior_distance += distance_between_intersections;
    EXPECT_FLOAT_EQ(reflected_ray.prior_distance(), expected_prior_distance);

    // Continue tracing the reflected ray.
    ray = reflected_ray;
  }
}

TEST_F(ReflectionKernelTest, SpecularReflectionTest) {
  // Emulate an intersection at t = 2, with a plane whose (unnormalized) normal
  // is (-1, -1, 0).
  incident_ray_.set_t_far(2.0f);
  const float normal[3] = {-1.0f, -1.0f, 0.0f};
  incident_ray_.set_intersected_geometry_normal(normal);

  // Setting the scattering coefficient to zero means to always reflect
  // specularly.
  const ReflectionKernel reflection(kUnitAbsorptionCoefficients, 0.0f,
                                    random_number_generator_);
  const AcousticRay reflected_ray = reflection.Reflect(incident_ray_);

  // Validate non-directional data.
  EXPECT_FLOAT_EQ(reflected_ray.t_near(), AcousticRay::kRayEpsilon);
  EXPECT_EQ(reflected_ray.type(), AcousticRay::RayType::kSpecular);
  const float expected_reflected_origin[3] = {1.15470053838f, 1.15470053838f,
                                              1.15470053838f};
  ExpectFloat3Close(reflected_ray.origin(), expected_reflected_origin);

  // Validate the reflected direction.
  const Vector3f& expected_reflected_direction =
      Vector3f(-1.0f, -1.0f, 1.0f).normalized();
  ExpectFloat3Close(reflected_ray.direction(),
                    expected_reflected_direction.data());
}

TEST_F(ReflectionKernelTest, DiffuseReflectionTest) {
  // Emulate an intersection at t = 2, with a plane whose (unnormalized) normal
  // is (-1, -1, 0).
  incident_ray_.set_t_far(2.0f);
  const float normal[3] = {-1.0f, -1.0f, 0.0f};
  incident_ray_.set_intersected_geometry_normal(normal);

  // Setting the scattering coefficient to 1.0 means to always reflect
  // diffusely.
  const ReflectionKernel reflection(kUnitAbsorptionCoefficients, 1.0f,
                                    random_number_generator_);
  const AcousticRay reflected_ray = reflection.Reflect(incident_ray_);

  // Validate non-directional data.
  EXPECT_FLOAT_EQ(reflected_ray.t_near(), AcousticRay::kRayEpsilon);
  EXPECT_EQ(reflected_ray.type(), AcousticRay::RayType::kDiffuse);

  // Validate the reflected directions.
  // For a reflected ray whose direction distribution is cosine-weighted over a
  // hemisphere:
  // - The PDF of theta is 2 sin(theta) cos(theta), and the CDF is sin^2(theta).
  // - The PDF of phi is 1 / 2 pi, and the CDF is 0.5 + phi / 2 pi.
  const Vector3f& plane_unit_normal =
      Vector3f(incident_ray_.intersected_geometry_normal()).normalized();
  ValidateDistribution(100000, 100, [&reflection, &plane_unit_normal, this]() {
    const AcousticRay reflected_ray = reflection.Reflect(incident_ray_);
    const Vector3f& local_direction =
        Quaternionf::FromTwoVectors(plane_unit_normal, Vector3f::UnitZ()) *
        Vector3f(reflected_ray.direction());
    const float cos_theta = local_direction.z();
    const float sin_theta_square = 1.0f - cos_theta * cos_theta;
    return sin_theta_square;
  });

  ValidateDistribution(100000, 100, [&reflection, &plane_unit_normal, this]() {
    const AcousticRay reflected_ray = reflection.Reflect(incident_ray_);
    const Vector3f& local_direction =
        Quaternionf::FromTwoVectors(plane_unit_normal, Vector3f::UnitZ()) *
        Vector3f(reflected_ray.direction());
    const float phi = std::atan2(local_direction.y(), local_direction.x());
    return 0.5f + phi / 2.0f / static_cast<float>(M_PI);
  });
}

TEST_F(ReflectionKernelTest, DiffuseRainReflectionTest) {
  // Emulate an intersection at t = 2, with a plane whose (unnormalized) normal
  // is (-1, -1, 0).
  incident_ray_.set_t_far(2.0f);
  const float normal[3] = {-1.0f, -1.0f, 0.0f};
  incident_ray_.set_intersected_geometry_normal(normal);

  // Setting the scattering coefficient to 1.0 means to always reflect
  // diffusely.
  const ReflectionKernel reflection(kUnitAbsorptionCoefficients, 1.0f,
                                    random_number_generator_);
  const AcousticRay reference_reflected_ray = reflection.Reflect(incident_ray_);

  // Generate a diffuse-rain ray for a listener on the same side of the plane.
  float direction_pdf = -1.0f;
  const Vector3f same_side_listener_position(0.0f, 0.0f, 2.0f);
  AcousticRay diffuse_rain_ray;
  reflection.ReflectDiffuseRain(incident_ray_, reference_reflected_ray,
                                same_side_listener_position, &direction_pdf,
                                &diffuse_rain_ray);

  // The direction of the diffuse-rain ray should be from the reflection point
  // (the origin of the |reference_reflected_ray|) to the listener position.
  const Vector3f reflection_point_to_listener_position =
      same_side_listener_position - Vector3f(reference_reflected_ray.origin());
  const Vector3f expected_direction =
      reflection_point_to_listener_position.normalized();
  ExpectFloat3Close(diffuse_rain_ray.direction(), expected_direction.data());

  // The output |direction_pdf| should be cos(theta) / pi, where theta is the
  // angle between the normal of the reflecting surface and the expected
  // direction.
  const float cos_theta = expected_direction.dot(Vector3f(normal).normalized());
  EXPECT_FLOAT_EQ(direction_pdf, cos_theta / kPi);

  // Verify that the |t_far| - |t_near| is the distance between the reflection
  // point and the listener position.
  EXPECT_FLOAT_EQ(diffuse_rain_ray.t_far() - diffuse_rain_ray.t_near(),
                  reflection_point_to_listener_position.norm());

  // Verify that other data are the same as |reference_reflected_ray|.
  ExpectFloat3Close(diffuse_rain_ray.origin(),
                    reference_reflected_ray.origin());
  EXPECT_FLOAT_EQ(diffuse_rain_ray.t_near(), reference_reflected_ray.t_near());
  ExpectFloat3Close(diffuse_rain_ray.intersected_geometry_normal(),
                    reference_reflected_ray.intersected_geometry_normal());
  for (size_t band = 0; band < kNumReverbOctaveBands; ++band) {
    EXPECT_FLOAT_EQ(diffuse_rain_ray.energies()[band],
                    reference_reflected_ray.energies()[band]);
  }
  EXPECT_EQ(diffuse_rain_ray.type(), reference_reflected_ray.type());
  EXPECT_FLOAT_EQ(diffuse_rain_ray.prior_distance(),
                  reference_reflected_ray.prior_distance());

  // Generate a diffuse-rain ray for a listener on the different side of the
  // plane and expect that the output |direction_pdf| is zero, meaning there is
  // no chance that the diffuse-rain ray is in that direction.
  const Vector3f different_side_listener_position(10.0f, 10.0f, 10.0f);
  reflection.ReflectDiffuseRain(incident_ray_, reference_reflected_ray,
                                different_side_listener_position,
                                &direction_pdf, &diffuse_rain_ray);
  EXPECT_FLOAT_EQ(direction_pdf, 0.0f);
}

}  // namespace

}  // namespace vraudio