8249f022d32cb40754bcd32e9d4e627b38558249
[opencv] / cxcore / include / cxtypes.h
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
5 //  By downloading, copying, installing or using the software you agree to this license.
6 //  If you do not agree to this license, do not download, install,
7 //  copy or use the software.
8 //
9 //
10 //                        Intel License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright (C) 2000, Intel Corporation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
15 //
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
18 //
19 //   * Redistribution's of source code must retain the above copyright notice,
20 //     this list of conditions and the following disclaimer.
21 //
22 //   * Redistribution's in binary form must reproduce the above copyright notice,
23 //     this list of conditions and the following disclaimer in the documentation
24 //     and/or other materials provided with the distribution.
25 //
26 //   * The name of Intel Corporation may not be used to endorse or promote products
27 //     derived from this software without specific prior written permission.
28 //
29 // This software is provided by the copyright holders and contributors "as is" and
30 // any express or implied warranties, including, but not limited to, the implied
31 // warranties of merchantability and fitness for a particular purpose are disclaimed.
32 // In no event shall the Intel Corporation or contributors be liable for any direct,
33 // indirect, incidental, special, exemplary, or consequential damages
34 // (including, but not limited to, procurement of substitute goods or services;
35 // loss of use, data, or profits; or business interruption) however caused
36 // and on any theory of liability, whether in contract, strict liability,
37 // or tort (including negligence or otherwise) arising in any way out of
38 // the use of this software, even if advised of the possibility of such damage.
39 //
40 //M*/
41
42 #ifndef _CXCORE_TYPES_H_
43 #define _CXCORE_TYPES_H_
44
45 #if !defined _CRT_SECURE_NO_DEPRECATE && _MSC_VER > 1300
46 #define _CRT_SECURE_NO_DEPRECATE /* to avoid multiple Visual Studio 2005 warnings */
47 #endif
48
49 #ifndef SKIP_INCLUDES
50   #include <assert.h>
51   #include <stdlib.h>
52   #include <string.h>
53   #include <float.h>
54
55   #if defined __ICL
56     #define CV_ICC   __ICL
57   #elif defined __ICC
58     #define CV_ICC   __ICC
59   #elif defined __ECL
60     #define CV_ICC   __ECL
61   #elif defined __ECC
62     #define CV_ICC   __ECC
63   #endif
64
65   #if defined WIN64 && defined EM64T && (defined _MSC_VER || defined CV_ICC) \
66       || defined __SSE2__ || defined _MM_SHUFFLE2
67     #include <emmintrin.h>
68     #define CV_SSE2 1
69   #else
70     #define CV_SSE2 0
71   #endif
72
73   #if defined __BORLANDC__
74     #include <fastmath.h>
75   #elif defined WIN64 && !defined EM64T && defined CV_ICC
76     #include <mathimf.h>
77   #else
78     #include <math.h>
79   #endif
80
81   #ifdef HAVE_IPL
82       #ifndef __IPL_H__
83           #if defined WIN32 || defined WIN64
84               #include <ipl.h>
85           #else
86               #include <ipl/ipl.h>
87           #endif
88       #endif
89   #elif defined __IPL_H__
90       #define HAVE_IPL
91   #endif
92 #endif // SKIP_INCLUDES
93
94 #if defined WIN32 || defined WIN64
95     #define CV_CDECL __cdecl
96     #define CV_STDCALL __stdcall
97 #else
98     #define CV_CDECL
99     #define CV_STDCALL
100 #endif
101
102 #ifndef CV_EXTERN_C
103     #ifdef __cplusplus
104         #define CV_EXTERN_C extern "C"
105         #define CV_DEFAULT(val) = val
106     #else
107         #define CV_EXTERN_C
108         #define CV_DEFAULT(val)
109     #endif
110 #endif
111
112 #ifndef CV_EXTERN_C_FUNCPTR
113     #ifdef __cplusplus
114         #define CV_EXTERN_C_FUNCPTR(x) extern "C" { typedef x; }
115     #else
116         #define CV_EXTERN_C_FUNCPTR(x) typedef x
117     #endif
118 #endif
119
120 #ifndef CV_INLINE
121 #if defined __cplusplus
122     #define CV_INLINE inline
123 #elif (defined WIN32 || defined WIN64) && !defined __GNUC__
124     #define CV_INLINE __inline
125 #else
126     #define CV_INLINE static
127 #endif
128 #endif /* CV_INLINE */
129
130 #if (defined WIN32 || defined WIN64) && defined CVAPI_EXPORTS
131     #define CV_EXPORTS __declspec(dllexport)
132 #else
133     #define CV_EXPORTS
134 #endif
135
136 #ifndef CVAPI
137     #define CVAPI(rettype) CV_EXTERN_C CV_EXPORTS rettype CV_CDECL
138 #endif
139
140 #if defined _MSC_VER || defined __BORLANDC__
141 typedef __int64 int64;
142 typedef unsigned __int64 uint64;
143 #else
144 typedef long long int64;
145 typedef unsigned long long uint64;
146 #endif
147
148 #ifndef HAVE_IPL
149 typedef unsigned char uchar;
150 typedef unsigned short ushort;
151 #endif
152
153 /* CvArr* is used to pass arbitrary array-like data structures
154    into the functions where the particular
155    array type is recognized at runtime */
156 typedef void CvArr;
157
158 typedef union Cv32suf
159 {
160     int i;
161     unsigned u;
162     float f;
163 }
164 Cv32suf;
165
166 typedef union Cv64suf
167 {
168     int64 i;
169     uint64 u;
170     double f;
171 }
172 Cv64suf;
173
174 /****************************************************************************************\
175 *                             Common macros and inline functions                         *
176 \****************************************************************************************/
177
178 #define CV_PI   3.1415926535897932384626433832795
179 #define CV_LOG2 0.69314718055994530941723212145818
180
181 #define CV_SWAP(a,b,t) ((t) = (a), (a) = (b), (b) = (t))
182
183 #ifndef MIN
184 #define MIN(a,b)  ((a) > (b) ? (b) : (a))
185 #endif
186
187 #ifndef MAX
188 #define MAX(a,b)  ((a) < (b) ? (b) : (a))
189 #endif
190
191 /* min & max without jumps */
192 #define  CV_IMIN(a, b)  ((a) ^ (((a)^(b)) & (((a) < (b)) - 1)))
193
194 #define  CV_IMAX(a, b)  ((a) ^ (((a)^(b)) & (((a) > (b)) - 1)))
195
196 /* absolute value without jumps */
197 #ifndef __cplusplus
198 #define  CV_IABS(a)     (((a) ^ ((a) < 0 ? -1 : 0)) - ((a) < 0 ? -1 : 0))
199 #else
200 #define  CV_IABS(a)     abs(a)
201 #endif
202 #define  CV_CMP(a,b)    (((a) > (b)) - ((a) < (b)))
203 #define  CV_SIGN(a)     CV_CMP((a),0)
204
205 CV_INLINE  int  cvRound( double value )
206 {
207 #if CV_SSE2
208     __m128d t = _mm_load_sd( &value );
209     return _mm_cvtsd_si32(t);
210 #elif defined WIN32 && !defined WIN64 && defined _MSC_VER
211     int t;
212     __asm
213     {
214         fld value;
215         fistp t;
216     }
217     return t;
218 #elif (defined HAVE_LRINT) || (defined WIN64 && !defined EM64T && defined CV_ICC)
219     return (int)lrint(value);
220 #else
221     /*
222      the algorithm was taken from Agner Fog's optimization guide
223      at http://www.agner.org/assem
224      */
225     Cv64suf temp;
226     temp.f = value + 6755399441055744.0;
227     return (int)temp.u;
228 #endif
229 }
230
231
232 CV_INLINE  int  cvFloor( double value )
233 {
234 #if CV_SSE2
235     __m128d t = _mm_load_sd( &value );
236     int i = _mm_cvtsd_si32(t);
237     return i - _mm_movemask_pd(_mm_cmplt_sd(t,_mm_cvtsi32_sd(t,i)));
238 #else
239     int temp = cvRound(value);
240     Cv32suf diff;
241     diff.f = (float)(value - temp);
242     return temp - (diff.i < 0);
243 #endif
244 }
245
246
247 CV_INLINE  int  cvCeil( double value )
248 {
249 #if CV_SSE2
250     __m128d t = _mm_load_sd( &value );
251     int i = _mm_cvtsd_si32(t);
252     return i + _mm_movemask_pd(_mm_cmplt_sd(_mm_cvtsi32_sd(t,i),t));
253 #else
254     int temp = cvRound(value);
255     Cv32suf diff;
256     diff.f = (float)(temp - value);
257     return temp + (diff.i < 0);
258 #endif
259 }
260
261 #define cvInvSqrt(value) ((float)(1./sqrt(value)))
262 #define cvSqrt(value)  ((float)sqrt(value))
263
264 CV_INLINE int cvIsNaN( double value )
265 {
266 #if 1/*defined _MSC_VER || defined __BORLANDC__
267     return _isnan(value);
268 #elif defined __GNUC__
269     return isnan(value);
270 #else*/
271     Cv64suf ieee754;
272     ieee754.f = value;
273     return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) +
274            ((unsigned)ieee754.u != 0) > 0x7ff00000;
275 #endif
276 }
277
278
279 CV_INLINE int cvIsInf( double value )
280 {
281 #if 1/*defined _MSC_VER || defined __BORLANDC__
282     return !_finite(value);
283 #elif defined __GNUC__
284     return isinf(value);
285 #else*/
286     Cv64suf ieee754;
287     ieee754.f = value;
288     return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) == 0x7ff00000 &&
289            (unsigned)ieee754.u == 0;
290 #endif
291 }
292
293
294 /*************** Random number generation *******************/
295
296 typedef uint64 CvRNG;
297
298 CV_INLINE CvRNG cvRNG( int64 seed CV_DEFAULT(-1))
299 {
300     CvRNG rng = seed ? (uint64)seed : (uint64)(int64)-1;
301     return rng;
302 }
303
304 /* returns random 32-bit unsigned integer */
305 CV_INLINE unsigned cvRandInt( CvRNG* rng )
306 {
307     uint64 temp = *rng;
308     temp = (uint64)(unsigned)temp*1554115554 + (temp >> 32);
309     *rng = temp;
310     return (unsigned)temp;
311 }
312
313 /* returns random floating-point number between 0 and 1 */
314 CV_INLINE double cvRandReal( CvRNG* rng )
315 {
316     return cvRandInt(rng)*2.3283064365386962890625e-10 /* 2^-32 */;
317 }
318
319 /****************************************************************************************\
320 *                                  Image type (IplImage)                                 *
321 \****************************************************************************************/
322
323 #ifndef HAVE_IPL
324
325 /*
326  * The following definitions (until #endif)
327  * is an extract from IPL headers.
328  * Copyright (c) 1995 Intel Corporation.
329  */
330 #define IPL_DEPTH_SIGN 0x80000000
331
332 #define IPL_DEPTH_1U     1
333 #define IPL_DEPTH_8U     8
334 #define IPL_DEPTH_16U   16
335 #define IPL_DEPTH_32F   32
336
337 #define IPL_DEPTH_8S  (IPL_DEPTH_SIGN| 8)
338 #define IPL_DEPTH_16S (IPL_DEPTH_SIGN|16)
339 #define IPL_DEPTH_32S (IPL_DEPTH_SIGN|32)
340
341 #define IPL_DATA_ORDER_PIXEL  0
342 #define IPL_DATA_ORDER_PLANE  1
343
344 #define IPL_ORIGIN_TL 0
345 #define IPL_ORIGIN_BL 1
346
347 #define IPL_ALIGN_4BYTES   4
348 #define IPL_ALIGN_8BYTES   8
349 #define IPL_ALIGN_16BYTES 16
350 #define IPL_ALIGN_32BYTES 32
351
352 #define IPL_ALIGN_DWORD   IPL_ALIGN_4BYTES
353 #define IPL_ALIGN_QWORD   IPL_ALIGN_8BYTES
354
355 #define IPL_BORDER_CONSTANT   0
356 #define IPL_BORDER_REPLICATE  1
357 #define IPL_BORDER_REFLECT    2
358 #define IPL_BORDER_WRAP       3
359
360 typedef struct _IplImage
361 {
362     int  nSize;         /* sizeof(IplImage) */
363     int  ID;            /* version (=0)*/
364     int  nChannels;     /* Most of OpenCV functions support 1,2,3 or 4 channels */
365     int  alphaChannel;  /* ignored by OpenCV */
366     int  depth;         /* pixel depth in bits: IPL_DEPTH_8U, IPL_DEPTH_8S, IPL_DEPTH_16S,
367                            IPL_DEPTH_32S, IPL_DEPTH_32F and IPL_DEPTH_64F are supported */
368     char colorModel[4]; /* ignored by OpenCV */
369     char channelSeq[4]; /* ditto */
370     int  dataOrder;     /* 0 - interleaved color channels, 1 - separate color channels.
371                            cvCreateImage can only create interleaved images */
372     int  origin;        /* 0 - top-left origin,
373                            1 - bottom-left origin (Windows bitmaps style) */
374     int  align;         /* Alignment of image rows (4 or 8).
375                            OpenCV ignores it and uses widthStep instead */
376     int  width;         /* image width in pixels */
377     int  height;        /* image height in pixels */
378     struct _IplROI *roi;/* image ROI. if NULL, the whole image is selected */
379     struct _IplImage *maskROI; /* must be NULL */
380     void  *imageId;     /* ditto */
381     struct _IplTileInfo *tileInfo; /* ditto */
382     int  imageSize;     /* image data size in bytes
383                            (==image->height*image->widthStep
384                            in case of interleaved data)*/
385     char *imageData;  /* pointer to aligned image data */
386     int  widthStep;   /* size of aligned image row in bytes */
387     int  BorderMode[4]; /* ignored by OpenCV */
388     int  BorderConst[4]; /* ditto */
389     char *imageDataOrigin; /* pointer to very origin of image data
390                               (not necessarily aligned) -
391                               needed for correct deallocation */
392 }
393 IplImage;
394
395 typedef struct _IplTileInfo IplTileInfo;
396
397 typedef struct _IplROI
398 {
399     int  coi; /* 0 - no COI (all channels are selected), 1 - 0th channel is selected ...*/
400     int  xOffset;
401     int  yOffset;
402     int  width;
403     int  height;
404 }
405 IplROI;
406
407 typedef struct _IplConvKernel
408 {
409     int  nCols;
410     int  nRows;
411     int  anchorX;
412     int  anchorY;
413     int *values;
414     int  nShiftR;
415 }
416 IplConvKernel;
417
418 typedef struct _IplConvKernelFP
419 {
420     int  nCols;
421     int  nRows;
422     int  anchorX;
423     int  anchorY;
424     float *values;
425 }
426 IplConvKernelFP;
427
428 #define IPL_IMAGE_HEADER 1
429 #define IPL_IMAGE_DATA   2
430 #define IPL_IMAGE_ROI    4
431
432 #endif/*HAVE_IPL*/
433
434 /* extra border mode */
435 #define IPL_BORDER_REFLECT_101    4
436
437 #define IPL_IMAGE_MAGIC_VAL  ((int)sizeof(IplImage))
438 #define CV_TYPE_NAME_IMAGE "opencv-image"
439
440 #define CV_IS_IMAGE_HDR(img) \
441     ((img) != NULL && ((const IplImage*)(img))->nSize == sizeof(IplImage))
442
443 #define CV_IS_IMAGE(img) \
444     (CV_IS_IMAGE_HDR(img) && ((IplImage*)img)->imageData != NULL)
445
446 /* for storing double-precision
447    floating point data in IplImage's */
448 #define IPL_DEPTH_64F  64
449
450 /* get reference to pixel at (col,row),
451    for multi-channel images (col) should be multiplied by number of channels */
452 #define CV_IMAGE_ELEM( image, elemtype, row, col )       \
453     (((elemtype*)((image)->imageData + (image)->widthStep*(row)))[(col)])
454
455 /****************************************************************************************\
456 *                                  Matrix type (CvMat)                                   *
457 \****************************************************************************************/
458
459 #define CV_CN_MAX     64
460 #define CV_CN_SHIFT   3
461 #define CV_DEPTH_MAX  (1 << CV_CN_SHIFT)
462
463 #define CV_8U   0
464 #define CV_8S   1
465 #define CV_16U  2
466 #define CV_16S  3
467 #define CV_32S  4
468 #define CV_32F  5
469 #define CV_64F  6
470 #define CV_USRTYPE1 7
471
472 #define CV_MAKETYPE(depth,cn) ((depth) + (((cn)-1) << CV_CN_SHIFT))
473 #define CV_MAKE_TYPE CV_MAKETYPE
474
475 #define CV_8UC1 CV_MAKETYPE(CV_8U,1)
476 #define CV_8UC2 CV_MAKETYPE(CV_8U,2)
477 #define CV_8UC3 CV_MAKETYPE(CV_8U,3)
478 #define CV_8UC4 CV_MAKETYPE(CV_8U,4)
479 #define CV_8UC(n) CV_MAKETYPE(CV_8U,(n))
480
481 #define CV_8SC1 CV_MAKETYPE(CV_8S,1)
482 #define CV_8SC2 CV_MAKETYPE(CV_8S,2)
483 #define CV_8SC3 CV_MAKETYPE(CV_8S,3)
484 #define CV_8SC4 CV_MAKETYPE(CV_8S,4)
485 #define CV_8SC(n) CV_MAKETYPE(CV_8S,(n))
486
487 #define CV_16UC1 CV_MAKETYPE(CV_16U,1)
488 #define CV_16UC2 CV_MAKETYPE(CV_16U,2)
489 #define CV_16UC3 CV_MAKETYPE(CV_16U,3)
490 #define CV_16UC4 CV_MAKETYPE(CV_16U,4)
491 #define CV_16UC(n) CV_MAKETYPE(CV_16U,(n))
492
493 #define CV_16SC1 CV_MAKETYPE(CV_16S,1)
494 #define CV_16SC2 CV_MAKETYPE(CV_16S,2)
495 #define CV_16SC3 CV_MAKETYPE(CV_16S,3)
496 #define CV_16SC4 CV_MAKETYPE(CV_16S,4)
497 #define CV_16SC(n) CV_MAKETYPE(CV_16S,(n))
498
499 #define CV_32SC1 CV_MAKETYPE(CV_32S,1)
500 #define CV_32SC2 CV_MAKETYPE(CV_32S,2)
501 #define CV_32SC3 CV_MAKETYPE(CV_32S,3)
502 #define CV_32SC4 CV_MAKETYPE(CV_32S,4)
503 #define CV_32SC(n) CV_MAKETYPE(CV_32S,(n))
504
505 #define CV_32FC1 CV_MAKETYPE(CV_32F,1)
506 #define CV_32FC2 CV_MAKETYPE(CV_32F,2)
507 #define CV_32FC3 CV_MAKETYPE(CV_32F,3)
508 #define CV_32FC4 CV_MAKETYPE(CV_32F,4)
509 #define CV_32FC(n) CV_MAKETYPE(CV_32F,(n))
510
511 #define CV_64FC1 CV_MAKETYPE(CV_64F,1)
512 #define CV_64FC2 CV_MAKETYPE(CV_64F,2)
513 #define CV_64FC3 CV_MAKETYPE(CV_64F,3)
514 #define CV_64FC4 CV_MAKETYPE(CV_64F,4)
515 #define CV_64FC(n) CV_MAKETYPE(CV_64F,(n))
516
517 #define CV_AUTO_STEP  0x7fffffff
518 #define CV_WHOLE_ARR  cvSlice( 0, 0x3fffffff )
519
520 #define CV_MAT_CN_MASK          ((CV_CN_MAX - 1) << CV_CN_SHIFT)
521 #define CV_MAT_CN(flags)        ((((flags) & CV_MAT_CN_MASK) >> CV_CN_SHIFT) + 1)
522 #define CV_MAT_DEPTH_MASK       (CV_DEPTH_MAX - 1)
523 #define CV_MAT_DEPTH(flags)     ((flags) & CV_MAT_DEPTH_MASK)
524 #define CV_MAT_TYPE_MASK        (CV_DEPTH_MAX*CV_CN_MAX - 1)
525 #define CV_MAT_TYPE(flags)      ((flags) & CV_MAT_TYPE_MASK)
526 #define CV_MAT_CONT_FLAG_SHIFT  14
527 #define CV_MAT_CONT_FLAG        (1 << CV_MAT_CONT_FLAG_SHIFT)
528 #define CV_IS_MAT_CONT(flags)   ((flags) & CV_MAT_CONT_FLAG)
529 #define CV_IS_CONT_MAT          CV_IS_MAT_CONT
530 #define CV_MAT_TEMP_FLAG_SHIFT  15
531 #define CV_MAT_TEMP_FLAG        (1 << CV_MAT_TEMP_FLAG_SHIFT)
532 #define CV_IS_TEMP_MAT(flags)   ((flags) & CV_MAT_TEMP_FLAG)
533
534 #define CV_MAGIC_MASK       0xFFFF0000
535 #define CV_MAT_MAGIC_VAL    0x42420000
536 #define CV_TYPE_NAME_MAT    "opencv-matrix"
537
538 typedef struct CvMat
539 {
540     int type;
541     int step;
542
543     /* for internal use only */
544     int* refcount;
545     int hdr_refcount;
546
547     union
548     {
549         uchar* ptr;
550         short* s;
551         int* i;
552         float* fl;
553         double* db;
554     } data;
555
556 #ifdef __cplusplus
557     union
558     {
559         int rows;
560         int height;
561     };
562
563     union
564     {
565         int cols;
566         int width;
567     };
568 #else
569     int rows;
570     int cols;
571 #endif
572
573 }
574 CvMat;
575
576
577 #define CV_IS_MAT_HDR(mat) \
578     ((mat) != NULL && \
579     (((const CvMat*)(mat))->type & CV_MAGIC_MASK) == CV_MAT_MAGIC_VAL && \
580     ((const CvMat*)(mat))->cols > 0 && ((const CvMat*)(mat))->rows > 0)
581
582 #define CV_IS_MAT(mat) \
583     (CV_IS_MAT_HDR(mat) && ((const CvMat*)(mat))->data.ptr != NULL)
584
585 #define CV_IS_MASK_ARR(mat) \
586     (((mat)->type & (CV_MAT_TYPE_MASK & ~CV_8SC1)) == 0)
587
588 #define CV_ARE_TYPES_EQ(mat1, mat2) \
589     ((((mat1)->type ^ (mat2)->type) & CV_MAT_TYPE_MASK) == 0)
590
591 #define CV_ARE_CNS_EQ(mat1, mat2) \
592     ((((mat1)->type ^ (mat2)->type) & CV_MAT_CN_MASK) == 0)
593
594 #define CV_ARE_DEPTHS_EQ(mat1, mat2) \
595     ((((mat1)->type ^ (mat2)->type) & CV_MAT_DEPTH_MASK) == 0)
596
597 #define CV_ARE_SIZES_EQ(mat1, mat2) \
598     ((mat1)->height == (mat2)->height && (mat1)->width == (mat2)->width)
599
600 #define CV_IS_MAT_CONST(mat)  \
601     (((mat)->height|(mat)->width) == 1)
602
603 /* size of each channel item,
604    0x124489 = 1000 0100 0100 0010 0010 0001 0001 ~ array of sizeof(arr_type_elem) */
605 #define CV_ELEM_SIZE1(type) \
606     ((((sizeof(size_t)<<28)|0x8442211) >> CV_MAT_DEPTH(type)*4) & 15)
607
608 /* 0x3a50 = 11 10 10 01 01 00 00 ~ array of log2(sizeof(arr_type_elem)) */
609 #define CV_ELEM_SIZE(type) \
610     (CV_MAT_CN(type) << ((((sizeof(size_t)/4+1)*16384|0x3a50) >> CV_MAT_DEPTH(type)*2) & 3))
611
612 /* inline constructor. No data is allocated internally!!!
613    (use together with cvCreateData, or use cvCreateMat instead to
614    get a matrix with allocated data) */
615 CV_INLINE CvMat cvMat( int rows, int cols, int type, void* data CV_DEFAULT(NULL))
616 {
617     CvMat m;
618
619     assert( (unsigned)CV_MAT_DEPTH(type) <= CV_64F );
620     type = CV_MAT_TYPE(type);
621     m.type = CV_MAT_MAGIC_VAL | CV_MAT_CONT_FLAG | type;
622     m.cols = cols;
623     m.rows = rows;
624     m.step = rows > 1 ? m.cols*CV_ELEM_SIZE(type) : 0;
625     m.data.ptr = (uchar*)data;
626     m.refcount = NULL;
627     m.hdr_refcount = 0;
628
629     return m;
630 }
631
632
633 #define CV_MAT_ELEM_PTR_FAST( mat, row, col, pix_size )  \
634     (assert( (unsigned)(row) < (unsigned)(mat).rows &&   \
635              (unsigned)(col) < (unsigned)(mat).cols ),   \
636      (mat).data.ptr + (size_t)(mat).step*(row) + (pix_size)*(col))
637
638 #define CV_MAT_ELEM_PTR( mat, row, col )                 \
639     CV_MAT_ELEM_PTR_FAST( mat, row, col, CV_ELEM_SIZE((mat).type) )
640
641 #define CV_MAT_ELEM( mat, elemtype, row, col )           \
642     (*(elemtype*)CV_MAT_ELEM_PTR_FAST( mat, row, col, sizeof(elemtype)))
643
644
645 CV_INLINE  double  cvmGet( const CvMat* mat, int row, int col )
646 {
647     int type;
648
649     type = CV_MAT_TYPE(mat->type);
650     assert( (unsigned)row < (unsigned)mat->rows &&
651             (unsigned)col < (unsigned)mat->cols );
652
653     if( type == CV_32FC1 )
654         return ((float*)(mat->data.ptr + (size_t)mat->step*row))[col];
655     else
656     {
657         assert( type == CV_64FC1 );
658         return ((double*)(mat->data.ptr + (size_t)mat->step*row))[col];
659     }
660 }
661
662
663 CV_INLINE  void  cvmSet( CvMat* mat, int row, int col, double value )
664 {
665     int type;
666     type = CV_MAT_TYPE(mat->type);
667     assert( (unsigned)row < (unsigned)mat->rows &&
668             (unsigned)col < (unsigned)mat->cols );
669
670     if( type == CV_32FC1 )
671         ((float*)(mat->data.ptr + (size_t)mat->step*row))[col] = (float)value;
672     else
673     {
674         assert( type == CV_64FC1 );
675         ((double*)(mat->data.ptr + (size_t)mat->step*row))[col] = (double)value;
676     }
677 }
678
679
680 CV_INLINE int cvCvToIplDepth( int type )
681 {
682     int depth = CV_MAT_DEPTH(type);
683     return CV_ELEM_SIZE1(depth)*8 | (depth == CV_8S || depth == CV_16S ||
684            depth == CV_32S ? IPL_DEPTH_SIGN : 0);
685 }
686
687
688 /****************************************************************************************\
689 *                       Multi-dimensional dense array (CvMatND)                          *
690 \****************************************************************************************/
691
692 #define CV_MATND_MAGIC_VAL    0x42430000
693 #define CV_TYPE_NAME_MATND    "opencv-nd-matrix"
694
695 #define CV_MAX_DIM            32
696 #define CV_MAX_DIM_HEAP       (1 << 16)
697
698 typedef struct CvMatND
699 {
700     int type;
701     int dims;
702
703     int* refcount;
704     int hdr_refcount;
705
706     union
707     {
708         uchar* ptr;
709         float* fl;
710         double* db;
711         int* i;
712         short* s;
713     } data;
714
715     struct
716     {
717         int size;
718         int step;
719     }
720     dim[CV_MAX_DIM];
721 }
722 CvMatND;
723
724 #define CV_IS_MATND_HDR(mat) \
725     ((mat) != NULL && (((const CvMatND*)(mat))->type & CV_MAGIC_MASK) == CV_MATND_MAGIC_VAL)
726
727 #define CV_IS_MATND(mat) \
728     (CV_IS_MATND_HDR(mat) && ((const CvMatND*)(mat))->data.ptr != NULL)
729
730
731 /****************************************************************************************\
732 *                      Multi-dimensional sparse array (CvSparseMat)                      *
733 \****************************************************************************************/
734
735 #define CV_SPARSE_MAT_MAGIC_VAL    0x42440000
736 #define CV_TYPE_NAME_SPARSE_MAT    "opencv-sparse-matrix"
737
738 struct CvSet;
739
740 typedef struct CvSparseMat
741 {
742     int type;
743     int dims;
744     int* refcount;
745     int hdr_refcount;
746
747     struct CvSet* heap;
748     void** hashtable;
749     int hashsize;
750     int valoffset;
751     int idxoffset;
752     int size[CV_MAX_DIM];
753 }
754 CvSparseMat;
755
756 #define CV_IS_SPARSE_MAT_HDR(mat) \
757     ((mat) != NULL && \
758     (((const CvSparseMat*)(mat))->type & CV_MAGIC_MASK) == CV_SPARSE_MAT_MAGIC_VAL)
759
760 #define CV_IS_SPARSE_MAT(mat) \
761     CV_IS_SPARSE_MAT_HDR(mat)
762
763 /**************** iteration through a sparse array *****************/
764
765 typedef struct CvSparseNode
766 {
767     unsigned hashval;
768     struct CvSparseNode* next;
769 }
770 CvSparseNode;
771
772 typedef struct CvSparseMatIterator
773 {
774     CvSparseMat* mat;
775     CvSparseNode* node;
776     int curidx;
777 }
778 CvSparseMatIterator;
779
780 #define CV_NODE_VAL(mat,node)   ((void*)((uchar*)(node) + (mat)->valoffset))
781 #define CV_NODE_IDX(mat,node)   ((int*)((uchar*)(node) + (mat)->idxoffset))
782
783 /****************************************************************************************\
784 *                                         Histogram                                      *
785 \****************************************************************************************/
786
787 typedef int CvHistType;
788
789 #define CV_HIST_MAGIC_VAL     0x42450000
790 #define CV_HIST_UNIFORM_FLAG  (1 << 10)
791
792 /* indicates whether bin ranges are set already or not */
793 #define CV_HIST_RANGES_FLAG   (1 << 11)
794
795 #define CV_HIST_ARRAY         0
796 #define CV_HIST_SPARSE        1
797 #define CV_HIST_TREE          CV_HIST_SPARSE
798
799 /* should be used as a parameter only,
800    it turns to CV_HIST_UNIFORM_FLAG of hist->type */
801 #define CV_HIST_UNIFORM       1
802
803 typedef struct CvHistogram
804 {
805     int     type;
806     CvArr*  bins;
807     float   thresh[CV_MAX_DIM][2]; /* for uniform histograms */
808     float** thresh2; /* for non-uniform histograms */
809     CvMatND mat; /* embedded matrix header for array histograms */
810 }
811 CvHistogram;
812
813 #define CV_IS_HIST( hist ) \
814     ((hist) != NULL  && \
815      (((CvHistogram*)(hist))->type & CV_MAGIC_MASK) == CV_HIST_MAGIC_VAL && \
816      (hist)->bins != NULL)
817
818 #define CV_IS_UNIFORM_HIST( hist ) \
819     (((hist)->type & CV_HIST_UNIFORM_FLAG) != 0)
820
821 #define CV_IS_SPARSE_HIST( hist ) \
822     CV_IS_SPARSE_MAT((hist)->bins)
823
824 #define CV_HIST_HAS_RANGES( hist ) \
825     (((hist)->type & CV_HIST_RANGES_FLAG) != 0)
826
827 /****************************************************************************************\
828 *                      Other supplementary data type definitions                         *
829 \****************************************************************************************/
830
831 /*************************************** CvRect *****************************************/
832
833 typedef struct CvRect
834 {
835     int x;
836     int y;
837     int width;
838     int height;
839 }
840 CvRect;
841
842 CV_INLINE  CvRect  cvRect( int x, int y, int width, int height )
843 {
844     CvRect r;
845
846     r.x = x;
847     r.y = y;
848     r.width = width;
849     r.height = height;
850
851     return r;
852 }
853
854
855 CV_INLINE  IplROI  cvRectToROI( CvRect rect, int coi )
856 {
857     IplROI roi;
858     roi.xOffset = rect.x;
859     roi.yOffset = rect.y;
860     roi.width = rect.width;
861     roi.height = rect.height;
862     roi.coi = coi;
863
864     return roi;
865 }
866
867
868 CV_INLINE  CvRect  cvROIToRect( IplROI roi )
869 {
870     return cvRect( roi.xOffset, roi.yOffset, roi.width, roi.height );
871 }
872
873 /*********************************** CvTermCriteria *************************************/
874
875 #define CV_TERMCRIT_ITER    1
876 #define CV_TERMCRIT_NUMBER  CV_TERMCRIT_ITER
877 #define CV_TERMCRIT_EPS     2
878
879 typedef struct CvTermCriteria
880 {
881     int    type;  /* may be combination of
882                      CV_TERMCRIT_ITER
883                      CV_TERMCRIT_EPS */
884     int    max_iter;
885     double epsilon;
886 }
887 CvTermCriteria;
888
889 CV_INLINE  CvTermCriteria  cvTermCriteria( int type, int max_iter, double epsilon )
890 {
891     CvTermCriteria t;
892
893     t.type = type;
894     t.max_iter = max_iter;
895     t.epsilon = (float)epsilon;
896
897     return t;
898 }
899
900
901 /******************************* CvPoint and variants ***********************************/
902
903 typedef struct CvPoint
904 {
905     int x;
906     int y;
907 }
908 CvPoint;
909
910
911 CV_INLINE  CvPoint  cvPoint( int x, int y )
912 {
913     CvPoint p;
914
915     p.x = x;
916     p.y = y;
917
918     return p;
919 }
920
921
922 typedef struct CvPoint2D32f
923 {
924     float x;
925     float y;
926 }
927 CvPoint2D32f;
928
929
930 CV_INLINE  CvPoint2D32f  cvPoint2D32f( double x, double y )
931 {
932     CvPoint2D32f p;
933
934     p.x = (float)x;
935     p.y = (float)y;
936
937     return p;
938 }
939
940
941 CV_INLINE  CvPoint2D32f  cvPointTo32f( CvPoint point )
942 {
943     return cvPoint2D32f( (float)point.x, (float)point.y );
944 }
945
946
947 CV_INLINE  CvPoint  cvPointFrom32f( CvPoint2D32f point )
948 {
949     CvPoint ipt;
950     ipt.x = cvRound(point.x);
951     ipt.y = cvRound(point.y);
952
953     return ipt;
954 }
955
956
957 typedef struct CvPoint3D32f
958 {
959     float x;
960     float y;
961     float z;
962 }
963 CvPoint3D32f;
964
965
966 CV_INLINE  CvPoint3D32f  cvPoint3D32f( double x, double y, double z )
967 {
968     CvPoint3D32f p;
969
970     p.x = (float)x;
971     p.y = (float)y;
972     p.z = (float)z;
973
974     return p;
975 }
976
977
978 typedef struct CvPoint2D64f
979 {
980     double x;
981     double y;
982 }
983 CvPoint2D64f;
984
985
986 CV_INLINE  CvPoint2D64f  cvPoint2D64f( double x, double y )
987 {
988     CvPoint2D64f p;
989
990     p.x = x;
991     p.y = y;
992
993     return p;
994 }
995
996
997 typedef struct CvPoint3D64f
998 {
999     double x;
1000     double y;
1001     double z;
1002 }
1003 CvPoint3D64f;
1004
1005
1006 CV_INLINE  CvPoint3D64f  cvPoint3D64f( double x, double y, double z )
1007 {
1008     CvPoint3D64f p;
1009
1010     p.x = x;
1011     p.y = y;
1012     p.z = z;
1013
1014     return p;
1015 }
1016
1017
1018 /******************************** CvSize's & CvBox **************************************/
1019
1020 typedef struct
1021 {
1022     int width;
1023     int height;
1024 }
1025 CvSize;
1026
1027 CV_INLINE  CvSize  cvSize( int width, int height )
1028 {
1029     CvSize s;
1030
1031     s.width = width;
1032     s.height = height;
1033
1034     return s;
1035 }
1036
1037 typedef struct CvSize2D32f
1038 {
1039     float width;
1040     float height;
1041 }
1042 CvSize2D32f;
1043
1044
1045 CV_INLINE  CvSize2D32f  cvSize2D32f( double width, double height )
1046 {
1047     CvSize2D32f s;
1048
1049     s.width = (float)width;
1050     s.height = (float)height;
1051
1052     return s;
1053 }
1054
1055 typedef struct CvBox2D
1056 {
1057     CvPoint2D32f center;  /* center of the box */
1058     CvSize2D32f  size;    /* box width and length */
1059     float angle;          /* angle between the horizontal axis
1060                              and the first side (i.e. length) in degrees */
1061 }
1062 CvBox2D;
1063
1064
1065 /* Line iterator state */
1066 typedef struct CvLineIterator
1067 {
1068     /* pointer to the current point */
1069     uchar* ptr;
1070
1071     /* Bresenham algorithm state */
1072     int  err;
1073     int  plus_delta;
1074     int  minus_delta;
1075     int  plus_step;
1076     int  minus_step;
1077 }
1078 CvLineIterator;
1079
1080
1081
1082 /************************************* CvSlice ******************************************/
1083
1084 typedef struct CvSlice
1085 {
1086     int  start_index, end_index;
1087 }
1088 CvSlice;
1089
1090 CV_INLINE  CvSlice  cvSlice( int start, int end )
1091 {
1092     CvSlice slice;
1093     slice.start_index = start;
1094     slice.end_index = end;
1095
1096     return slice;
1097 }
1098
1099 #define CV_WHOLE_SEQ_END_INDEX 0x3fffffff
1100 #define CV_WHOLE_SEQ  cvSlice(0, CV_WHOLE_SEQ_END_INDEX)
1101
1102
1103 /************************************* CvScalar *****************************************/
1104
1105 typedef struct CvScalar
1106 {
1107     double val[4];
1108 }
1109 CvScalar;
1110
1111 CV_INLINE  CvScalar  cvScalar( double val0, double val1 CV_DEFAULT(0),
1112                                double val2 CV_DEFAULT(0), double val3 CV_DEFAULT(0))
1113 {
1114     CvScalar scalar;
1115     scalar.val[0] = val0; scalar.val[1] = val1;
1116     scalar.val[2] = val2; scalar.val[3] = val3;
1117     return scalar;
1118 }
1119
1120
1121 CV_INLINE  CvScalar  cvRealScalar( double val0 )
1122 {
1123     CvScalar scalar;
1124     scalar.val[0] = val0;
1125     scalar.val[1] = scalar.val[2] = scalar.val[3] = 0;
1126     return scalar;
1127 }
1128
1129 CV_INLINE  CvScalar  cvScalarAll( double val0123 )
1130 {
1131     CvScalar scalar;
1132     scalar.val[0] = val0123;
1133     scalar.val[1] = val0123;
1134     scalar.val[2] = val0123;
1135     scalar.val[3] = val0123;
1136     return scalar;
1137 }
1138
1139 /****************************************************************************************\
1140 *                                   Dynamic Data structures                              *
1141 \****************************************************************************************/
1142
1143 /******************************** Memory storage ****************************************/
1144
1145 typedef struct CvMemBlock
1146 {
1147     struct CvMemBlock*  prev;
1148     struct CvMemBlock*  next;
1149 }
1150 CvMemBlock;
1151
1152 #define CV_STORAGE_MAGIC_VAL    0x42890000
1153
1154 typedef struct CvMemStorage
1155 {
1156     int signature;
1157     CvMemBlock* bottom;/* first allocated block */
1158     CvMemBlock* top;   /* current memory block - top of the stack */
1159     struct  CvMemStorage* parent; /* borrows new blocks from */
1160     int block_size;  /* block size */
1161     int free_space;  /* free space in the current block */
1162 }
1163 CvMemStorage;
1164
1165 #define CV_IS_STORAGE(storage)  \
1166     ((storage) != NULL &&       \
1167     (((CvMemStorage*)(storage))->signature & CV_MAGIC_MASK) == CV_STORAGE_MAGIC_VAL)
1168
1169
1170 typedef struct CvMemStoragePos
1171 {
1172     CvMemBlock* top;
1173     int free_space;
1174 }
1175 CvMemStoragePos;
1176
1177
1178 /*********************************** Sequence *******************************************/
1179
1180 typedef struct CvSeqBlock
1181 {
1182     struct CvSeqBlock*  prev; /* previous sequence block */
1183     struct CvSeqBlock*  next; /* next sequence block */
1184     int    start_index;       /* index of the first element in the block +
1185                                  sequence->first->start_index */
1186     int    count;             /* number of elements in the block */
1187     char*  data;              /* pointer to the first element of the block */
1188 }
1189 CvSeqBlock;
1190
1191
1192 #define CV_TREE_NODE_FIELDS(node_type)                          \
1193     int       flags;         /* micsellaneous flags */          \
1194     int       header_size;   /* size of sequence header */      \
1195     struct    node_type* h_prev; /* previous sequence */        \
1196     struct    node_type* h_next; /* next sequence */            \
1197     struct    node_type* v_prev; /* 2nd previous sequence */    \
1198     struct    node_type* v_next  /* 2nd next sequence */
1199
1200 /*
1201    Read/Write sequence.
1202    Elements can be dynamically inserted to or deleted from the sequence.
1203 */
1204 #define CV_SEQUENCE_FIELDS()                                            \
1205     CV_TREE_NODE_FIELDS(CvSeq);                                         \
1206     int       total;          /* total number of elements */            \
1207     int       elem_size;      /* size of sequence element in bytes */   \
1208     char*     block_max;      /* maximal bound of the last block */     \
1209     char*     ptr;            /* current write pointer */               \
1210     int       delta_elems;    /* how many elements allocated when the seq grows */  \
1211     CvMemStorage* storage;    /* where the seq is stored */             \
1212     CvSeqBlock* free_blocks;  /* free blocks list */                    \
1213     CvSeqBlock* first; /* pointer to the first sequence block */
1214
1215 typedef struct CvSeq
1216 {
1217     CV_SEQUENCE_FIELDS()
1218 }
1219 CvSeq;
1220
1221 #define CV_TYPE_NAME_SEQ             "opencv-sequence"
1222 #define CV_TYPE_NAME_SEQ_TREE        "opencv-sequence-tree"
1223
1224 /*************************************** Set ********************************************/
1225 /*
1226   Set.
1227   Order is not preserved. There can be gaps between sequence elements.
1228   After the element has been inserted it stays in the same place all the time.
1229   The MSB(most-significant or sign bit) of the first field (flags) is 0 iff the element exists.
1230 */
1231 #define CV_SET_ELEM_FIELDS(elem_type)   \
1232     int  flags;                         \
1233     struct elem_type* next_free;
1234
1235 typedef struct CvSetElem
1236 {
1237     CV_SET_ELEM_FIELDS(CvSetElem)
1238 }
1239 CvSetElem;
1240
1241 #define CV_SET_FIELDS()      \
1242     CV_SEQUENCE_FIELDS()     \
1243     CvSetElem* free_elems;   \
1244     int active_count;
1245
1246 typedef struct CvSet
1247 {
1248     CV_SET_FIELDS()
1249 }
1250 CvSet;
1251
1252
1253 #define CV_SET_ELEM_IDX_MASK   ((1 << 26) - 1)
1254 #define CV_SET_ELEM_FREE_FLAG  (1 << (sizeof(int)*8-1))
1255
1256 /* Checks whether the element pointed by ptr belongs to a set or not */
1257 #define CV_IS_SET_ELEM( ptr )  (((CvSetElem*)(ptr))->flags >= 0)
1258
1259 /************************************* Graph ********************************************/
1260
1261 /*
1262   Graph is represented as a set of vertices.
1263   Vertices contain their adjacency lists (more exactly, pointers to first incoming or
1264   outcoming edge (or 0 if isolated vertex)). Edges are stored in another set.
1265   There is a single-linked list of incoming/outcoming edges for each vertex.
1266
1267   Each edge consists of:
1268     two pointers to the starting and the ending vertices (vtx[0] and vtx[1],
1269     respectively). Graph may be oriented or not. In the second case, edges between
1270     vertex i to vertex j are not distingueshed (during the search operations).
1271
1272     two pointers to next edges for the starting and the ending vertices.
1273     next[0] points to the next edge in the vtx[0] adjacency list and
1274     next[1] points to the next edge in the vtx[1] adjacency list.
1275 */
1276 #define CV_GRAPH_EDGE_FIELDS()      \
1277     int flags;                      \
1278     float weight;                   \
1279     struct CvGraphEdge* next[2];    \
1280     struct CvGraphVtx* vtx[2];
1281
1282
1283 #define CV_GRAPH_VERTEX_FIELDS()    \
1284     int flags;                      \
1285     struct CvGraphEdge* first;
1286
1287
1288 typedef struct CvGraphEdge
1289 {
1290     CV_GRAPH_EDGE_FIELDS()
1291 }
1292 CvGraphEdge;
1293
1294 typedef struct CvGraphVtx
1295 {
1296     CV_GRAPH_VERTEX_FIELDS()
1297 }
1298 CvGraphVtx;
1299
1300 typedef struct CvGraphVtx2D
1301 {
1302     CV_GRAPH_VERTEX_FIELDS()
1303     CvPoint2D32f* ptr;
1304 }
1305 CvGraphVtx2D;
1306
1307 /*
1308    Graph is "derived" from the set (this is set a of vertices)
1309    and includes another set (edges)
1310 */
1311 #define  CV_GRAPH_FIELDS()   \
1312     CV_SET_FIELDS()          \
1313     CvSet* edges;
1314
1315 typedef struct CvGraph
1316 {
1317     CV_GRAPH_FIELDS()
1318 }
1319 CvGraph;
1320
1321 #define CV_TYPE_NAME_GRAPH "opencv-graph"
1322
1323 /*********************************** Chain/Countour *************************************/
1324
1325 typedef struct CvChain
1326 {
1327     CV_SEQUENCE_FIELDS()
1328     CvPoint  origin;
1329 }
1330 CvChain;
1331
1332 #define CV_CONTOUR_FIELDS()  \
1333     CV_SEQUENCE_FIELDS()     \
1334     CvRect rect;             \
1335     int color;               \
1336     int reserved[3];
1337
1338 typedef struct CvContour
1339 {
1340     CV_CONTOUR_FIELDS()
1341 }
1342 CvContour;
1343
1344 typedef CvContour CvPoint2DSeq;
1345
1346 /****************************************************************************************\
1347 *                                    Sequence types                                      *
1348 \****************************************************************************************/
1349
1350 #define CV_SEQ_MAGIC_VAL             0x42990000
1351
1352 #define CV_IS_SEQ(seq) \
1353     ((seq) != NULL && (((CvSeq*)(seq))->flags & CV_MAGIC_MASK) == CV_SEQ_MAGIC_VAL)
1354
1355 #define CV_SET_MAGIC_VAL             0x42980000
1356 #define CV_IS_SET(set) \
1357     ((set) != NULL && (((CvSeq*)(set))->flags & CV_MAGIC_MASK) == CV_SET_MAGIC_VAL)
1358
1359 #define CV_SEQ_ELTYPE_BITS           9
1360 #define CV_SEQ_ELTYPE_MASK           ((1 << CV_SEQ_ELTYPE_BITS) - 1)
1361
1362 #define CV_SEQ_ELTYPE_POINT          CV_32SC2  /* (x,y) */
1363 #define CV_SEQ_ELTYPE_CODE           CV_8UC1   /* freeman code: 0..7 */
1364 #define CV_SEQ_ELTYPE_GENERIC        0
1365 #define CV_SEQ_ELTYPE_PTR            CV_USRTYPE1
1366 #define CV_SEQ_ELTYPE_PPOINT         CV_SEQ_ELTYPE_PTR  /* &(x,y) */
1367 #define CV_SEQ_ELTYPE_INDEX          CV_32SC1  /* #(x,y) */
1368 #define CV_SEQ_ELTYPE_GRAPH_EDGE     0  /* &next_o, &next_d, &vtx_o, &vtx_d */
1369 #define CV_SEQ_ELTYPE_GRAPH_VERTEX   0  /* first_edge, &(x,y) */
1370 #define CV_SEQ_ELTYPE_TRIAN_ATR      0  /* vertex of the binary tree   */
1371 #define CV_SEQ_ELTYPE_CONNECTED_COMP 0  /* connected component  */
1372 #define CV_SEQ_ELTYPE_POINT3D        CV_32FC3  /* (x,y,z)  */
1373
1374 #define CV_SEQ_KIND_BITS        3
1375 #define CV_SEQ_KIND_MASK        (((1 << CV_SEQ_KIND_BITS) - 1)<<CV_SEQ_ELTYPE_BITS)
1376
1377 /* types of sequences */
1378 #define CV_SEQ_KIND_GENERIC     (0 << CV_SEQ_ELTYPE_BITS)
1379 #define CV_SEQ_KIND_CURVE       (1 << CV_SEQ_ELTYPE_BITS)
1380 #define CV_SEQ_KIND_BIN_TREE    (2 << CV_SEQ_ELTYPE_BITS)
1381
1382 /* types of sparse sequences (sets) */
1383 #define CV_SEQ_KIND_GRAPH       (3 << CV_SEQ_ELTYPE_BITS)
1384 #define CV_SEQ_KIND_SUBDIV2D    (4 << CV_SEQ_ELTYPE_BITS)
1385
1386 #define CV_SEQ_FLAG_SHIFT       (CV_SEQ_KIND_BITS + CV_SEQ_ELTYPE_BITS)
1387
1388 /* flags for curves */
1389 #define CV_SEQ_FLAG_CLOSED     (1 << CV_SEQ_FLAG_SHIFT)
1390 #define CV_SEQ_FLAG_SIMPLE     (2 << CV_SEQ_FLAG_SHIFT)
1391 #define CV_SEQ_FLAG_CONVEX     (4 << CV_SEQ_FLAG_SHIFT)
1392 #define CV_SEQ_FLAG_HOLE       (8 << CV_SEQ_FLAG_SHIFT)
1393
1394 /* flags for graphs */
1395 #define CV_GRAPH_FLAG_ORIENTED (1 << CV_SEQ_FLAG_SHIFT)
1396
1397 #define CV_GRAPH               CV_SEQ_KIND_GRAPH
1398 #define CV_ORIENTED_GRAPH      (CV_SEQ_KIND_GRAPH|CV_GRAPH_FLAG_ORIENTED)
1399
1400 /* point sets */
1401 #define CV_SEQ_POINT_SET       (CV_SEQ_KIND_GENERIC| CV_SEQ_ELTYPE_POINT)
1402 #define CV_SEQ_POINT3D_SET     (CV_SEQ_KIND_GENERIC| CV_SEQ_ELTYPE_POINT3D)
1403 #define CV_SEQ_POLYLINE        (CV_SEQ_KIND_CURVE  | CV_SEQ_ELTYPE_POINT)
1404 #define CV_SEQ_POLYGON         (CV_SEQ_FLAG_CLOSED | CV_SEQ_POLYLINE )
1405 #define CV_SEQ_CONTOUR         CV_SEQ_POLYGON
1406 #define CV_SEQ_SIMPLE_POLYGON  (CV_SEQ_FLAG_SIMPLE | CV_SEQ_POLYGON  )
1407
1408 /* chain-coded curves */
1409 #define CV_SEQ_CHAIN           (CV_SEQ_KIND_CURVE  | CV_SEQ_ELTYPE_CODE)
1410 #define CV_SEQ_CHAIN_CONTOUR   (CV_SEQ_FLAG_CLOSED | CV_SEQ_CHAIN)
1411
1412 /* binary tree for the contour */
1413 #define CV_SEQ_POLYGON_TREE    (CV_SEQ_KIND_BIN_TREE  | CV_SEQ_ELTYPE_TRIAN_ATR)
1414
1415 /* sequence of the connected components */
1416 #define CV_SEQ_CONNECTED_COMP  (CV_SEQ_KIND_GENERIC  | CV_SEQ_ELTYPE_CONNECTED_COMP)
1417
1418 /* sequence of the integer numbers */
1419 #define CV_SEQ_INDEX           (CV_SEQ_KIND_GENERIC  | CV_SEQ_ELTYPE_INDEX)
1420
1421 #define CV_SEQ_ELTYPE( seq )   ((seq)->flags & CV_SEQ_ELTYPE_MASK)
1422 #define CV_SEQ_KIND( seq )     ((seq)->flags & CV_SEQ_KIND_MASK )
1423
1424 /* flag checking */
1425 #define CV_IS_SEQ_INDEX( seq )      ((CV_SEQ_ELTYPE(seq) == CV_SEQ_ELTYPE_INDEX) && \
1426                                      (CV_SEQ_KIND(seq) == CV_SEQ_KIND_GENERIC))
1427
1428 #define CV_IS_SEQ_CURVE( seq )      (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE)
1429 #define CV_IS_SEQ_CLOSED( seq )     (((seq)->flags & CV_SEQ_FLAG_CLOSED) != 0)
1430 #define CV_IS_SEQ_CONVEX( seq )     (((seq)->flags & CV_SEQ_FLAG_CONVEX) != 0)
1431 #define CV_IS_SEQ_HOLE( seq )       (((seq)->flags & CV_SEQ_FLAG_HOLE) != 0)
1432 #define CV_IS_SEQ_SIMPLE( seq )     ((((seq)->flags & CV_SEQ_FLAG_SIMPLE) != 0) || \
1433                                     CV_IS_SEQ_CONVEX(seq))
1434
1435 /* type checking macros */
1436 #define CV_IS_SEQ_POINT_SET( seq ) \
1437     ((CV_SEQ_ELTYPE(seq) == CV_32SC2 || CV_SEQ_ELTYPE(seq) == CV_32FC2))
1438
1439 #define CV_IS_SEQ_POINT_SUBSET( seq ) \
1440     (CV_IS_SEQ_INDEX( seq ) || CV_SEQ_ELTYPE(seq) == CV_SEQ_ELTYPE_PPOINT)
1441
1442 #define CV_IS_SEQ_POLYLINE( seq )   \
1443     (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE && CV_IS_SEQ_POINT_SET(seq))
1444
1445 #define CV_IS_SEQ_POLYGON( seq )   \
1446     (CV_IS_SEQ_POLYLINE(seq) && CV_IS_SEQ_CLOSED(seq))
1447
1448 #define CV_IS_SEQ_CHAIN( seq )   \
1449     (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE && (seq)->elem_size == 1)
1450
1451 #define CV_IS_SEQ_CONTOUR( seq )   \
1452     (CV_IS_SEQ_CLOSED(seq) && (CV_IS_SEQ_POLYLINE(seq) || CV_IS_SEQ_CHAIN(seq)))
1453
1454 #define CV_IS_SEQ_CHAIN_CONTOUR( seq ) \
1455     (CV_IS_SEQ_CHAIN( seq ) && CV_IS_SEQ_CLOSED( seq ))
1456
1457 #define CV_IS_SEQ_POLYGON_TREE( seq ) \
1458     (CV_SEQ_ELTYPE (seq) ==  CV_SEQ_ELTYPE_TRIAN_ATR &&    \
1459     CV_SEQ_KIND( seq ) ==  CV_SEQ_KIND_BIN_TREE )
1460
1461 #define CV_IS_GRAPH( seq )    \
1462     (CV_IS_SET(seq) && CV_SEQ_KIND((CvSet*)(seq)) == CV_SEQ_KIND_GRAPH)
1463
1464 #define CV_IS_GRAPH_ORIENTED( seq )   \
1465     (((seq)->flags & CV_GRAPH_FLAG_ORIENTED) != 0)
1466
1467 #define CV_IS_SUBDIV2D( seq )  \
1468     (CV_IS_SET(seq) && CV_SEQ_KIND((CvSet*)(seq)) == CV_SEQ_KIND_SUBDIV2D)
1469
1470 /****************************************************************************************/
1471 /*                            Sequence writer & reader                                  */
1472 /****************************************************************************************/
1473
1474 #define CV_SEQ_WRITER_FIELDS()                                     \
1475     int          header_size;                                      \
1476     CvSeq*       seq;        /* the sequence written */            \
1477     CvSeqBlock*  block;      /* current block */                   \
1478     char*        ptr;        /* pointer to free space */           \
1479     char*        block_min;  /* pointer to the beginning of block*/\
1480     char*        block_max;  /* pointer to the end of block */
1481
1482 typedef struct CvSeqWriter
1483 {
1484     CV_SEQ_WRITER_FIELDS()
1485 }
1486 CvSeqWriter;
1487
1488
1489 #define CV_SEQ_READER_FIELDS()                                      \
1490     int          header_size;                                       \
1491     CvSeq*       seq;        /* sequence, beign read */             \
1492     CvSeqBlock*  block;      /* current block */                    \
1493     char*        ptr;        /* pointer to element be read next */  \
1494     char*        block_min;  /* pointer to the beginning of block */\
1495     char*        block_max;  /* pointer to the end of block */      \
1496     int          delta_index;/* = seq->first->start_index   */      \
1497     char*        prev_elem;  /* pointer to previous element */
1498
1499
1500 typedef struct CvSeqReader
1501 {
1502     CV_SEQ_READER_FIELDS()
1503 }
1504 CvSeqReader;
1505
1506 /****************************************************************************************/
1507 /*                                Operations on sequences                               */
1508 /****************************************************************************************/
1509
1510 #define  CV_SEQ_ELEM( seq, elem_type, index )                    \
1511 /* assert gives some guarantee that <seq> parameter is valid */  \
1512 (   assert(sizeof((seq)->first[0]) == sizeof(CvSeqBlock) &&      \
1513     (seq)->elem_size == sizeof(elem_type)),                      \
1514     (elem_type*)((seq)->first && (unsigned)index <               \
1515     (unsigned)((seq)->first->count) ?                            \
1516     (seq)->first->data + (index) * sizeof(elem_type) :           \
1517     cvGetSeqElem( (CvSeq*)(seq), (index) )))
1518 #define CV_GET_SEQ_ELEM( elem_type, seq, index ) CV_SEQ_ELEM( (seq), elem_type, (index) )
1519
1520 /* macro that adds element to sequence */
1521 #define CV_WRITE_SEQ_ELEM_VAR( elem_ptr, writer )     \
1522 {                                                     \
1523     if( (writer).ptr >= (writer).block_max )          \
1524     {                                                 \
1525         cvCreateSeqBlock( &writer);                   \
1526     }                                                 \
1527     memcpy((writer).ptr, elem_ptr, (writer).seq->elem_size);\
1528     (writer).ptr += (writer).seq->elem_size;          \
1529 }
1530
1531 #define CV_WRITE_SEQ_ELEM( elem, writer )             \
1532 {                                                     \
1533     assert( (writer).seq->elem_size == sizeof(elem)); \
1534     if( (writer).ptr >= (writer).block_max )          \
1535     {                                                 \
1536         cvCreateSeqBlock( &writer);                   \
1537     }                                                 \
1538     assert( (writer).ptr <= (writer).block_max - sizeof(elem));\
1539     memcpy((writer).ptr, &(elem), sizeof(elem));      \
1540     (writer).ptr += sizeof(elem);                     \
1541 }
1542
1543
1544 /* move reader position forward */
1545 #define CV_NEXT_SEQ_ELEM( elem_size, reader )                 \
1546 {                                                             \
1547     if( ((reader).ptr += (elem_size)) >= (reader).block_max ) \
1548     {                                                         \
1549         cvChangeSeqBlock( &(reader), 1 );                     \
1550     }                                                         \
1551 }
1552
1553
1554 /* move reader position backward */
1555 #define CV_PREV_SEQ_ELEM( elem_size, reader )                \
1556 {                                                            \
1557     if( ((reader).ptr -= (elem_size)) < (reader).block_min ) \
1558     {                                                        \
1559         cvChangeSeqBlock( &(reader), -1 );                   \
1560     }                                                        \
1561 }
1562
1563 /* read element and move read position forward */
1564 #define CV_READ_SEQ_ELEM( elem, reader )                       \
1565 {                                                              \
1566     assert( (reader).seq->elem_size == sizeof(elem));          \
1567     memcpy( &(elem), (reader).ptr, sizeof((elem)));            \
1568     CV_NEXT_SEQ_ELEM( sizeof(elem), reader )                   \
1569 }
1570
1571 /* read element and move read position backward */
1572 #define CV_REV_READ_SEQ_ELEM( elem, reader )                     \
1573 {                                                                \
1574     assert( (reader).seq->elem_size == sizeof(elem));            \
1575     memcpy(&(elem), (reader).ptr, sizeof((elem)));               \
1576     CV_PREV_SEQ_ELEM( sizeof(elem), reader )                     \
1577 }
1578
1579
1580 #define CV_READ_CHAIN_POINT( _pt, reader )                              \
1581 {                                                                       \
1582     (_pt) = (reader).pt;                                                \
1583     if( (reader).ptr )                                                  \
1584     {                                                                   \
1585         CV_READ_SEQ_ELEM( (reader).code, (reader));                     \
1586         assert( ((reader).code & ~7) == 0 );                            \
1587         (reader).pt.x += (reader).deltas[(int)(reader).code][0];        \
1588         (reader).pt.y += (reader).deltas[(int)(reader).code][1];        \
1589     }                                                                   \
1590 }
1591
1592 #define CV_CURRENT_POINT( reader )  (*((CvPoint*)((reader).ptr)))
1593 #define CV_PREV_POINT( reader )     (*((CvPoint*)((reader).prev_elem)))
1594
1595 #define CV_READ_EDGE( pt1, pt2, reader )               \
1596 {                                                      \
1597     assert( sizeof(pt1) == sizeof(CvPoint) &&          \
1598             sizeof(pt2) == sizeof(CvPoint) &&          \
1599             reader.seq->elem_size == sizeof(CvPoint)); \
1600     (pt1) = CV_PREV_POINT( reader );                   \
1601     (pt2) = CV_CURRENT_POINT( reader );                \
1602     (reader).prev_elem = (reader).ptr;                 \
1603     CV_NEXT_SEQ_ELEM( sizeof(CvPoint), (reader));      \
1604 }
1605
1606 /************ Graph macros ************/
1607
1608 /* returns next graph edge for given vertex */
1609 #define  CV_NEXT_GRAPH_EDGE( edge, vertex )                              \
1610      (assert((edge)->vtx[0] == (vertex) || (edge)->vtx[1] == (vertex)),  \
1611       (edge)->next[(edge)->vtx[1] == (vertex)])
1612
1613
1614
1615 /****************************************************************************************\
1616 *             Data structures for persistence (a.k.a serialization) functionality        *
1617 \****************************************************************************************/
1618
1619 /* "black box" file storage */
1620 typedef struct CvFileStorage CvFileStorage;
1621
1622 /* storage flags */
1623 #define CV_STORAGE_READ          0
1624 #define CV_STORAGE_WRITE         1
1625 #define CV_STORAGE_WRITE_TEXT    CV_STORAGE_WRITE
1626 #define CV_STORAGE_WRITE_BINARY  CV_STORAGE_WRITE
1627 #define CV_STORAGE_APPEND        2
1628
1629 /* list of attributes */
1630 typedef struct CvAttrList
1631 {
1632     const char** attr; /* NULL-terminated array of (attribute_name,attribute_value) pairs */
1633     struct CvAttrList* next; /* pointer to next chunk of the attributes list */
1634 }
1635 CvAttrList;
1636
1637 CV_INLINE CvAttrList cvAttrList( const char** attr CV_DEFAULT(NULL),
1638                                  CvAttrList* next CV_DEFAULT(NULL) )
1639 {
1640     CvAttrList l;
1641     l.attr = attr;
1642     l.next = next;
1643
1644     return l;
1645 }
1646
1647 struct CvTypeInfo;
1648
1649 #define CV_NODE_NONE        0
1650 #define CV_NODE_INT         1
1651 #define CV_NODE_INTEGER     CV_NODE_INT
1652 #define CV_NODE_REAL        2
1653 #define CV_NODE_FLOAT       CV_NODE_REAL
1654 #define CV_NODE_STR         3
1655 #define CV_NODE_STRING      CV_NODE_STR
1656 #define CV_NODE_REF         4 /* not used */
1657 #define CV_NODE_SEQ         5
1658 #define CV_NODE_MAP         6
1659 #define CV_NODE_TYPE_MASK   7
1660
1661 #define CV_NODE_TYPE(flags)  ((flags) & CV_NODE_TYPE_MASK)
1662
1663 /* file node flags */
1664 #define CV_NODE_FLOW        8 /* used only for writing structures to YAML format */
1665 #define CV_NODE_USER        16
1666 #define CV_NODE_EMPTY       32
1667 #define CV_NODE_NAMED       64
1668
1669 #define CV_NODE_IS_INT(flags)        (CV_NODE_TYPE(flags) == CV_NODE_INT)
1670 #define CV_NODE_IS_REAL(flags)       (CV_NODE_TYPE(flags) == CV_NODE_REAL)
1671 #define CV_NODE_IS_STRING(flags)     (CV_NODE_TYPE(flags) == CV_NODE_STRING)
1672 #define CV_NODE_IS_SEQ(flags)        (CV_NODE_TYPE(flags) == CV_NODE_SEQ)
1673 #define CV_NODE_IS_MAP(flags)        (CV_NODE_TYPE(flags) == CV_NODE_MAP)
1674 #define CV_NODE_IS_COLLECTION(flags) (CV_NODE_TYPE(flags) >= CV_NODE_SEQ)
1675 #define CV_NODE_IS_FLOW(flags)       (((flags) & CV_NODE_FLOW) != 0)
1676 #define CV_NODE_IS_EMPTY(flags)      (((flags) & CV_NODE_EMPTY) != 0)
1677 #define CV_NODE_IS_USER(flags)       (((flags) & CV_NODE_USER) != 0)
1678 #define CV_NODE_HAS_NAME(flags)      (((flags) & CV_NODE_NAMED) != 0)
1679
1680 #define CV_NODE_SEQ_SIMPLE 256
1681 #define CV_NODE_SEQ_IS_SIMPLE(seq) (((seq)->flags & CV_NODE_SEQ_SIMPLE) != 0)
1682
1683 typedef struct CvString
1684 {
1685     int len;
1686     char* ptr;
1687 }
1688 CvString;
1689
1690 /* all the keys (names) of elements in the readed file storage
1691    are stored in the hash to speed up the lookup operations */
1692 typedef struct CvStringHashNode
1693 {
1694     unsigned hashval;
1695     CvString str;
1696     struct CvStringHashNode* next;
1697 }
1698 CvStringHashNode;
1699
1700 typedef struct CvGenericHash CvFileNodeHash;
1701
1702 /* basic element of the file storage - scalar or collection */
1703 typedef struct CvFileNode
1704 {
1705     int tag;
1706     struct CvTypeInfo* info; /* type information
1707             (only for user-defined object, for others it is 0) */
1708     union
1709     {
1710         double f; /* scalar floating-point number */
1711         int i;    /* scalar integer number */
1712         CvString str; /* text string */
1713         CvSeq* seq; /* sequence (ordered collection of file nodes) */
1714         CvFileNodeHash* map; /* map (collection of named file nodes) */
1715     } data;
1716 }
1717 CvFileNode;
1718
1719 #ifdef __cplusplus
1720 extern "C" {
1721 #endif
1722 typedef int (CV_CDECL *CvIsInstanceFunc)( const void* struct_ptr );
1723 typedef void (CV_CDECL *CvReleaseFunc)( void** struct_dblptr );
1724 typedef void* (CV_CDECL *CvReadFunc)( CvFileStorage* storage, CvFileNode* node );
1725 typedef void (CV_CDECL *CvWriteFunc)( CvFileStorage* storage, const char* name,
1726                                       const void* struct_ptr, CvAttrList attributes );
1727 typedef void* (CV_CDECL *CvCloneFunc)( const void* struct_ptr );
1728 #ifdef __cplusplus
1729 }
1730 #endif
1731
1732 typedef struct CvTypeInfo
1733 {
1734     int flags;
1735     int header_size;
1736     struct CvTypeInfo* prev;
1737     struct CvTypeInfo* next;
1738     const char* type_name;
1739     CvIsInstanceFunc is_instance;
1740     CvReleaseFunc release;
1741     CvReadFunc read;
1742     CvWriteFunc write;
1743     CvCloneFunc clone;
1744 }
1745 CvTypeInfo;
1746
1747
1748 /**** System data types ******/
1749
1750 typedef struct CvPluginFuncInfo
1751 {
1752     void** func_addr;
1753     void* default_func_addr;
1754     const char* func_names;
1755     int search_modules;
1756     int loaded_from;
1757 }
1758 CvPluginFuncInfo;
1759
1760 typedef struct CvModuleInfo
1761 {
1762     struct CvModuleInfo* next;
1763     const char* name;
1764     const char* version;
1765     CvPluginFuncInfo* func_tab;
1766 }
1767 CvModuleInfo;
1768
1769 #endif /*_CXCORE_TYPES_H_*/
1770
1771 /* End of file. */