Vulkan Schnee 0.0.1
High-performance rendering engine
Loading...
Searching...
No Matches
Random.h
Go to the documentation of this file.
1#pragma once
2
3#include <random>
4
5namespace Math
6{
7 inline std::mt19937& randomEngine()
8 {
9 static thread_local std::mt19937 engine( std::random_device{}() );
10 return engine;
11 }
12
13 inline int randomInt( int min, int max )
14 {
15 std::uniform_int_distribution<int> distribution( min, max );
16 return distribution( randomEngine() );
17 }
18
19 inline float randomFloat( float min, float max )
20 {
21 std::uniform_real_distribution<float> distribution( min, max );
22 return distribution( randomEngine() );
23 }
24
25 inline glm::vec3 randomVectorInCone(glm::vec3 direction, float angle)
26 {
27 // angle is in radians.
28 // direction defines the cone axis.
29
30 const float len2 = glm::dot(direction, direction);
31 if (len2 <= 0.000001f)
32 return {0.0f, 0.0f, 1.0f};
33
34 const glm::vec3 axis = glm::normalize(direction);
35
36 // Replace these with your own random floats in [0, 1].
37 const float u1 = randomFloat(0.0f, 1.0f);
38 const float u2 = randomFloat(0.0f, 1.0f);
39
40 // Uniform distribution over the cone's solid angle.
41 const float cosMax = std::cos(angle);
42 const float cosTheta = glm::mix(1.0f, cosMax, u1);
43 const float sinTheta = std::sqrt(1.0f - cosTheta * cosTheta);
44
45 const float phi = 2.0f * glm::pi<float>() * u2;
46
47 // Random vector in local space, where the cone points along +Z.
48 const glm::vec3 local{
49 std::cos(phi) * sinTheta,
50 std::sin(phi) * sinTheta,
51 cosTheta
52 };
53
54 // Build an orthonormal basis around `axis`.
55 const glm::vec3 helper =
56 std::abs(axis.z) < 0.999f
57 ? glm::vec3(0.0f, 0.0f, 1.0f)
58 : glm::vec3(1.0f, 0.0f, 0.0f);
59
60 const glm::vec3 tangent = glm::normalize(glm::cross(helper, axis));
61 const glm::vec3 bitangent = glm::cross(axis, tangent);
62
63 // Transform local cone vector into world space.
64 const glm::vec3 world =
65 tangent * local.x +
66 bitangent * local.y +
67 axis * local.z;
68
69 return glm::normalize(world);
70 }
71}
Definition Random.h:6
int randomInt(int min, int max)
Definition Random.h:13
float randomFloat(float min, float max)
Definition Random.h:19
std::mt19937 & randomEngine()
Definition Random.h:7
glm::vec3 randomVectorInCone(glm::vec3 direction, float angle)
Definition Random.h:25