]> git.mxchange.org Git - simgear.git/blob - simgear/nasal/mathlib.c
Clamp pitch values rather than just dumping an error message.
[simgear.git] / simgear / nasal / mathlib.c
1 #ifdef _MSC_VER
2 #define _USE_MATH_DEFINES
3 #endif
4
5 #include <math.h>
6 #include <string.h>
7
8 #include "nasal.h"
9
10 static naRef f_sin(naContext c, naRef args)
11 {
12     naRef a = naNumValue(naVec_get(args, 0));
13     if(naIsNil(a))
14         naRuntimeError(c, "non numeric argument to sin()");
15     a.num = sin(a.num);
16     return a;
17 }
18
19 static naRef f_cos(naContext c, naRef args)
20 {
21     naRef a = naNumValue(naVec_get(args, 0));
22     if(naIsNil(a))
23         naRuntimeError(c, "non numeric argument to cos()");
24     a.num = cos(a.num);
25     return a;
26 }
27
28 static naRef f_exp(naContext c, naRef args)
29 {
30     naRef a = naNumValue(naVec_get(args, 0));
31     if(naIsNil(a))
32         naRuntimeError(c, "non numeric argument to exp()");
33     a.num = exp(a.num);
34     return a;
35 }
36
37 static naRef f_ln(naContext c, naRef args)
38 {
39     naRef a = naNumValue(naVec_get(args, 0));
40     if(naIsNil(a))
41         naRuntimeError(c, "non numeric argument to ln()");
42     a.num = log(a.num);
43     return a;
44 }
45
46 static naRef f_sqrt(naContext c, naRef args)
47 {
48     naRef a = naNumValue(naVec_get(args, 0));
49     if(naIsNil(a))
50         naRuntimeError(c, "non numeric argument to sqrt()");
51     a.num = sqrt(a.num);
52     return a;
53 }
54
55 static naRef f_atan2(naContext c, naRef args)
56 {
57     naRef a = naNumValue(naVec_get(args, 0));
58     naRef b = naNumValue(naVec_get(args, 1));
59     if(naIsNil(a) || naIsNil(b))
60         naRuntimeError(c, "non numeric argument to atan2()");
61     a.num = atan2(a.num, b.num);
62     return a;
63 }
64
65 static struct func { char* name; naCFunction func; } funcs[] = {
66     { "sin", f_sin },
67     { "cos", f_cos },
68     { "exp", f_exp },
69     { "ln", f_ln },
70     { "sqrt", f_sqrt },
71     { "atan2", f_atan2 },
72 };
73
74 naRef naMathLib(naContext c)
75 {
76     naRef name, namespace = naNewHash(c);
77     int i, n = sizeof(funcs)/sizeof(struct func);
78     for(i=0; i<n; i++) {
79         naRef code = naNewCCode(c, funcs[i].func);
80         naRef name = naStr_fromdata(naNewString(c),
81                                     funcs[i].name, strlen(funcs[i].name));
82         naHash_set(namespace, name, naNewFunc(c, code));
83     }
84
85     // Set up constants for math.pi and math.e
86     name = naStr_fromdata(naNewString(c), "pi", 2);
87     naHash_set(namespace, name, naNum(M_PI));
88
89     name = naStr_fromdata(naNewString(c), "e", 1);
90     naHash_set(namespace, name, naNum(M_E));
91
92     return namespace;
93 }