ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/include/util.h
Revision: 1.62
Committed: Fri Jan 25 18:13:57 2008 UTC (16 years, 4 months ago) by root
Content type: text/plain
Branch: MAIN
CVS Tags: rel-2_42
Changes since 1.61: +1 -1 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.46 /*
2 root 1.58 * This file is part of Deliantra, the Roguelike Realtime MMORPG.
3 root 1.46 *
4 root 1.58 * Copyright (©) 2005,2006,2007 Marc Alexander Lehmann / Robin Redeker / the Deliantra team
5 root 1.46 *
6 root 1.58 * Deliantra is free software: you can redistribute it and/or modify
7 root 1.51 * it under the terms of the GNU General Public License as published by
8     * the Free Software Foundation, either version 3 of the License, or
9     * (at your option) any later version.
10 root 1.46 *
11 root 1.51 * This program is distributed in the hope that it will be useful,
12     * but WITHOUT ANY WARRANTY; without even the implied warranty of
13     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14     * GNU General Public License for more details.
15 root 1.46 *
16 root 1.51 * You should have received a copy of the GNU General Public License
17     * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 root 1.46 *
19 root 1.58 * The authors can be reached via e-mail to <support@deliantra.net>
20 root 1.46 */
21    
22 root 1.1 #ifndef UTIL_H__
23     #define UTIL_H__
24    
25 root 1.36 //#define PREFER_MALLOC
26 root 1.62 #define DEBUG_SALLOC
27 root 1.36
28 root 1.2 #if __GNUC__ >= 3
29 root 1.45 # define is_constant(c) __builtin_constant_p (c)
30     # define expect(expr,value) __builtin_expect ((expr),(value))
31     # define prefetch(addr,rw,locality) __builtin_prefetch (addr, rw, locality)
32 root 1.2 #else
33 root 1.45 # define is_constant(c) 0
34     # define expect(expr,value) (expr)
35     # define prefetch(addr,rw,locality)
36 root 1.2 #endif
37    
38 root 1.47 #if __GNUC__ < 4 || (__GNUC__ == 4 || __GNUC_MINOR__ < 4)
39     # define decltype(x) typeof(x)
40     #endif
41    
42 root 1.45 // put into ifs if you are very sure that the expression
43     // is mostly true or mosty false. note that these return
44     // booleans, not the expression.
45     #define expect_false(expr) expect ((expr) != 0, 0)
46     #define expect_true(expr) expect ((expr) != 0, 1)
47    
48 root 1.11 #include <cstddef>
49 root 1.28 #include <cmath>
50 root 1.25 #include <new>
51     #include <vector>
52 root 1.11
53     #include <glib.h>
54    
55 root 1.25 #include <shstr.h>
56     #include <traits.h>
57    
58 root 1.60 #ifdef DEBUG_SALLOC
59     # define g_slice_alloc0(s) debug_slice_alloc0(s)
60     # define g_slice_alloc(s) debug_slice_alloc(s)
61     # define g_slice_free1(s,p) debug_slice_free1(s,p)
62     void *g_slice_alloc (unsigned long size);
63     void *g_slice_alloc0 (unsigned long size);
64     void g_slice_free1 (unsigned long size, void *ptr);
65     #endif
66    
67 root 1.49 // use C0X decltype for auto declarations until ISO C++ sanctifies them (if ever)
68 root 1.47 #define auto(var,expr) decltype(expr) var = (expr)
69 root 1.14
70 root 1.26 // very ugly macro that basicaly declares and initialises a variable
71     // that is in scope for the next statement only
72     // works only for stuff that can be assigned 0 and converts to false
73     // (note: works great for pointers)
74     // most ugly macro I ever wrote
75 root 1.48 #define statementvar(type, name, value) if (type name = 0) { } else if (((name) = (value)), 1)
76 root 1.26
77 root 1.27 // in range including end
78     #define IN_RANGE_INC(val,beg,end) \
79     ((unsigned int)(val) - (unsigned int)(beg) <= (unsigned int)(end) - (unsigned int)(beg))
80    
81     // in range excluding end
82     #define IN_RANGE_EXC(val,beg,end) \
83     ((unsigned int)(val) - (unsigned int)(beg) < (unsigned int)(end) - (unsigned int)(beg))
84    
85 root 1.31 void fork_abort (const char *msg);
86    
87 root 1.35 // rationale for using (U) not (T) is to reduce signed/unsigned issues,
88     // as a is often a constant while b is the variable. it is still a bug, though.
89     template<typename T, typename U> static inline T min (T a, U b) { return (U)a < b ? (U)a : b; }
90     template<typename T, typename U> static inline T max (T a, U b) { return (U)a > b ? (U)a : b; }
91     template<typename T, typename U, typename V> static inline T clamp (T v, U a, V b) { return v < (T)a ? (T)a : v >(T)b ? (T)b : v; }
92 root 1.32
93     template<typename T, typename U> static inline void swap (T& a, U& b) { T t=a; a=(T)b; b=(U)t; }
94    
95 root 1.44 template<typename T>
96     static inline T
97     lerp (T val, T min_in, T max_in, T min_out, T max_out)
98     {
99     return (val - min_in) * (max_out - min_out) / (max_in - min_in) + min_out;
100     }
101    
102 root 1.37 // lots of stuff taken from FXT
103    
104     /* Rotate right. This is used in various places for checksumming */
105 root 1.38 //TODO: that sucks, use a better checksum algo
106 root 1.37 static inline uint32_t
107 root 1.38 rotate_right (uint32_t c, uint32_t count = 1)
108 root 1.37 {
109 root 1.38 return (c << (32 - count)) | (c >> count);
110     }
111    
112     static inline uint32_t
113     rotate_left (uint32_t c, uint32_t count = 1)
114     {
115     return (c >> (32 - count)) | (c << count);
116 root 1.37 }
117    
118     // Return abs(a-b)
119     // Both a and b must not have the most significant bit set
120     static inline uint32_t
121     upos_abs_diff (uint32_t a, uint32_t b)
122     {
123     long d1 = b - a;
124     long d2 = (d1 & (d1 >> 31)) << 1;
125    
126     return d1 - d2; // == (b - d) - (a + d);
127     }
128    
129     // Both a and b must not have the most significant bit set
130     static inline uint32_t
131     upos_min (uint32_t a, uint32_t b)
132     {
133     int32_t d = b - a;
134     d &= d >> 31;
135     return a + d;
136     }
137    
138     // Both a and b must not have the most significant bit set
139     static inline uint32_t
140     upos_max (uint32_t a, uint32_t b)
141     {
142     int32_t d = b - a;
143     d &= d >> 31;
144     return b - d;
145     }
146    
147 root 1.28 // this is much faster than crossfires original algorithm
148     // on modern cpus
149     inline int
150     isqrt (int n)
151     {
152     return (int)sqrtf ((float)n);
153     }
154    
155     // this is only twice as fast as naive sqrtf (dx*dy+dy*dy)
156     #if 0
157     // and has a max. error of 6 in the range -100..+100.
158     #else
159     // and has a max. error of 9 in the range -100..+100.
160     #endif
161     inline int
162     idistance (int dx, int dy)
163     {
164     unsigned int dx_ = abs (dx);
165     unsigned int dy_ = abs (dy);
166    
167     #if 0
168     return dx_ > dy_
169     ? (dx_ * 61685 + dy_ * 26870) >> 16
170     : (dy_ * 61685 + dx_ * 26870) >> 16;
171     #else
172 root 1.30 return dx_ + dy_ - min (dx_, dy_) * 5 / 8;
173 root 1.28 #endif
174     }
175    
176 root 1.29 /*
177     * absdir(int): Returns a number between 1 and 8, which represent
178     * the "absolute" direction of a number (it actually takes care of
179     * "overflow" in previous calculations of a direction).
180     */
181     inline int
182     absdir (int d)
183     {
184     return ((d - 1) & 7) + 1;
185     }
186 root 1.28
187 root 1.57 extern size_t slice_alloc; // statistics
188    
189 root 1.1 // makes dynamically allocated objects zero-initialised
190     struct zero_initialised
191     {
192 root 1.11 void *operator new (size_t s, void *p)
193     {
194     memset (p, 0, s);
195     return p;
196     }
197    
198     void *operator new (size_t s)
199     {
200 root 1.57 slice_alloc += s;
201 root 1.11 return g_slice_alloc0 (s);
202     }
203    
204     void *operator new[] (size_t s)
205     {
206 root 1.57 slice_alloc += s;
207 root 1.11 return g_slice_alloc0 (s);
208     }
209    
210     void operator delete (void *p, size_t s)
211     {
212 root 1.57 slice_alloc -= s;
213 root 1.11 g_slice_free1 (s, p);
214     }
215    
216     void operator delete[] (void *p, size_t s)
217     {
218 root 1.57 slice_alloc -= s;
219 root 1.11 g_slice_free1 (s, p);
220     }
221     };
222    
223 root 1.20 void *salloc_ (int n) throw (std::bad_alloc);
224     void *salloc_ (int n, void *src) throw (std::bad_alloc);
225    
226 root 1.12 // strictly the same as g_slice_alloc, but never returns 0
227 root 1.20 template<typename T>
228     inline T *salloc (int n = 1) throw (std::bad_alloc) { return (T *)salloc_ (n * sizeof (T)); }
229    
230 root 1.17 // also copies src into the new area, like "memdup"
231 root 1.18 // if src is 0, clears the memory
232     template<typename T>
233 root 1.20 inline T *salloc (int n, T *src) throw (std::bad_alloc) { return (T *)salloc_ (n * sizeof (T), (void *)src); }
234 root 1.18
235 root 1.21 // clears the memory
236     template<typename T>
237     inline T *salloc0(int n = 1) throw (std::bad_alloc) { return (T *)salloc_ (n * sizeof (T), 0); }
238    
239 root 1.12 // for symmetry
240 root 1.18 template<typename T>
241 root 1.20 inline void sfree (T *ptr, int n = 1) throw ()
242 root 1.12 {
243 root 1.36 #ifdef PREFER_MALLOC
244     free (ptr);
245     #else
246 root 1.57 slice_alloc -= n * sizeof (T);
247 root 1.20 g_slice_free1 (n * sizeof (T), (void *)ptr);
248 root 1.36 #endif
249 root 1.12 }
250 root 1.11
251     // a STL-compatible allocator that uses g_slice
252     // boy, this is verbose
253     template<typename Tp>
254     struct slice_allocator
255     {
256     typedef size_t size_type;
257     typedef ptrdiff_t difference_type;
258     typedef Tp *pointer;
259     typedef const Tp *const_pointer;
260     typedef Tp &reference;
261     typedef const Tp &const_reference;
262     typedef Tp value_type;
263    
264     template <class U>
265     struct rebind
266     {
267     typedef slice_allocator<U> other;
268     };
269    
270     slice_allocator () throw () { }
271     slice_allocator (const slice_allocator &o) throw () { }
272     template<typename Tp2>
273     slice_allocator (const slice_allocator<Tp2> &) throw () { }
274    
275     ~slice_allocator () { }
276    
277     pointer address (reference x) const { return &x; }
278     const_pointer address (const_reference x) const { return &x; }
279    
280     pointer allocate (size_type n, const_pointer = 0)
281     {
282 root 1.18 return salloc<Tp> (n);
283 root 1.11 }
284    
285     void deallocate (pointer p, size_type n)
286     {
287 root 1.19 sfree<Tp> (p, n);
288 root 1.11 }
289    
290     size_type max_size ()const throw ()
291     {
292     return size_t (-1) / sizeof (Tp);
293     }
294    
295     void construct (pointer p, const Tp &val)
296     {
297     ::new (p) Tp (val);
298     }
299    
300     void destroy (pointer p)
301     {
302     p->~Tp ();
303     }
304 root 1.1 };
305    
306 root 1.32 // P. L'Ecuyer, “Maximally Equidistributed Combined Tausworthe Generators”, Mathematics of Computation, 65, 213 (1996), 203–213.
307     // http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme.ps
308     // http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme2.ps
309     struct tausworthe_random_generator
310     {
311 root 1.34 // generator
312 root 1.32 uint32_t state [4];
313    
314 root 1.34 void operator =(const tausworthe_random_generator &src)
315     {
316     state [0] = src.state [0];
317     state [1] = src.state [1];
318     state [2] = src.state [2];
319     state [3] = src.state [3];
320     }
321    
322     void seed (uint32_t seed);
323 root 1.32 uint32_t next ();
324    
325 root 1.34 // uniform distribution
326 root 1.42 uint32_t operator ()(uint32_t num)
327 root 1.32 {
328 root 1.42 return is_constant (num)
329     ? (next () * (uint64_t)num) >> 32U
330     : get_range (num);
331 root 1.32 }
332    
333     // return a number within (min .. max)
334     int operator () (int r_min, int r_max)
335     {
336 root 1.42 return is_constant (r_min) && is_constant (r_max) && r_min <= r_max
337     ? r_min + operator ()(r_max - r_min + 1)
338 root 1.34 : get_range (r_min, r_max);
339 root 1.32 }
340    
341     double operator ()()
342     {
343 root 1.34 return this->next () / (double)0xFFFFFFFFU;
344 root 1.32 }
345 root 1.34
346     protected:
347     uint32_t get_range (uint32_t r_max);
348     int get_range (int r_min, int r_max);
349 root 1.32 };
350    
351     typedef tausworthe_random_generator rand_gen;
352    
353     extern rand_gen rndm;
354    
355 root 1.54 INTERFACE_CLASS (attachable)
356     struct refcnt_base
357     {
358     typedef int refcnt_t;
359     mutable refcnt_t ACC (RW, refcnt);
360    
361     MTH void refcnt_inc () const { ++refcnt; }
362     MTH void refcnt_dec () const { --refcnt; }
363    
364     refcnt_base () : refcnt (0) { }
365     };
366    
367 root 1.56 // to avoid branches with more advanced compilers
368 root 1.54 extern refcnt_base::refcnt_t refcnt_dummy;
369    
370 root 1.7 template<class T>
371     struct refptr
372     {
373 root 1.54 // p if not null
374     refcnt_base::refcnt_t *refcnt_ref () { return p ? &p->refcnt : &refcnt_dummy; }
375    
376     void refcnt_dec ()
377     {
378     if (!is_constant (p))
379     --*refcnt_ref ();
380     else if (p)
381     --p->refcnt;
382     }
383    
384     void refcnt_inc ()
385     {
386     if (!is_constant (p))
387     ++*refcnt_ref ();
388     else if (p)
389     ++p->refcnt;
390     }
391    
392 root 1.7 T *p;
393    
394     refptr () : p(0) { }
395 root 1.54 refptr (const refptr<T> &p) : p(p.p) { refcnt_inc (); }
396     refptr (T *p) : p(p) { refcnt_inc (); }
397     ~refptr () { refcnt_dec (); }
398 root 1.7
399     const refptr<T> &operator =(T *o)
400     {
401 root 1.54 // if decrementing ever destroys we need to reverse the order here
402     refcnt_dec ();
403 root 1.7 p = o;
404 root 1.54 refcnt_inc ();
405 root 1.7 return *this;
406     }
407    
408 root 1.54 const refptr<T> &operator =(const refptr<T> &o)
409 root 1.7 {
410     *this = o.p;
411     return *this;
412     }
413    
414     T &operator * () const { return *p; }
415 root 1.54 T *operator ->() const { return p; }
416 root 1.7
417     operator T *() const { return p; }
418     };
419    
420 root 1.24 typedef refptr<maptile> maptile_ptr;
421 root 1.22 typedef refptr<object> object_ptr;
422     typedef refptr<archetype> arch_ptr;
423 root 1.24 typedef refptr<client> client_ptr;
424     typedef refptr<player> player_ptr;
425 root 1.22
426 root 1.4 struct str_hash
427     {
428     std::size_t operator ()(const char *s) const
429     {
430     unsigned long hash = 0;
431    
432     /* use the one-at-a-time hash function, which supposedly is
433     * better than the djb2-like one used by perl5.005, but
434     * certainly is better then the bug used here before.
435     * see http://burtleburtle.net/bob/hash/doobs.html
436     */
437     while (*s)
438     {
439     hash += *s++;
440     hash += hash << 10;
441     hash ^= hash >> 6;
442     }
443    
444     hash += hash << 3;
445     hash ^= hash >> 11;
446     hash += hash << 15;
447    
448     return hash;
449     }
450     };
451    
452     struct str_equal
453     {
454     bool operator ()(const char *a, const char *b) const
455     {
456     return !strcmp (a, b);
457     }
458     };
459    
460 root 1.49 // Mostly the same as std::vector, but insert/erase can reorder
461 root 1.52 // the elements, making append(=insert)/remove O(1) instead of O(n).
462 root 1.49 //
463 root 1.52 // NOTE: only some forms of erase are available
464 root 1.26 template<class T>
465     struct unordered_vector : std::vector<T, slice_allocator<T> >
466 root 1.6 {
467 root 1.11 typedef typename unordered_vector::iterator iterator;
468 root 1.6
469     void erase (unsigned int pos)
470     {
471     if (pos < this->size () - 1)
472     (*this)[pos] = (*this)[this->size () - 1];
473    
474     this->pop_back ();
475     }
476    
477     void erase (iterator i)
478     {
479     erase ((unsigned int )(i - this->begin ()));
480     }
481     };
482    
483 root 1.49 // This container blends advantages of linked lists
484     // (efficiency) with vectors (random access) by
485     // by using an unordered vector and storing the vector
486     // index inside the object.
487     //
488     // + memory-efficient on most 64 bit archs
489     // + O(1) insert/remove
490     // + free unique (but varying) id for inserted objects
491     // + cache-friendly iteration
492     // - only works for pointers to structs
493     //
494     // NOTE: only some forms of erase/insert are available
495 root 1.50 typedef int object_vector_index;
496    
497     template<class T, object_vector_index T::*indexmember>
498 root 1.26 struct object_vector : std::vector<T *, slice_allocator<T *> >
499     {
500 root 1.48 typedef typename object_vector::iterator iterator;
501    
502     bool contains (const T *obj) const
503     {
504 root 1.50 return obj->*indexmember;
505 root 1.48 }
506    
507     iterator find (const T *obj)
508     {
509 root 1.50 return obj->*indexmember
510     ? this->begin () + obj->*indexmember - 1
511 root 1.48 : this->end ();
512     }
513    
514 root 1.53 void push_back (T *obj)
515     {
516     std::vector<T *, slice_allocator<T *> >::push_back (obj);
517     obj->*indexmember = this->size ();
518     }
519    
520 root 1.26 void insert (T *obj)
521     {
522     push_back (obj);
523     }
524    
525     void insert (T &obj)
526     {
527     insert (&obj);
528     }
529    
530     void erase (T *obj)
531     {
532 root 1.50 unsigned int pos = obj->*indexmember;
533     obj->*indexmember = 0;
534 root 1.26
535     if (pos < this->size ())
536     {
537     (*this)[pos - 1] = (*this)[this->size () - 1];
538 root 1.50 (*this)[pos - 1]->*indexmember = pos;
539 root 1.26 }
540    
541     this->pop_back ();
542     }
543    
544     void erase (T &obj)
545     {
546 root 1.50 erase (&obj);
547 root 1.26 }
548     };
549    
550 root 1.10 // basically does what strncpy should do, but appends "..." to strings exceeding length
551     void assign (char *dst, const char *src, int maxlen);
552    
553     // type-safe version of assign
554 root 1.9 template<int N>
555     inline void assign (char (&dst)[N], const char *src)
556     {
557 root 1.10 assign ((char *)&dst, src, N);
558 root 1.9 }
559    
560 root 1.17 typedef double tstamp;
561    
562 root 1.59 // return current time as timestamp
563 root 1.17 tstamp now ();
564    
565 root 1.25 int similar_direction (int a, int b);
566    
567 root 1.55 // like sprintf, but returns a "static" buffer
568     const char *format (const char *format, ...);
569 root 1.43
570 root 1.1 #endif
571