yum-archive/SoggyShaders

Old Unity shaders.

git clone https://git.yummers.dev/yum-archive/SoggyShaders

yumCheck in cloud shader8427cb4

master
2.2 KiB89 linesraw
1#ifndef __MATH_INC
2#define __MATH_INC
3
4#include "pema99.cginc"
5
6#define PI 3.14159265
7
8// Differentiable approximation of the standard `max` function.
9float dmax(float a, float b, float k)
10{
11  return log2(exp2(k * a) + exp2(k * b)) / k;
12}
13
14// Differentiable approximation of the standard `min` function.
15float dmin(float a, float b, float k)
16{
17  return -1.0 * dmax(-1.0 * a, -1.0 * b, k);
18}
19
20// Generate a random number on [0, 1].
21float rand2(float2 p)
22{
23  return glsl_mod(sin(dot(p, float2(561.0, 885.0))) * 776.2, 1.0);
24}
25
26// Generate a random number on [0, 1].
27float rand3(float3 p)
28{
29  return glsl_mod(sin(dot(p, float3(897.0, 367.0, 197.0))) * 1073.6
30      + sin(dot(p, float3(473.0, 599.0, 1093.0))) * 12.6, 1.0);
31}
32
33// 3 dimensional value noise. `p` is assumed to be a point inside a unit cube.
34// Theory: https://en.wikipedia.org/wiki/Value_noise
35float vnoise3d(float3 p)
36{
37  float3 pu = floor(p);
38  float3 pv = glsl_mod(p, 1.0);
39
40  // Assign random numbers to the corner of a cube.
41  float n000 = rand3(pu + float3(0,0,0));
42  float n001 = rand3(pu + float3(0,0,1));
43  float n010 = rand3(pu + float3(0,1,0));
44  float n011 = rand3(pu + float3(0,1,1));
45  float n100 = rand3(pu + float3(1,0,0));
46  float n101 = rand3(pu + float3(1,0,1));
47  float n110 = rand3(pu + float3(1,1,0));
48  float n111 = rand3(pu + float3(1,1,1));
49
50  float n00 = lerp(n000, n001, pv.z);
51  float n01 = lerp(n010, n011, pv.z);
52  float n10 = lerp(n100, n101, pv.z);
53  float n11 = lerp(n110, n111, pv.z);
54
55  float n0 = lerp(n00, n01, pv.y);
56  float n1 = lerp(n10, n11, pv.y);
57
58  float n = lerp(n0, n1, pv.x);
59
60  return n;
61}
62
63float fbm(float3 p, const int n_octaves, float w)
64{
65  float g = exp2(-w);
66  float a = 1.0;
67  float p_scale = 1.0;
68
69  float res = 0.0;
70  for (int i = 0; i < n_octaves; i++) {
71    res += a * vnoise3d(p * p_scale);
72
73    p_scale /= w;
74    a *= g;
75  }
76
77  // On average, vnoise3d returns 0.5.
78  // Sum of any geometric series is, for growth parameter r and constant a,
79  // a / (1 - r).
80  // We want to map onto [0, 1], so divide by this expected sum.
81  // Use a = 1, to account for the worst-case possibility that every call to
82  // vnoise3d() returns 1.
83  res /= (1 / (1 - g));
84
85  return res;
86}
87
88#endif  // __MATH_INC
89