ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/include/util.h
Revision: 1.50
Committed: Sun Jun 24 00:33:54 2007 UTC (16 years, 11 months ago) by root
Content type: text/plain
Branch: MAIN
Changes since 1.49: +11 -9 lines
Log Message:
- pippijn unknowingly inspired the idea of documenting the
  type of the objetc_vector_index explicitly.
- pippijn spotted a typoe, to, go figure!

File Contents

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