]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/menu/nexuiz/slider_decibels.c
speed up exp function ;)
[divverent/nexuiz.git] / data / qcsrc / menu / nexuiz / slider_decibels.c
1 #ifdef INTERFACE
2 CLASS(NexuizDecibelsSlider) EXTENDS(NexuizSlider)
3         METHOD(NexuizDecibelsSlider, loadCvars, void(entity))
4         METHOD(NexuizDecibelsSlider, saveCvars, void(entity))
5         METHOD(NexuizDecibelsSlider, valueToText, string(entity, float))
6 ENDCLASS(NexuizDecibelsSlider)
7 entity makeNexuizDecibelsSlider(float, float, float, string);
8 #endif
9
10 #ifdef IMPLEMENTATION
11
12 float exp(float x)
13 {
14         return pow(2.718281828459045, x);
15
16         /* wtf did I do here?
17         float i;
18         float t, s;
19
20         s = 1;
21         t = 1;
22         for(i = 1; i < 100; ++i)
23         {
24                 t *= x;
25                 t /= i;
26                 s += t;
27         }
28
29         return s;
30         */
31 }
32
33 float ln(float x)
34 {
35         float i;
36         float r, r0;
37
38         r = 1;
39         r0 = 0;
40         for(i = 1; fabs(r - r0) >= 0.05; ++i)
41         {
42                 // Newton iteration on exp(r) = x:
43                 //   r <- r - (exp(r) - x) / (exp(r))
44                 //   r <- r - 1 + x / exp(r)
45                 r0 = r;
46                 r = r0 - 1 + x / exp(r0);
47         }
48         dprint("ln: ", ftos(i), " iterations\n");
49
50         return r;
51 }
52
53 #define LOG10 2.302585093
54
55 entity makeNexuizDecibelsSlider(float theValueMin, float theValueMax, float theValueStep, string theCvar)
56 {
57         entity me;
58         me = spawnNexuizDecibelsSlider();
59         me.configureNexuizSlider(me, theValueMin, theValueMax, theValueStep, theCvar);
60         return me;
61 }
62 void loadCvarsNexuizDecibelsSlider(entity me)
63 {
64         float v;
65
66         if not(me.cvarName)
67                 return;
68
69         v = cvar(me.cvarName);
70         if(v >= 0.98)
71                 me.value = 0;
72         else if(v < 0.0005)
73                 me.value = -1000000;
74         else
75                 me.value = 0.1 * floor(0.5 + 10.0 * ln(cvar(me.cvarName)) * 10 / LOG10);
76 }
77 void saveCvarsNexuizDecibelsSlider(entity me)
78 {
79         if not(me.cvarName)
80                 return;
81
82         if(me.value >= -0.1)
83                 cvar_set(me.cvarName, "1");
84         if(me.value < -33)
85                 cvar_set(me.cvarName, "0");
86         else
87                 cvar_set(me.cvarName, ftos(exp(me.value / 10 * LOG10)));
88 }
89
90 string valueToTextNexuizDecibelsSlider(entity me, float v)
91 {
92         if(v < -33)
93                 return "OFF";
94         else if(v >= -0.1)
95                 return "MAX";
96         return strcat(valueToTextSlider(me, v), " dB");
97 }
98
99 #endif