deepstone

view src/fixedp.h @ 34:c6406e4aa0fb

better input, fixed emulated code to work again
author John Tsiombikas <nuclear@member.fsf.org>
date Mon, 23 Sep 2013 05:58:24 +0300
parents 61d97b17cd2b
children 1fa939507d8b
line source
1 #ifndef FIXED_POINT_H_
2 #define FIXED_POINT_H_
4 #include "inttypes.h"
6 #ifdef DBG_USE_FLOAT
7 typedef float fixed;
8 #else
9 typedef int32_t fixed;
10 #endif
12 /* valid choices for DECIMAL_BITS
13 * 8: for fixed point 24:8
14 * 16: for fixed point 16:16
15 */
16 #define DECIMAL_BITS 16
18 #if DECIMAL_BITS == 8
19 #define FIXED_SHIFT 8
20 #define FLT_SCALE 256.0f
21 #define FRAC_MASK 0xff
22 #else /* DECIMAL_BITS == 16 */
23 #define FIXED_SHIFT 16
24 #define FLT_SCALE 65536.0f
25 #define FRAC_MASK 0xffff
26 #endif /* DECIMAL_BITS */
28 /*extern const fixed fixed_zero;
29 extern const fixed fixed_one;
30 extern const fixed fixed_half;
31 extern const fixed fixed_tenth;
32 extern const fixed fixed_255;*/
34 #ifdef DBG_USE_FLOAT
35 /* ------- debug mode, use floating point -------- */
36 #define FIXED_INT_PART(n) ((int)(n))
37 #define FIXED_FRAC_PART(n) ((n) > 0.0f ? (FIXED_INT_PART(n) - (n)) : (FIXED_INT_PART(n) + (n)))
38 #define FIXED_ROUND(n) FIXED_INT_PART((n) >= 0.0 ? (n) + 0.5f : (n) - 0.5f)
40 #define FIXED_TO_FLOAT(n) (n)
41 #define FLOAT_TO_FIXED(n) (n)
42 #define INT_TO_FIXED(n) ((float)(n))
44 #define FIXED_EPSILON (1e-6)
46 #else /* ---- really fixed point ---- */
48 #define FIXED_INT_PART(n) ((n) >> FIXED_SHIFT)
49 #define FIXED_FRAC_PART(n) ((n) & FRAC_MASK)
50 #define FIXED_ROUND(n) FIXED_INT_PART((n) >= 0 ? (n) + fixedf(0.5) : (n) - fixedf(0.5))
51 /*#define FIXED_ROUND(n) FIXED_INT_PART(n)*/
53 #define FIXED_TO_FLOAT(n) (float)((n) / FLT_SCALE)
54 #define FLOAT_TO_FIXED(n) (fixed)((n) * FLT_SCALE)
55 #define INT_TO_FIXED(n) (fixed)((n) << FIXED_SHIFT)
57 #define FIXED_EPSILON (1)
59 #endif
62 #define fixed_int(n) FIXED_INT_PART(n)
63 #define fixed_frac(n) FIXED_FRAC_PART(n)
64 #define fixed_float(n) FIXED_TO_FLOAT(n)
65 #define fixed_round(n) FIXED_ROUND(n)
67 #define fixedf(n) FLOAT_TO_FIXED(n)
68 #define fixedi(n) INT_TO_FIXED(n)
70 #define fixed_add(n1, n2) ((n1) + (n2))
71 #define fixed_sub(n1, n2) ((n1) - (n2))
75 #ifdef DBG_USE_FLOAT
77 #define fixed_mul(n1, n2) ((n1) * (n2))
78 #define fixed_div(n1, n2) ((n1) / (n2))
80 #define fixed_sin(x) (fixed)sin(x)
81 #define fixed_cos(x) (fixed)cos(x)
83 #else
85 #if DECIMAL_BITS == 8
86 #define fixed_mul(n1, n2) (fixed)((n1) * (n2) >> FIXED_SHIFT)
87 #define fixed_div(n1, n2) (((n1) << FIXED_SHIFT) / (n2))
88 #else
89 #define fixed_div(n1, n2) (((n2) >> 8) ? (((n1) << 8) / ((n2) >> 8)) : (n1))
90 #define fixed_mul(n1, n2) (((n1) >> 8) * ((n2) >> 8))
91 #endif /* DECIMAL_BITS */
93 #ifdef __cplusplus
94 extern "C" {
95 #endif
97 fixed fixed_sin(fixed angle);
98 fixed fixed_cos(fixed angle);
100 #ifdef __cplusplus
101 }
102 #endif
104 #endif
106 #endif /* FIXED_POINT_H_ */