]> mj.ucw.cz Git - libucw.git/blob - images/math.h
58a884ef687bc3ec81a73e4fa447c789119ee802
[libucw.git] / images / math.h
1 #ifndef _IMAGES_MATH_H
2 #define _IMAGES_MATH_H
3
4 extern const u32 fast_div_tab[];
5 extern const byte fast_sqrt_tab[];
6
7 static inline uns isqr(int x)
8 {
9   return x * x;
10 }
11
12 static inline uns fast_div_u32_u8(uns x, uns y)
13 {
14   return ((u64)(x) * fast_div_tab[y]) >> 32;
15 }
16
17 static inline uns fast_sqrt_u16(uns x)
18 {
19   uns y;
20   if (x < (1 << 10) - 3)
21     y = fast_sqrt_tab[(x + 3) >> 2] >> 3;
22   else if (x < (1 << 14) - 28)
23     y = fast_sqrt_tab[(x + 28) >> 6] >> 1;
24   else
25     y = fast_sqrt_tab[x >> 8];
26   return (x < y * y) ? y - 1 : y;
27 }
28
29 static inline uns fast_sqrt_u32(uns x)
30 {
31   uns y;
32   if (x < (1 << 16))
33     {
34       if (x < (1 << 10) - 3)
35         y = fast_sqrt_tab[(x + 3) >> 2] >> 3;
36       else if (x < (1 << 14) - 28)
37         y = fast_sqrt_tab[(x + 28) >> 6] >> 1;
38       else
39         y = fast_sqrt_tab[x >> 8];
40     }
41   else
42     {
43       if (x < (1 << 24))
44         {
45           if (x < (1 << 20))
46             {
47               y = fast_sqrt_tab[x >> 12];
48               y = (fast_div_u32_u8(x, y) >> 3) + (y << 1);
49             }
50           else
51             {
52               y = fast_sqrt_tab[x >> 16];
53               y = (fast_div_u32_u8(x, y) >> 5) + (y << 3);
54             }
55         }
56       else
57         {
58           if (x < (1 << 28))
59             {
60               if (x < (1 << 26))
61                 {
62                   y = fast_sqrt_tab[x >> 18];
63                   y = (fast_div_u32_u8(x, y) >> 6) + (y << 4);
64                 }
65               else
66                 {
67                   y = fast_sqrt_tab[x >> 20];
68                   y = (fast_div_u32_u8(x, y) >> 7) + (y << 5);
69                 }
70             }
71           else
72             {
73               if (x < (1 << 30))
74                 {
75                   y = fast_sqrt_tab[x >> 22];
76                   y = (fast_div_u32_u8(x, y) >> 8) + (y << 6);
77                 }
78               else
79                 {
80                   y = fast_sqrt_tab[x >> 24];
81                   y = (fast_div_u32_u8(x, y) >> 9) + (y << 7);
82                 }
83             }
84         }
85     }
86   return (x < y * y) ? y - 1 : y;
87 }
88
89 #endif