Fully disable AUD's FFTW3 usage.
[blender-staging.git] / source / blender / blenkernel / intern / customdata.c
1 /*
2 * $Id$
3 *
4 * ***** BEGIN GPL LICENSE BLOCK *****
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * 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 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software  Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 *
20 * The Original Code is Copyright (C) 2006 Blender Foundation.
21 * All rights reserved.
22 *
23 * The Original Code is: all of this file.
24 *
25 * Contributor(s): Ben Batt <benbatt@gmail.com>
26 *
27 * ***** END GPL LICENSE BLOCK *****
28 *
29 * Implementation of CustomData.
30 *
31 * BKE_customdata.h contains the function prototypes for this file.
32 *
33 */ 
34
35 #include <math.h>
36 #include <string.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "DNA_meshdata_types.h"
41 #include "DNA_ID.h"
42
43 #include "BLI_blenlib.h"
44 #include "BLI_linklist.h"
45 #include "BLI_math.h"
46 #include "BLI_mempool.h"
47
48 #include "BKE_customdata.h"
49 #include "BKE_customdata_file.h"
50 #include "BKE_global.h"
51 #include "BKE_main.h"
52 #include "BKE_utildefines.h"
53
54 /* number of layers to add when growing a CustomData object */
55 #define CUSTOMDATA_GROW 5
56
57 /********************* Layer type information **********************/
58 typedef struct LayerTypeInfo {
59         int size;          /* the memory size of one element of this layer's data */
60         char *structname;  /* name of the struct used, for file writing */
61         int structnum;     /* number of structs per element, for file writing */
62         char *defaultname; /* default layer name */
63
64         /* a function to copy count elements of this layer's data
65          * (deep copy if appropriate)
66          * if NULL, memcpy is used
67          */
68         void (*copy)(const void *source, void *dest, int count);
69
70         /* a function to free any dynamically allocated components of this
71          * layer's data (note the data pointer itself should not be freed)
72          * size should be the size of one element of this layer's data (e.g.
73          * LayerTypeInfo.size)
74          */
75         void (*free)(void *data, int count, int size);
76
77         /* a function to interpolate between count source elements of this
78          * layer's data and store the result in dest
79          * if weights == NULL or sub_weights == NULL, they should default to 1
80          *
81          * weights gives the weight for each element in sources
82          * sub_weights gives the sub-element weights for each element in sources
83          *    (there should be (sub element count)^2 weights per element)
84          * count gives the number of elements in sources
85          */
86         void (*interp)(void **sources, float *weights, float *sub_weights,
87                                    int count, void *dest);
88
89         /* a function to swap the data in corners of the element */
90         void (*swap)(void *data, const int *corner_indices);
91
92         /* a function to set a layer's data to default values. if NULL, the
93            default is assumed to be all zeros */
94         void (*set_default)(void *data, int count);
95
96         /* a function to read data from a cdf file */
97         int (*read)(CDataFile *cdf, void *data, int count);
98
99         /* a function to write data to a cdf file */
100         int (*write)(CDataFile *cdf, void *data, int count);
101
102         /* a function to determine file size */
103         size_t (*filesize)(CDataFile *cdf, void *data, int count);
104 } LayerTypeInfo;
105
106 static void layerCopy_mdeformvert(const void *source, void *dest,
107                                                                   int count)
108 {
109         int i, size = sizeof(MDeformVert);
110
111         memcpy(dest, source, count * size);
112
113         for(i = 0; i < count; ++i) {
114                 MDeformVert *dvert = (MDeformVert *)((char *)dest + i * size);
115
116                 if(dvert->totweight) {
117                         MDeformWeight *dw = MEM_callocN(dvert->totweight * sizeof(*dw),
118                                                                                         "layerCopy_mdeformvert dw");
119
120                         memcpy(dw, dvert->dw, dvert->totweight * sizeof(*dw));
121                         dvert->dw = dw;
122                 }
123                 else
124                         dvert->dw = NULL;
125         }
126 }
127
128 static void layerFree_mdeformvert(void *data, int count, int size)
129 {
130         int i;
131
132         for(i = 0; i < count; ++i) {
133                 MDeformVert *dvert = (MDeformVert *)((char *)data + i * size);
134
135                 if(dvert->dw) {
136                         MEM_freeN(dvert->dw);
137                         dvert->dw = NULL;
138                         dvert->totweight = 0;
139                 }
140         }
141 }
142
143 static void linklist_free_simple(void *link)
144 {
145         MEM_freeN(link);
146 }
147
148 static void layerInterp_mdeformvert(void **sources, float *weights,
149                                                                         float *UNUSED(sub_weights), int count, void *dest)
150 {
151         MDeformVert *dvert = dest;
152         LinkNode *dest_dw = NULL; /* a list of lists of MDeformWeight pointers */
153         LinkNode *node;
154         int i, j, totweight;
155
156         if(count <= 0) return;
157
158         /* build a list of unique def_nrs for dest */
159         totweight = 0;
160         for(i = 0; i < count; ++i) {
161                 MDeformVert *source = sources[i];
162                 float interp_weight = weights ? weights[i] : 1.0f;
163
164                 for(j = 0; j < source->totweight; ++j) {
165                         MDeformWeight *dw = &source->dw[j];
166
167                         for(node = dest_dw; node; node = node->next) {
168                                 MDeformWeight *tmp_dw = (MDeformWeight *)node->link;
169
170                                 if(tmp_dw->def_nr == dw->def_nr) {
171                                         tmp_dw->weight += dw->weight * interp_weight;
172                                         break;
173                                 }
174                         }
175
176                         /* if this def_nr is not in the list, add it */
177                         if(!node) {
178                                 MDeformWeight *tmp_dw = MEM_callocN(sizeof(*tmp_dw),
179                                                                                         "layerInterp_mdeformvert tmp_dw");
180                                 tmp_dw->def_nr = dw->def_nr;
181                                 tmp_dw->weight = dw->weight * interp_weight;
182                                 BLI_linklist_prepend(&dest_dw, tmp_dw);
183                                 totweight++;
184                         }
185                 }
186         }
187
188         /* now we know how many unique deform weights there are, so realloc */
189         if(dvert->dw) MEM_freeN(dvert->dw);
190
191         if(totweight) {
192                 dvert->dw = MEM_callocN(sizeof(*dvert->dw) * totweight,
193                                                                 "layerInterp_mdeformvert dvert->dw");
194                 dvert->totweight = totweight;
195
196                 for(i = 0, node = dest_dw; node; node = node->next, ++i)
197                         dvert->dw[i] = *((MDeformWeight *)node->link);
198         }
199         else
200                 memset(dvert, 0, sizeof(*dvert));
201
202         BLI_linklist_free(dest_dw, linklist_free_simple);
203 }
204
205
206 static void layerInterp_msticky(void **sources, float *weights,
207                                                                 float *UNUSED(sub_weights), int count, void *dest)
208 {
209         float co[2], w;
210         MSticky *mst;
211         int i;
212
213         co[0] = co[1] = 0.0f;
214         for(i = 0; i < count; i++) {
215                 w = weights ? weights[i] : 1.0f;
216                 mst = (MSticky*)sources[i];
217
218                 co[0] += w*mst->co[0];
219                 co[1] += w*mst->co[1];
220         }
221
222         mst = (MSticky*)dest;
223         mst->co[0] = co[0];
224         mst->co[1] = co[1];
225 }
226
227
228 static void layerCopy_tface(const void *source, void *dest, int count)
229 {
230         const MTFace *source_tf = (const MTFace*)source;
231         MTFace *dest_tf = (MTFace*)dest;
232         int i;
233
234         for(i = 0; i < count; ++i)
235                 dest_tf[i] = source_tf[i];
236 }
237
238 static void layerInterp_tface(void **sources, float *weights,
239                                                           float *sub_weights, int count, void *dest)
240 {
241         MTFace *tf = dest;
242         int i, j, k;
243         float uv[4][2];
244         float *sub_weight;
245
246         if(count <= 0) return;
247
248         memset(uv, 0, sizeof(uv));
249
250         sub_weight = sub_weights;
251         for(i = 0; i < count; ++i) {
252                 float weight = weights ? weights[i] : 1;
253                 MTFace *src = sources[i];
254
255                 for(j = 0; j < 4; ++j) {
256                         if(sub_weights) {
257                                 for(k = 0; k < 4; ++k, ++sub_weight) {
258                                         float w = (*sub_weight) * weight;
259                                         float *tmp_uv = src->uv[k];
260
261                                         uv[j][0] += tmp_uv[0] * w;
262                                         uv[j][1] += tmp_uv[1] * w;
263                                 }
264                         } else {
265                                 uv[j][0] += src->uv[j][0] * weight;
266                                 uv[j][1] += src->uv[j][1] * weight;
267                         }
268                 }
269         }
270
271         *tf = *(MTFace *)sources[0];
272         for(j = 0; j < 4; ++j) {
273                 tf->uv[j][0] = uv[j][0];
274                 tf->uv[j][1] = uv[j][1];
275         }
276 }
277
278 static void layerSwap_tface(void *data, const int *corner_indices)
279 {
280         MTFace *tf = data;
281         float uv[4][2];
282         static const short pin_flags[4] =
283                 { TF_PIN1, TF_PIN2, TF_PIN3, TF_PIN4 };
284         static const char sel_flags[4] =
285                 { TF_SEL1, TF_SEL2, TF_SEL3, TF_SEL4 };
286         short unwrap = tf->unwrap & ~(TF_PIN1 | TF_PIN2 | TF_PIN3 | TF_PIN4);
287         char flag = tf->flag & ~(TF_SEL1 | TF_SEL2 | TF_SEL3 | TF_SEL4);
288         int j;
289
290         for(j = 0; j < 4; ++j) {
291                 int source_index = corner_indices[j];
292
293                 uv[j][0] = tf->uv[source_index][0];
294                 uv[j][1] = tf->uv[source_index][1];
295
296                 // swap pinning flags around
297                 if(tf->unwrap & pin_flags[source_index]) {
298                         unwrap |= pin_flags[j];
299                 }
300
301                 // swap selection flags around
302                 if(tf->flag & sel_flags[source_index]) {
303                         flag |= sel_flags[j];
304                 }
305         }
306
307         memcpy(tf->uv, uv, sizeof(tf->uv));
308         tf->unwrap = unwrap;
309         tf->flag = flag;
310 }
311
312 static void layerDefault_tface(void *data, int count)
313 {
314         static MTFace default_tf = {{{0, 0}, {1, 0}, {1, 1}, {0, 1}}, NULL,
315                                                            0, 0, TF_DYNAMIC, 0, 0};
316         MTFace *tf = (MTFace*)data;
317         int i;
318
319         for(i = 0; i < count; i++)
320                 tf[i] = default_tf;
321 }
322
323 static void layerCopy_origspace_face(const void *source, void *dest, int count)
324 {
325         const OrigSpaceFace *source_tf = (const OrigSpaceFace*)source;
326         OrigSpaceFace *dest_tf = (OrigSpaceFace*)dest;
327         int i;
328
329         for(i = 0; i < count; ++i)
330                 dest_tf[i] = source_tf[i];
331 }
332
333 static void layerInterp_origspace_face(void **sources, float *weights,
334                                                           float *sub_weights, int count, void *dest)
335 {
336         OrigSpaceFace *osf = dest;
337         int i, j, k;
338         float uv[4][2];
339         float *sub_weight;
340
341         if(count <= 0) return;
342
343         memset(uv, 0, sizeof(uv));
344
345         sub_weight = sub_weights;
346         for(i = 0; i < count; ++i) {
347                 float weight = weights ? weights[i] : 1;
348                 OrigSpaceFace *src = sources[i];
349
350                 for(j = 0; j < 4; ++j) {
351                         if(sub_weights) {
352                                 for(k = 0; k < 4; ++k, ++sub_weight) {
353                                         float w = (*sub_weight) * weight;
354                                         float *tmp_uv = src->uv[k];
355
356                                         uv[j][0] += tmp_uv[0] * w;
357                                         uv[j][1] += tmp_uv[1] * w;
358                                 }
359                         } else {
360                                 uv[j][0] += src->uv[j][0] * weight;
361                                 uv[j][1] += src->uv[j][1] * weight;
362                         }
363                 }
364         }
365
366         *osf = *(OrigSpaceFace *)sources[0];
367         for(j = 0; j < 4; ++j) {
368                 osf->uv[j][0] = uv[j][0];
369                 osf->uv[j][1] = uv[j][1];
370         }
371 }
372
373 static void layerSwap_origspace_face(void *data, const int *corner_indices)
374 {
375         OrigSpaceFace *osf = data;
376         float uv[4][2];
377         int j;
378
379         for(j = 0; j < 4; ++j) {
380                 uv[j][0] = osf->uv[corner_indices[j]][0];
381                 uv[j][1] = osf->uv[corner_indices[j]][1];
382         }
383         memcpy(osf->uv, uv, sizeof(osf->uv));
384 }
385
386 static void layerDefault_origspace_face(void *data, int count)
387 {
388         static OrigSpaceFace default_osf = {{{0, 0}, {1, 0}, {1, 1}, {0, 1}}};
389         OrigSpaceFace *osf = (OrigSpaceFace*)data;
390         int i;
391
392         for(i = 0; i < count; i++)
393                 osf[i] = default_osf;
394 }
395
396 #if 0
397 /* Adapted from sculptmode.c */
398 static void mdisps_bilinear(float out[3], float (*disps)[3], int st, float u, float v)
399 {
400         int x, y, x2, y2;
401         const int st_max = st - 1;
402         float urat, vrat, uopp;
403         float d[4][3], d2[2][3];
404
405         if(u < 0)
406                 u = 0;
407         else if(u >= st)
408                 u = st_max;
409         if(v < 0)
410                 v = 0;
411         else if(v >= st)
412                 v = st_max;
413
414         x = floor(u);
415         y = floor(v);
416         x2 = x + 1;
417         y2 = y + 1;
418
419         if(x2 >= st) x2 = st_max;
420         if(y2 >= st) y2 = st_max;
421         
422         urat = u - x;
423         vrat = v - y;
424         uopp = 1 - urat;
425
426         copy_v3_v3(d[0], disps[y * st + x]);
427         copy_v3_v3(d[1], disps[y * st + x2]);
428         copy_v3_v3(d[2], disps[y2 * st + x]);
429         copy_v3_v3(d[3], disps[y2 * st + x2]);
430         mul_v3_fl(d[0], uopp);
431         mul_v3_fl(d[1], urat);
432         mul_v3_fl(d[2], uopp);
433         mul_v3_fl(d[3], urat);
434
435         add_v3_v3v3(d2[0], d[0], d[1]);
436         add_v3_v3v3(d2[1], d[2], d[3]);
437         mul_v3_fl(d2[0], 1 - vrat);
438         mul_v3_fl(d2[1], vrat);
439
440         add_v3_v3v3(out, d2[0], d2[1]);
441 }
442 #endif
443
444 static int mdisp_corners(MDisps *s)
445 {
446         int lvl= 13;
447
448         while(lvl > 0) {
449                 int side = (1 << (lvl-1)) + 1;
450                 if ((s->totdisp % (side*side)) == 0) return s->totdisp / (side*side);
451                 lvl--;
452         }
453
454         return 0;
455 }
456
457 static void layerSwap_mdisps(void *data, const int *ci)
458 {
459         MDisps *s = data;
460         float (*d)[3] = NULL;
461         int corners, cornersize, S;
462
463         if(s->disps) {
464                 int nverts= (ci[1] == 3) ? 4 : 3; /* silly way to know vertex count of face */
465                 corners= mdisp_corners(s);
466                 cornersize= s->totdisp/corners;
467
468                 if(corners!=nverts) {
469                         /* happens when face changed vertex count in edit mode
470                            if it happened, just forgot displacement */
471
472                         MEM_freeN(s->disps);
473                         s->disps= NULL;
474                         s->totdisp= 0; /* flag to update totdisp */
475                         return;
476                 }
477
478                 d= MEM_callocN(sizeof(float) * 3 * s->totdisp, "mdisps swap");
479
480                 for(S = 0; S < corners; S++)
481                         memcpy(d + cornersize*S, s->disps + cornersize*ci[S], cornersize*3*sizeof(float));
482                 
483                 MEM_freeN(s->disps);
484                 s->disps= d;
485         }
486 }
487
488 static void layerInterp_mdisps(void **UNUSED(sources), float *UNUSED(weights),
489                                 float *UNUSED(sub_weights), int UNUSED(count), void *dest)
490 {
491         MDisps *d = dest;
492         int i;
493
494         // XXX
495 #if 0
496         MDisps *d = dest;
497         MDisps *s = NULL;
498         int st, stl;
499         int i, x, y;
500         float crn[4][2];
501         float (*sw)[4] = NULL;
502
503         /* Initialize the destination */
504         for(i = 0; i < d->totdisp; ++i) {
505                 zero_v3(d->disps[i]);
506         }
507
508         /* For now, some restrictions on the input */
509         if(count != 1 || !sub_weights) return;
510
511         st = sqrt(d->totdisp);
512         stl = st - 1;
513
514         sw = (void*)sub_weights;
515         for(i = 0; i < 4; ++i) {
516                 crn[i][0] = 0 * sw[i][0] + stl * sw[i][1] + stl * sw[i][2] + 0 * sw[i][3];
517                 crn[i][1] = 0 * sw[i][0] + 0 * sw[i][1] + stl * sw[i][2] + stl * sw[i][3];
518         }
519
520         s = sources[0];
521         for(y = 0; y < st; ++y) {
522                 for(x = 0; x < st; ++x) {
523                         /* One suspects this code could be cleaner. */
524                         float xl = (float)x / (st - 1);
525                         float yl = (float)y / (st - 1);
526                         float mid1[2] = {crn[0][0] * (1 - xl) + crn[1][0] * xl,
527                                          crn[0][1] * (1 - xl) + crn[1][1] * xl};
528                         float mid2[2] = {crn[3][0] * (1 - xl) + crn[2][0] * xl,
529                                          crn[3][1] * (1 - xl) + crn[2][1] * xl};
530                         float mid3[2] = {mid1[0] * (1 - yl) + mid2[0] * yl,
531                                          mid1[1] * (1 - yl) + mid2[1] * yl};
532
533                         float srcdisp[3];
534
535                         mdisps_bilinear(srcdisp, s->disps, st, mid3[0], mid3[1]);
536                         copy_v3_v3(d->disps[y * st + x], srcdisp);
537                 }
538         }
539 #else
540         if(d->disps) {
541                 for(i = 0; i < d->totdisp; ++i)
542                         zero_v3(d->disps[i]);
543         }
544 #endif
545 }
546
547 static void layerCopy_mdisps(const void *source, void *dest, int count)
548 {
549         int i;
550         const MDisps *s = source;
551         MDisps *d = dest;
552
553         for(i = 0; i < count; ++i) {
554                 if(s[i].disps) {
555                         d[i].disps = MEM_dupallocN(s[i].disps);
556                         d[i].totdisp = s[i].totdisp;
557                 }
558                 else {
559                         d[i].disps = NULL;
560                         d[i].totdisp = 0;
561                 }
562                 
563         }
564 }
565
566 static void layerFree_mdisps(void *data, int count, int UNUSED(size))
567 {
568         int i;
569         MDisps *d = data;
570
571         for(i = 0; i < count; ++i) {
572                 if(d[i].disps)
573                         MEM_freeN(d[i].disps);
574                 d[i].disps = NULL;
575                 d[i].totdisp = 0;
576         }
577 }
578
579 static int layerRead_mdisps(CDataFile *cdf, void *data, int count)
580 {
581         MDisps *d = data;
582         int i;
583
584         for(i = 0; i < count; ++i) {
585                 if(!d[i].disps)
586                         d[i].disps = MEM_callocN(sizeof(float)*3*d[i].totdisp, "mdisps read");
587
588                 if(!cdf_read_data(cdf, d[i].totdisp*3*sizeof(float), d[i].disps)) {
589                         printf("failed to read multires displacement %d/%d %d\n", i, count, d[i].totdisp);
590                         return 0;
591                 }
592         }
593
594         return 1;
595 }
596
597 static int layerWrite_mdisps(CDataFile *cdf, void *data, int count)
598 {
599         MDisps *d = data;
600         int i;
601
602         for(i = 0; i < count; ++i) {
603                 if(!cdf_write_data(cdf, d[i].totdisp*3*sizeof(float), d[i].disps)) {
604                         printf("failed to write multires displacement %d/%d %d\n", i, count, d[i].totdisp);
605                         return 0;
606                 }
607         }
608
609         return 1;
610 }
611
612 static size_t layerFilesize_mdisps(CDataFile *UNUSED(cdf), void *data, int count)
613 {
614         MDisps *d = data;
615         size_t size = 0;
616         int i;
617
618         for(i = 0; i < count; ++i)
619                 size += d[i].totdisp*3*sizeof(float);
620
621         return size;
622 }
623
624 /* --------- */
625
626 static void layerDefault_mloopcol(void *data, int count)
627 {
628         static MLoopCol default_mloopcol = {255,255,255,255};
629         MLoopCol *mlcol = (MLoopCol*)data;
630         int i;
631         for(i = 0; i < count; i++)
632                 mlcol[i] = default_mloopcol;
633
634 }
635
636 static void layerInterp_mloopcol(void **sources, float *weights,
637                                 float *sub_weights, int count, void *dest)
638 {
639         MLoopCol *mc = dest;
640         int i;
641         float *sub_weight;
642         struct {
643                 float a;
644                 float r;
645                 float g;
646                 float b;
647         } col;
648         col.a = col.r = col.g = col.b = 0;
649
650         sub_weight = sub_weights;
651         for(i = 0; i < count; ++i){
652                 float weight = weights ? weights[i] : 1;
653                 MLoopCol *src = sources[i];
654                 if(sub_weights){
655                         col.a += src->a * (*sub_weight) * weight;
656                         col.r += src->r * (*sub_weight) * weight;
657                         col.g += src->g * (*sub_weight) * weight;
658                         col.b += src->b * (*sub_weight) * weight;
659                         sub_weight++;           
660                 } else {
661                         col.a += src->a * weight;
662                         col.r += src->r * weight;
663                         col.g += src->g * weight;
664                         col.b += src->b * weight;
665                 }
666         }
667         
668         /* Subdivide smooth or fractal can cause problems without clamping
669          * although weights should also not cause this situation */
670         CLAMP(col.a, 0.0f, 255.0f);
671         CLAMP(col.r, 0.0f, 255.0f);
672         CLAMP(col.g, 0.0f, 255.0f);
673         CLAMP(col.b, 0.0f, 255.0f);
674         
675         mc->a = (int)col.a;
676         mc->r = (int)col.r;
677         mc->g = (int)col.g;
678         mc->b = (int)col.b;
679 }
680 static void layerInterp_mloopuv(void **sources, float *weights,
681                                 float *sub_weights, int count, void *dest)
682 {
683         MLoopUV *mluv = dest;
684         int i;
685         float *sub_weight;
686         struct {
687                 float u;
688                 float v;
689         }uv;
690         uv.u = uv.v = 0.0;
691
692         sub_weight = sub_weights;
693         for(i = 0; i < count; ++i){
694                 float weight = weights ? weights[i] : 1;
695                 MLoopUV *src = sources[i];
696                 if(sub_weights){
697                         uv.u += src->uv[0] * (*sub_weight) * weight;
698                         uv.v += src->uv[1] * (*sub_weight) * weight;
699                         sub_weight++;           
700                 } else {
701                         uv.u += src->uv[0] * weight;
702                         uv.v += src->uv[1] * weight;
703                 }
704         }
705         mluv->uv[0] = uv.u;
706         mluv->uv[1] = uv.v;
707 }
708
709 static void layerInterp_mcol(void **sources, float *weights,
710                                                          float *sub_weights, int count, void *dest)
711 {
712         MCol *mc = dest;
713         int i, j, k;
714         struct {
715                 float a;
716                 float r;
717                 float g;
718                 float b;
719         } col[4];
720         float *sub_weight;
721
722         if(count <= 0) return;
723
724         memset(col, 0, sizeof(col));
725         
726         sub_weight = sub_weights;
727         for(i = 0; i < count; ++i) {
728                 float weight = weights ? weights[i] : 1;
729
730                 for(j = 0; j < 4; ++j) {
731                         if(sub_weights) {
732                                 MCol *src = sources[i];
733                                 for(k = 0; k < 4; ++k, ++sub_weight, ++src) {
734                                         col[j].a += src->a * (*sub_weight) * weight;
735                                         col[j].r += src->r * (*sub_weight) * weight;
736                                         col[j].g += src->g * (*sub_weight) * weight;
737                                         col[j].b += src->b * (*sub_weight) * weight;
738                                 }
739                         } else {
740                                 MCol *src = sources[i];
741                                 col[j].a += src[j].a * weight;
742                                 col[j].r += src[j].r * weight;
743                                 col[j].g += src[j].g * weight;
744                                 col[j].b += src[j].b * weight;
745                         }
746                 }
747         }
748
749         for(j = 0; j < 4; ++j) {
750                 
751                 /* Subdivide smooth or fractal can cause problems without clamping
752                  * although weights should also not cause this situation */
753                 CLAMP(col[j].a, 0.0f, 255.0f);
754                 CLAMP(col[j].r, 0.0f, 255.0f);
755                 CLAMP(col[j].g, 0.0f, 255.0f);
756                 CLAMP(col[j].b, 0.0f, 255.0f);
757                 
758                 mc[j].a = (int)col[j].a;
759                 mc[j].r = (int)col[j].r;
760                 mc[j].g = (int)col[j].g;
761                 mc[j].b = (int)col[j].b;
762         }
763 }
764
765 static void layerSwap_mcol(void *data, const int *corner_indices)
766 {
767         MCol *mcol = data;
768         MCol col[4];
769         int j;
770
771         for(j = 0; j < 4; ++j)
772                 col[j] = mcol[corner_indices[j]];
773
774         memcpy(mcol, col, sizeof(col));
775 }
776
777 static void layerDefault_mcol(void *data, int count)
778 {
779         static MCol default_mcol = {255, 255, 255, 255};
780         MCol *mcol = (MCol*)data;
781         int i;
782
783         for(i = 0; i < 4*count; i++)
784                 mcol[i] = default_mcol;
785 }
786
787
788
789 const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = {
790         {sizeof(MVert), "MVert", 1, NULL, NULL, NULL, NULL, NULL, NULL},
791         {sizeof(MSticky), "MSticky", 1, NULL, NULL, NULL, layerInterp_msticky, NULL,
792          NULL},
793         {sizeof(MDeformVert), "MDeformVert", 1, NULL, layerCopy_mdeformvert,
794          layerFree_mdeformvert, layerInterp_mdeformvert, NULL, NULL},
795         {sizeof(MEdge), "MEdge", 1, NULL, NULL, NULL, NULL, NULL, NULL},
796         {sizeof(MFace), "MFace", 1, NULL, NULL, NULL, NULL, NULL, NULL},
797         {sizeof(MTFace), "MTFace", 1, "UVTex", layerCopy_tface, NULL,
798          layerInterp_tface, layerSwap_tface, layerDefault_tface},
799         /* 4 MCol structs per face */
800         {sizeof(MCol)*4, "MCol", 4, "Col", NULL, NULL, layerInterp_mcol,
801          layerSwap_mcol, layerDefault_mcol},
802         {sizeof(int), "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
803         /* 3 floats per normal vector */
804         {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
805         {sizeof(int), "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
806         {sizeof(MFloatProperty), "MFloatProperty",1,"Float",NULL,NULL,NULL,NULL},
807         {sizeof(MIntProperty), "MIntProperty",1,"Int",NULL,NULL,NULL,NULL},
808         {sizeof(MStringProperty), "MStringProperty",1,"String",NULL,NULL,NULL,NULL},
809         {sizeof(OrigSpaceFace), "OrigSpaceFace", 1, "UVTex", layerCopy_origspace_face, NULL,
810          layerInterp_origspace_face, layerSwap_origspace_face, layerDefault_origspace_face},
811         {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
812         {sizeof(MTexPoly), "MTexPoly", 1, "Face Texture", NULL, NULL, NULL, NULL, NULL},
813         {sizeof(MLoopUV), "MLoopUV", 1, "UV coord", NULL, NULL, layerInterp_mloopuv, NULL, NULL},
814         {sizeof(MLoopCol), "MLoopCol", 1, "Col", NULL, NULL, layerInterp_mloopcol, NULL, layerDefault_mloopcol},
815         {sizeof(float)*3*4, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
816         {sizeof(MDisps), "MDisps", 1, NULL, layerCopy_mdisps,
817          layerFree_mdisps, layerInterp_mdisps, layerSwap_mdisps, NULL, layerRead_mdisps, layerWrite_mdisps, layerFilesize_mdisps},
818         {sizeof(MCol)*4, "MCol", 4, "WeightCol", NULL, NULL, layerInterp_mcol,
819          layerSwap_mcol, layerDefault_mcol},
820          {sizeof(MCol)*4, "MCol", 4, "IDCol", NULL, NULL, layerInterp_mcol,
821          layerSwap_mcol, layerDefault_mcol},
822          {sizeof(MCol)*4, "MCol", 4, "TexturedCol", NULL, NULL, layerInterp_mcol,
823          layerSwap_mcol, layerDefault_mcol},
824         {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL}
825 };
826
827 const char *LAYERTYPENAMES[CD_NUMTYPES] = {
828         /*   0-4 */ "CDMVert", "CDMSticky", "CDMDeformVert", "CDMEdge", "CDMFace",
829         /*   5-9 */ "CDMTFace", "CDMCol", "CDOrigIndex", "CDNormal", "CDFlags",
830         /* 10-14 */ "CDMFloatProperty", "CDMIntProperty","CDMStringProperty", "CDOrigSpace", "CDOrco",
831         /* 15-19 */ "CDMTexPoly", "CDMLoopUV", "CDMloopCol", "CDTangent", "CDMDisps",
832         /* 20-23 */"CDWeightMCol", "CDIDMCol", "CDTextureMCol", "CDClothOrco"
833 };
834
835 const CustomDataMask CD_MASK_BAREMESH =
836         CD_MASK_MVERT | CD_MASK_MEDGE | CD_MASK_MFACE;
837 const CustomDataMask CD_MASK_MESH =
838         CD_MASK_MVERT | CD_MASK_MEDGE | CD_MASK_MFACE |
839         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE | CD_MASK_MCOL |
840         CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR | CD_MASK_MDISPS;
841 const CustomDataMask CD_MASK_EDITMESH =
842         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE |
843         CD_MASK_MCOL|CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR | CD_MASK_MDISPS;
844 const CustomDataMask CD_MASK_DERIVEDMESH =
845         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE |
846         CD_MASK_MCOL | CD_MASK_ORIGINDEX | CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_CLOTH_ORCO |
847         CD_MASK_PROP_STR | CD_MASK_ORIGSPACE | CD_MASK_ORCO | CD_MASK_TANGENT | CD_MASK_WEIGHT_MCOL;
848 const CustomDataMask CD_MASK_BMESH = 
849         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR;
850 const CustomDataMask CD_MASK_FACECORNERS =
851         CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_MTEXPOLY | CD_MASK_MLOOPUV |
852         CD_MASK_MLOOPCOL;
853
854
855 static const LayerTypeInfo *layerType_getInfo(int type)
856 {
857         if(type < 0 || type >= CD_NUMTYPES) return NULL;
858
859         return &LAYERTYPEINFO[type];
860 }
861
862 static const char *layerType_getName(int type)
863 {
864         if(type < 0 || type >= CD_NUMTYPES) return NULL;
865
866         return LAYERTYPENAMES[type];
867 }
868
869 /********************* CustomData functions *********************/
870 static void customData_update_offsets(CustomData *data);
871
872 static CustomDataLayer *customData_add_layer__internal(CustomData *data,
873         int type, int alloctype, void *layerdata, int totelem, const char *name);
874
875 void CustomData_merge(const struct CustomData *source, struct CustomData *dest,
876                                           CustomDataMask mask, int alloctype, int totelem)
877 {
878         const LayerTypeInfo *typeInfo;
879         CustomDataLayer *layer, *newlayer;
880         int i, type, number = 0, lasttype = -1, lastactive = 0, lastrender = 0, lastclone = 0, lastmask = 0, lastflag = 0;
881
882         for(i = 0; i < source->totlayer; ++i) {
883                 layer = &source->layers[i];
884                 typeInfo = layerType_getInfo(layer->type);
885
886                 type = layer->type;
887
888                 if (type != lasttype) {
889                         number = 0;
890                         lastactive = layer->active;
891                         lastrender = layer->active_rnd;
892                         lastclone = layer->active_clone;
893                         lastmask = layer->active_mask;
894                         lasttype = type;
895                         lastflag = layer->flag;
896                 }
897                 else
898                         number++;
899
900                 if(lastflag & CD_FLAG_NOCOPY) continue;
901                 else if(!((int)mask & (int)(1 << (int)type))) continue;
902                 else if(number < CustomData_number_of_layers(dest, type)) continue;
903
904                 if((alloctype == CD_ASSIGN) && (lastflag & CD_FLAG_NOFREE))
905                         newlayer = customData_add_layer__internal(dest, type, CD_REFERENCE,
906                                 layer->data, totelem, layer->name);
907                 else
908                         newlayer = customData_add_layer__internal(dest, type, alloctype,
909                                 layer->data, totelem, layer->name);
910                 
911                 if(newlayer) {
912                         newlayer->active = lastactive;
913                         newlayer->active_rnd = lastrender;
914                         newlayer->active_clone = lastclone;
915                         newlayer->active_mask = lastmask;
916                         newlayer->flag |= lastflag & (CD_FLAG_EXTERNAL|CD_FLAG_IN_MEMORY);
917                 }
918         }
919 }
920
921 void CustomData_copy(const struct CustomData *source, struct CustomData *dest,
922                                          CustomDataMask mask, int alloctype, int totelem)
923 {
924         memset(dest, 0, sizeof(*dest));
925
926         if(source->external)
927                 dest->external= MEM_dupallocN(source->external);
928
929         CustomData_merge(source, dest, mask, alloctype, totelem);
930 }
931
932 static void customData_free_layer__internal(CustomDataLayer *layer, int totelem)
933 {
934         const LayerTypeInfo *typeInfo;
935
936         if(!(layer->flag & CD_FLAG_NOFREE) && layer->data) {
937                 typeInfo = layerType_getInfo(layer->type);
938
939                 if(typeInfo->free)
940                         typeInfo->free(layer->data, totelem, typeInfo->size);
941
942                 if(layer->data)
943                         MEM_freeN(layer->data);
944         }
945 }
946
947 static void CustomData_external_free(CustomData *data)
948 {
949         if(data->external) {
950                 MEM_freeN(data->external);
951                 data->external= NULL;
952         }
953 }
954
955 void CustomData_free(CustomData *data, int totelem)
956 {
957         int i;
958
959         for(i = 0; i < data->totlayer; ++i)
960                 customData_free_layer__internal(&data->layers[i], totelem);
961
962         if(data->layers)
963                 MEM_freeN(data->layers);
964         
965         CustomData_external_free(data);
966         
967         memset(data, 0, sizeof(*data));
968 }
969
970 static void customData_update_offsets(CustomData *data)
971 {
972         const LayerTypeInfo *typeInfo;
973         int i, offset = 0;
974
975         for(i = 0; i < data->totlayer; ++i) {
976                 typeInfo = layerType_getInfo(data->layers[i].type);
977
978                 data->layers[i].offset = offset;
979                 offset += typeInfo->size;
980         }
981
982         data->totsize = offset;
983 }
984
985 int CustomData_get_layer_index(const CustomData *data, int type)
986 {
987         int i; 
988
989         for(i=0; i < data->totlayer; ++i)
990                 if(data->layers[i].type == type)
991                         return i;
992
993         return -1;
994 }
995
996 int CustomData_get_named_layer_index(const CustomData *data, int type, char *name)
997 {
998         int i;
999
1000         for(i=0; i < data->totlayer; ++i)
1001                 if(data->layers[i].type == type && strcmp(data->layers[i].name, name)==0)
1002                         return i;
1003
1004         return -1;
1005 }
1006
1007 int CustomData_get_active_layer_index(const CustomData *data, int type)
1008 {
1009         int i;
1010
1011         for(i=0; i < data->totlayer; ++i)
1012                 if(data->layers[i].type == type)
1013                         return i + data->layers[i].active;
1014
1015         return -1;
1016 }
1017
1018 int CustomData_get_render_layer_index(const CustomData *data, int type)
1019 {
1020         int i;
1021
1022         for(i=0; i < data->totlayer; ++i)
1023                 if(data->layers[i].type == type)
1024                         return i + data->layers[i].active_rnd;
1025
1026         return -1;
1027 }
1028
1029 int CustomData_get_clone_layer_index(const CustomData *data, int type)
1030 {
1031         int i;
1032
1033         for(i=0; i < data->totlayer; ++i)
1034                 if(data->layers[i].type == type)
1035                         return i + data->layers[i].active_clone;
1036
1037         return -1;
1038 }
1039
1040 int CustomData_get_stencil_layer_index(const CustomData *data, int type)
1041 {
1042         int i;
1043
1044         for(i=0; i < data->totlayer; ++i)
1045                 if(data->layers[i].type == type)
1046                         return i + data->layers[i].active_mask;
1047
1048         return -1;
1049 }
1050
1051 int CustomData_get_active_layer(const CustomData *data, int type)
1052 {
1053         int i;
1054
1055         for(i=0; i < data->totlayer; ++i)
1056                 if(data->layers[i].type == type)
1057                         return data->layers[i].active;
1058
1059         return -1;
1060 }
1061
1062 int CustomData_get_render_layer(const CustomData *data, int type)
1063 {
1064         int i;
1065
1066         for(i=0; i < data->totlayer; ++i)
1067                 if(data->layers[i].type == type)
1068                         return data->layers[i].active_rnd;
1069
1070         return -1;
1071 }
1072
1073 int CustomData_get_clone_layer(const CustomData *data, int type)
1074 {
1075         int i;
1076
1077         for(i=0; i < data->totlayer; ++i)
1078                 if(data->layers[i].type == type)
1079                         return data->layers[i].active_clone;
1080
1081         return -1;
1082 }
1083
1084 int CustomData_get_stencil_layer(const CustomData *data, int type)
1085 {
1086         int i;
1087
1088         for(i=0; i < data->totlayer; ++i)
1089                 if(data->layers[i].type == type)
1090                         return data->layers[i].active_mask;
1091
1092         return -1;
1093 }
1094
1095 void CustomData_set_layer_active(CustomData *data, int type, int n)
1096 {
1097         int i;
1098
1099         for(i=0; i < data->totlayer; ++i)
1100                 if(data->layers[i].type == type)
1101                         data->layers[i].active = n;
1102 }
1103
1104 void CustomData_set_layer_render(CustomData *data, int type, int n)
1105 {
1106         int i;
1107
1108         for(i=0; i < data->totlayer; ++i)
1109                 if(data->layers[i].type == type)
1110                         data->layers[i].active_rnd = n;
1111 }
1112
1113 void CustomData_set_layer_clone(CustomData *data, int type, int n)
1114 {
1115         int i;
1116
1117         for(i=0; i < data->totlayer; ++i)
1118                 if(data->layers[i].type == type)
1119                         data->layers[i].active_clone = n;
1120 }
1121
1122 void CustomData_set_layer_stencil(CustomData *data, int type, int n)
1123 {
1124         int i;
1125
1126         for(i=0; i < data->totlayer; ++i)
1127                 if(data->layers[i].type == type)
1128                         data->layers[i].active_mask = n;
1129 }
1130
1131 /* for using with an index from CustomData_get_active_layer_index and CustomData_get_render_layer_index */
1132 void CustomData_set_layer_active_index(CustomData *data, int type, int n)
1133 {
1134         int i;
1135
1136         for(i=0; i < data->totlayer; ++i)
1137                 if(data->layers[i].type == type)
1138                         data->layers[i].active = n-i;
1139 }
1140
1141 void CustomData_set_layer_render_index(CustomData *data, int type, int n)
1142 {
1143         int i;
1144
1145         for(i=0; i < data->totlayer; ++i)
1146                 if(data->layers[i].type == type)
1147                         data->layers[i].active_rnd = n-i;
1148 }
1149
1150 void CustomData_set_layer_clone_index(CustomData *data, int type, int n)
1151 {
1152         int i;
1153
1154         for(i=0; i < data->totlayer; ++i)
1155                 if(data->layers[i].type == type)
1156                         data->layers[i].active_clone = n-i;
1157 }
1158
1159 void CustomData_set_layer_stencil_index(CustomData *data, int type, int n)
1160 {
1161         int i;
1162
1163         for(i=0; i < data->totlayer; ++i)
1164                 if(data->layers[i].type == type)
1165                         data->layers[i].active_mask = n-i;
1166 }
1167
1168 void CustomData_set_layer_flag(struct CustomData *data, int type, int flag)
1169 {
1170         int i;
1171
1172         for(i=0; i < data->totlayer; ++i)
1173                 if(data->layers[i].type == type)
1174                         data->layers[i].flag |= flag;
1175 }
1176
1177 static int customData_resize(CustomData *data, int amount)
1178 {
1179         CustomDataLayer *tmp = MEM_callocN(sizeof(*tmp)*(data->maxlayer + amount),
1180                                                                            "CustomData->layers");
1181         if(!tmp) return 0;
1182
1183         data->maxlayer += amount;
1184         if (data->layers) {
1185                 memcpy(tmp, data->layers, sizeof(*tmp) * data->totlayer);
1186                 MEM_freeN(data->layers);
1187         }
1188         data->layers = tmp;
1189
1190         return 1;
1191 }
1192
1193 static CustomDataLayer *customData_add_layer__internal(CustomData *data,
1194         int type, int alloctype, void *layerdata, int totelem, const char *name)
1195 {
1196         const LayerTypeInfo *typeInfo= layerType_getInfo(type);
1197         int size = typeInfo->size * totelem, flag = 0, index = data->totlayer;
1198         void *newlayerdata;
1199
1200         if (!typeInfo->defaultname && CustomData_has_layer(data, type))
1201                 return &data->layers[CustomData_get_layer_index(data, type)];
1202
1203         if((alloctype == CD_ASSIGN) || (alloctype == CD_REFERENCE)) {
1204                 newlayerdata = layerdata;
1205         }
1206         else {
1207                 newlayerdata = MEM_callocN(size, layerType_getName(type));
1208                 if(!newlayerdata)
1209                         return NULL;
1210         }
1211
1212         if (alloctype == CD_DUPLICATE) {
1213                 if(typeInfo->copy)
1214                         typeInfo->copy(layerdata, newlayerdata, totelem);
1215                 else
1216                         memcpy(newlayerdata, layerdata, size);
1217         }
1218         else if (alloctype == CD_DEFAULT) {
1219                 if(typeInfo->set_default)
1220                         typeInfo->set_default((char*)newlayerdata, totelem);
1221         }
1222         else if (alloctype == CD_REFERENCE)
1223                 flag |= CD_FLAG_NOFREE;
1224
1225         if(index >= data->maxlayer) {
1226                 if(!customData_resize(data, CUSTOMDATA_GROW)) {
1227                         if(newlayerdata != layerdata)
1228                                 MEM_freeN(newlayerdata);
1229                         return NULL;
1230                 }
1231         }
1232         
1233         data->totlayer++;
1234
1235         /* keep layers ordered by type */
1236         for( ; index > 0 && data->layers[index - 1].type > type; --index)
1237                 data->layers[index] = data->layers[index - 1];
1238
1239         data->layers[index].type = type;
1240         data->layers[index].flag = flag;
1241         data->layers[index].data = newlayerdata;
1242
1243         if(name || (name=typeInfo->defaultname)) {
1244                 strcpy(data->layers[index].name, name);
1245                 CustomData_set_layer_unique_name(data, index);
1246         }
1247         else
1248                 data->layers[index].name[0] = '\0';
1249
1250         if(index > 0 && data->layers[index-1].type == type) {
1251                 data->layers[index].active = data->layers[index-1].active;
1252                 data->layers[index].active_rnd = data->layers[index-1].active_rnd;
1253                 data->layers[index].active_clone = data->layers[index-1].active_clone;
1254                 data->layers[index].active_mask = data->layers[index-1].active_mask;
1255         } else {
1256                 data->layers[index].active = 0;
1257                 data->layers[index].active_rnd = 0;
1258                 data->layers[index].active_clone = 0;
1259                 data->layers[index].active_mask = 0;
1260         }
1261         
1262         customData_update_offsets(data);
1263
1264         return &data->layers[index];
1265 }
1266
1267 void *CustomData_add_layer(CustomData *data, int type, int alloctype,
1268                                                    void *layerdata, int totelem)
1269 {
1270         CustomDataLayer *layer;
1271         const LayerTypeInfo *typeInfo= layerType_getInfo(type);
1272         
1273         layer = customData_add_layer__internal(data, type, alloctype, layerdata,
1274                                                                                    totelem, typeInfo->defaultname);
1275
1276         if(layer)
1277                 return layer->data;
1278
1279         return NULL;
1280 }
1281
1282 /*same as above but accepts a name*/
1283 void *CustomData_add_layer_named(CustomData *data, int type, int alloctype,
1284                                                    void *layerdata, int totelem, const char *name)
1285 {
1286         CustomDataLayer *layer;
1287         
1288         layer = customData_add_layer__internal(data, type, alloctype, layerdata,
1289                                                                                    totelem, name);
1290
1291         if(layer)
1292                 return layer->data;
1293
1294         return NULL;
1295 }
1296
1297
1298 int CustomData_free_layer(CustomData *data, int type, int totelem, int index)
1299 {
1300         int i;
1301         
1302         if (index < 0) return 0;
1303
1304         customData_free_layer__internal(&data->layers[index], totelem);
1305
1306         for (i=index+1; i < data->totlayer; ++i)
1307                 data->layers[i-1] = data->layers[i];
1308
1309         data->totlayer--;
1310
1311         /* if layer was last of type in array, set new active layer */
1312         if ((index >= data->totlayer) || (data->layers[index].type != type)) {
1313                 i = CustomData_get_layer_index(data, type);
1314                 
1315                 if (i >= 0)
1316                         for (; i < data->totlayer && data->layers[i].type == type; i++) {
1317                                 data->layers[i].active--;
1318                                 data->layers[i].active_rnd--;
1319                                 data->layers[i].active_clone--;
1320                                 data->layers[i].active_mask--;
1321                         }
1322         }
1323
1324         if (data->totlayer <= data->maxlayer-CUSTOMDATA_GROW)
1325                 customData_resize(data, -CUSTOMDATA_GROW);
1326
1327         customData_update_offsets(data);
1328
1329         return 1;
1330 }
1331
1332 int CustomData_free_layer_active(CustomData *data, int type, int totelem)
1333 {
1334         int index = 0;
1335         index = CustomData_get_active_layer_index(data, type);
1336         if (index < 0) return 0;
1337         return CustomData_free_layer(data, type, totelem, index);
1338 }
1339
1340
1341 void CustomData_free_layers(CustomData *data, int type, int totelem)
1342 {
1343         while (CustomData_has_layer(data, type))
1344                 CustomData_free_layer_active(data, type, totelem);
1345 }
1346
1347 int CustomData_has_layer(const CustomData *data, int type)
1348 {
1349         return (CustomData_get_layer_index(data, type) != -1);
1350 }
1351
1352 int CustomData_number_of_layers(const CustomData *data, int type)
1353 {
1354         int i, number = 0;
1355
1356         for(i = 0; i < data->totlayer; i++)
1357                 if(data->layers[i].type == type)
1358                         number++;
1359         
1360         return number;
1361 }
1362
1363 void *CustomData_duplicate_referenced_layer(struct CustomData *data, int type)
1364 {
1365         CustomDataLayer *layer;
1366         int layer_index;
1367
1368         /* get the layer index of the first layer of type */
1369         layer_index = CustomData_get_active_layer_index(data, type);
1370         if(layer_index < 0) return NULL;
1371
1372         layer = &data->layers[layer_index];
1373
1374         if (layer->flag & CD_FLAG_NOFREE) {
1375                 layer->data = MEM_dupallocN(layer->data);
1376                 layer->flag &= ~CD_FLAG_NOFREE;
1377         }
1378
1379         return layer->data;
1380 }
1381
1382 void *CustomData_duplicate_referenced_layer_named(struct CustomData *data,
1383                                                                                                   int type, char *name)
1384 {
1385         CustomDataLayer *layer;
1386         int layer_index;
1387
1388         /* get the layer index of the desired layer */
1389         layer_index = CustomData_get_named_layer_index(data, type, name);
1390         if(layer_index < 0) return NULL;
1391
1392         layer = &data->layers[layer_index];
1393
1394         if (layer->flag & CD_FLAG_NOFREE) {
1395                 layer->data = MEM_dupallocN(layer->data);
1396                 layer->flag &= ~CD_FLAG_NOFREE;
1397         }
1398
1399         return layer->data;
1400 }
1401
1402 void CustomData_free_temporary(CustomData *data, int totelem)
1403 {
1404         CustomDataLayer *layer;
1405         int i, j;
1406
1407         for(i = 0, j = 0; i < data->totlayer; ++i) {
1408                 layer = &data->layers[i];
1409
1410                 if (i != j)
1411                         data->layers[j] = data->layers[i];
1412
1413                 if ((layer->flag & CD_FLAG_TEMPORARY) == CD_FLAG_TEMPORARY)
1414                         customData_free_layer__internal(layer, totelem);
1415                 else
1416                         j++;
1417         }
1418
1419         data->totlayer = j;
1420
1421         if(data->totlayer <= data->maxlayer-CUSTOMDATA_GROW)
1422                 customData_resize(data, -CUSTOMDATA_GROW);
1423
1424         customData_update_offsets(data);
1425 }
1426
1427 void CustomData_set_only_copy(const struct CustomData *data,
1428                                                           CustomDataMask mask)
1429 {
1430         int i;
1431
1432         for(i = 0; i < data->totlayer; ++i)
1433                 if(!((int)mask & (int)(1 << (int)data->layers[i].type)))
1434                         data->layers[i].flag |= CD_FLAG_NOCOPY;
1435 }
1436
1437 void CustomData_copy_data(const CustomData *source, CustomData *dest,
1438                                                   int source_index, int dest_index, int count)
1439 {
1440         const LayerTypeInfo *typeInfo;
1441         int src_i, dest_i;
1442         int src_offset;
1443         int dest_offset;
1444
1445         /* copies a layer at a time */
1446         dest_i = 0;
1447         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1448
1449                 /* find the first dest layer with type >= the source type
1450                  * (this should work because layers are ordered by type)
1451                  */
1452                 while(dest_i < dest->totlayer
1453                           && dest->layers[dest_i].type < source->layers[src_i].type)
1454                         ++dest_i;
1455
1456                 /* if there are no more dest layers, we're done */
1457                 if(dest_i >= dest->totlayer) return;
1458
1459                 /* if we found a matching layer, copy the data */
1460                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1461                         char *src_data = source->layers[src_i].data;
1462                         char *dest_data = dest->layers[dest_i].data;
1463
1464                         typeInfo = layerType_getInfo(source->layers[src_i].type);
1465
1466                         src_offset = source_index * typeInfo->size;
1467                         dest_offset = dest_index * typeInfo->size;
1468
1469                         if(typeInfo->copy)
1470                                 typeInfo->copy(src_data + src_offset,
1471                                                                 dest_data + dest_offset,
1472                                                                 count);
1473                         else
1474                                 memcpy(dest_data + dest_offset,
1475                                            src_data + src_offset,
1476                                            count * typeInfo->size);
1477
1478                         /* if there are multiple source & dest layers of the same type,
1479                          * we don't want to copy all source layers to the same dest, so
1480                          * increment dest_i
1481                          */
1482                         ++dest_i;
1483                 }
1484         }
1485 }
1486
1487 void CustomData_free_elem(CustomData *data, int index, int count)
1488 {
1489         int i;
1490         const LayerTypeInfo *typeInfo;
1491
1492         for(i = 0; i < data->totlayer; ++i) {
1493                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
1494                         typeInfo = layerType_getInfo(data->layers[i].type);
1495
1496                         if(typeInfo->free) {
1497                                 int offset = typeInfo->size * index;
1498
1499                                 typeInfo->free((char *)data->layers[i].data + offset,
1500                                                            count, typeInfo->size);
1501                         }
1502                 }
1503         }
1504 }
1505
1506 #define SOURCE_BUF_SIZE 100
1507
1508 void CustomData_interp(const CustomData *source, CustomData *dest,
1509                                            int *src_indices, float *weights, float *sub_weights,
1510                                            int count, int dest_index)
1511 {
1512         int src_i, dest_i;
1513         int dest_offset;
1514         int j;
1515         void *source_buf[SOURCE_BUF_SIZE];
1516         void **sources = source_buf;
1517
1518         /* slow fallback in case we're interpolating a ridiculous number of
1519          * elements
1520          */
1521         if(count > SOURCE_BUF_SIZE)
1522                 sources = MEM_callocN(sizeof(*sources) * count,
1523                                                           "CustomData_interp sources");
1524
1525         /* interpolates a layer at a time */
1526         dest_i = 0;
1527         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1528                 const LayerTypeInfo *typeInfo= layerType_getInfo(source->layers[src_i].type);
1529                 if(!typeInfo->interp) continue;
1530
1531                 /* find the first dest layer with type >= the source type
1532                  * (this should work because layers are ordered by type)
1533                  */
1534                 while(dest_i < dest->totlayer
1535                           && dest->layers[dest_i].type < source->layers[src_i].type)
1536                         ++dest_i;
1537
1538                 /* if there are no more dest layers, we're done */
1539                 if(dest_i >= dest->totlayer) return;
1540
1541                 /* if we found a matching layer, copy the data */
1542                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1543                         void *src_data = source->layers[src_i].data;
1544
1545                         for(j = 0; j < count; ++j)
1546                                 sources[j] = (char *)src_data
1547                                                          + typeInfo->size * src_indices[j];
1548
1549                         dest_offset = dest_index * typeInfo->size;
1550
1551                         typeInfo->interp(sources, weights, sub_weights, count,
1552                                                    (char *)dest->layers[dest_i].data + dest_offset);
1553
1554                         /* if there are multiple source & dest layers of the same type,
1555                          * we don't want to copy all source layers to the same dest, so
1556                          * increment dest_i
1557                          */
1558                         ++dest_i;
1559                 }
1560         }
1561
1562         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
1563 }
1564
1565 void CustomData_swap(struct CustomData *data, int index, const int *corner_indices)
1566 {
1567         const LayerTypeInfo *typeInfo;
1568         int i;
1569
1570         for(i = 0; i < data->totlayer; ++i) {
1571                 typeInfo = layerType_getInfo(data->layers[i].type);
1572
1573                 if(typeInfo->swap) {
1574                         int offset = typeInfo->size * index;
1575
1576                         typeInfo->swap((char *)data->layers[i].data + offset, corner_indices);
1577                 }
1578         }
1579 }
1580
1581 void *CustomData_get(const CustomData *data, int index, int type)
1582 {
1583         int offset;
1584         int layer_index;
1585         
1586         /* get the layer index of the active layer of type */
1587         layer_index = CustomData_get_active_layer_index(data, type);
1588         if(layer_index < 0) return NULL;
1589
1590         /* get the offset of the desired element */
1591         offset = layerType_getInfo(type)->size * index;
1592
1593         return (char *)data->layers[layer_index].data + offset;
1594 }
1595
1596 void *CustomData_get_layer(const CustomData *data, int type)
1597 {
1598         /* get the layer index of the active layer of type */
1599         int layer_index = CustomData_get_active_layer_index(data, type);
1600         if(layer_index < 0) return NULL;
1601
1602         return data->layers[layer_index].data;
1603 }
1604
1605 void *CustomData_get_layer_n(const CustomData *data, int type, int n)
1606 {
1607         /* get the layer index of the active layer of type */
1608         int layer_index = CustomData_get_layer_index(data, type);
1609         if(layer_index < 0) return NULL;
1610
1611         return data->layers[layer_index+n].data;
1612 }
1613
1614 void *CustomData_get_layer_named(const struct CustomData *data, int type,
1615                                                                  char *name)
1616 {
1617         int layer_index = CustomData_get_named_layer_index(data, type, name);
1618         if(layer_index < 0) return NULL;
1619
1620         return data->layers[layer_index].data;
1621 }
1622
1623 void *CustomData_set_layer(const CustomData *data, int type, void *ptr)
1624 {
1625         /* get the layer index of the first layer of type */
1626         int layer_index = CustomData_get_active_layer_index(data, type);
1627
1628         if(layer_index < 0) return NULL;
1629
1630         data->layers[layer_index].data = ptr;
1631
1632         return ptr;
1633 }
1634
1635 void *CustomData_set_layer_n(const struct CustomData *data, int type, int n, void *ptr)
1636 {
1637         /* get the layer index of the first layer of type */
1638         int layer_index = CustomData_get_layer_index(data, type);
1639         if(layer_index < 0) return NULL;
1640
1641         data->layers[layer_index+n].data = ptr;
1642
1643         return ptr;
1644 }
1645
1646 void CustomData_set(const CustomData *data, int index, int type, void *source)
1647 {
1648         void *dest = CustomData_get(data, index, type);
1649         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1650
1651         if(!dest) return;
1652
1653         if(typeInfo->copy)
1654                 typeInfo->copy(source, dest, 1);
1655         else
1656                 memcpy(dest, source, typeInfo->size);
1657 }
1658
1659 /* EditMesh functions */
1660
1661 void CustomData_em_free_block(CustomData *data, void **block)
1662 {
1663         const LayerTypeInfo *typeInfo;
1664         int i;
1665
1666         if(!*block) return;
1667
1668         for(i = 0; i < data->totlayer; ++i) {
1669                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
1670                         typeInfo = layerType_getInfo(data->layers[i].type);
1671
1672                         if(typeInfo->free) {
1673                                 int offset = data->layers[i].offset;
1674                                 typeInfo->free((char*)*block + offset, 1, typeInfo->size);
1675                         }
1676                 }
1677         }
1678
1679         MEM_freeN(*block);
1680         *block = NULL;
1681 }
1682
1683 static void CustomData_em_alloc_block(CustomData *data, void **block)
1684 {
1685         /* TODO: optimize free/alloc */
1686
1687         if (*block)
1688                 CustomData_em_free_block(data, block);
1689
1690         if (data->totsize > 0)
1691                 *block = MEM_callocN(data->totsize, "CustomData EM block");
1692         else
1693                 *block = NULL;
1694 }
1695
1696 void CustomData_em_copy_data(const CustomData *source, CustomData *dest,
1697                                                         void *src_block, void **dest_block)
1698 {
1699         const LayerTypeInfo *typeInfo;
1700         int dest_i, src_i;
1701
1702         if (!*dest_block)
1703                 CustomData_em_alloc_block(dest, dest_block);
1704         
1705         /* copies a layer at a time */
1706         dest_i = 0;
1707         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1708
1709                 /* find the first dest layer with type >= the source type
1710                  * (this should work because layers are ordered by type)
1711                  */
1712                 while(dest_i < dest->totlayer
1713                           && dest->layers[dest_i].type < source->layers[src_i].type)
1714                         ++dest_i;
1715
1716                 /* if there are no more dest layers, we're done */
1717                 if(dest_i >= dest->totlayer) return;
1718
1719                 /* if we found a matching layer, copy the data */
1720                 if(dest->layers[dest_i].type == source->layers[src_i].type &&
1721                         strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
1722                         char *src_data = (char*)src_block + source->layers[src_i].offset;
1723                         char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
1724
1725                         typeInfo = layerType_getInfo(source->layers[src_i].type);
1726
1727                         if(typeInfo->copy)
1728                                 typeInfo->copy(src_data, dest_data, 1);
1729                         else
1730                                 memcpy(dest_data, src_data, typeInfo->size);
1731
1732                         /* if there are multiple source & dest layers of the same type,
1733                          * we don't want to copy all source layers to the same dest, so
1734                          * increment dest_i
1735                          */
1736                         ++dest_i;
1737                 }
1738         }
1739 }
1740
1741 void *CustomData_em_get(const CustomData *data, void *block, int type)
1742 {
1743         int layer_index;
1744         
1745         /* get the layer index of the first layer of type */
1746         layer_index = CustomData_get_active_layer_index(data, type);
1747         if(layer_index < 0) return NULL;
1748
1749         return (char *)block + data->layers[layer_index].offset;
1750 }
1751
1752 void *CustomData_em_get_n(const CustomData *data, void *block, int type, int n)
1753 {
1754         int layer_index;
1755         
1756         /* get the layer index of the first layer of type */
1757         layer_index = CustomData_get_layer_index(data, type);
1758         if(layer_index < 0) return NULL;
1759
1760         return (char *)block + data->layers[layer_index+n].offset;
1761 }
1762
1763 void CustomData_em_set(CustomData *data, void *block, int type, void *source)
1764 {
1765         void *dest = CustomData_em_get(data, block, type);
1766         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1767
1768         if(!dest) return;
1769
1770         if(typeInfo->copy)
1771                 typeInfo->copy(source, dest, 1);
1772         else
1773                 memcpy(dest, source, typeInfo->size);
1774 }
1775
1776 void CustomData_em_set_n(CustomData *data, void *block, int type, int n, void *source)
1777 {
1778         void *dest = CustomData_em_get_n(data, block, type, n);
1779         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1780
1781         if(!dest) return;
1782
1783         if(typeInfo->copy)
1784                 typeInfo->copy(source, dest, 1);
1785         else
1786                 memcpy(dest, source, typeInfo->size);
1787 }
1788
1789 void CustomData_em_interp(CustomData *data, void **src_blocks, float *weights,
1790                                                   float *sub_weights, int count, void *dest_block)
1791 {
1792         int i, j;
1793         void *source_buf[SOURCE_BUF_SIZE];
1794         void **sources = source_buf;
1795
1796         /* slow fallback in case we're interpolating a ridiculous number of
1797          * elements
1798          */
1799         if(count > SOURCE_BUF_SIZE)
1800                 sources = MEM_callocN(sizeof(*sources) * count,
1801                                                           "CustomData_interp sources");
1802
1803         /* interpolates a layer at a time */
1804         for(i = 0; i < data->totlayer; ++i) {
1805                 CustomDataLayer *layer = &data->layers[i];
1806                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
1807
1808                 if(typeInfo->interp) {
1809                         for(j = 0; j < count; ++j)
1810                                 sources[j] = (char *)src_blocks[j] + layer->offset;
1811
1812                         typeInfo->interp(sources, weights, sub_weights, count,
1813                                                           (char *)dest_block + layer->offset);
1814                 }
1815         }
1816
1817         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
1818 }
1819
1820 void CustomData_em_set_default(CustomData *data, void **block)
1821 {
1822         const LayerTypeInfo *typeInfo;
1823         int i;
1824
1825         if (!*block)
1826                 CustomData_em_alloc_block(data, block);
1827
1828         for(i = 0; i < data->totlayer; ++i) {
1829                 int offset = data->layers[i].offset;
1830
1831                 typeInfo = layerType_getInfo(data->layers[i].type);
1832
1833                 if(typeInfo->set_default)
1834                         typeInfo->set_default((char*)*block + offset, 1);
1835         }
1836 }
1837
1838 void CustomData_to_em_block(const CustomData *source, CustomData *dest,
1839                                                         int src_index, void **dest_block)
1840 {
1841         const LayerTypeInfo *typeInfo;
1842         int dest_i, src_i, src_offset;
1843
1844         if (!*dest_block)
1845                 CustomData_em_alloc_block(dest, dest_block);
1846         
1847         /* copies a layer at a time */
1848         dest_i = 0;
1849         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1850
1851                 /* find the first dest layer with type >= the source type
1852                  * (this should work because layers are ordered by type)
1853                  */
1854                 while(dest_i < dest->totlayer
1855                           && dest->layers[dest_i].type < source->layers[src_i].type)
1856                         ++dest_i;
1857
1858                 /* if there are no more dest layers, we're done */
1859                 if(dest_i >= dest->totlayer) return;
1860
1861                 /* if we found a matching layer, copy the data */
1862                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1863                         int offset = dest->layers[dest_i].offset;
1864                         char *src_data = source->layers[src_i].data;
1865                         char *dest_data = (char*)*dest_block + offset;
1866
1867                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
1868                         src_offset = src_index * typeInfo->size;
1869
1870                         if(typeInfo->copy)
1871                                 typeInfo->copy(src_data + src_offset, dest_data, 1);
1872                         else
1873                                 memcpy(dest_data, src_data + src_offset, typeInfo->size);
1874
1875                         /* if there are multiple source & dest layers of the same type,
1876                          * we don't want to copy all source layers to the same dest, so
1877                          * increment dest_i
1878                          */
1879                         ++dest_i;
1880                 }
1881         }
1882 }
1883
1884 void CustomData_from_em_block(const CustomData *source, CustomData *dest,
1885                                                           void *src_block, int dest_index)
1886 {
1887         const LayerTypeInfo *typeInfo;
1888         int dest_i, src_i, dest_offset;
1889
1890         /* copies a layer at a time */
1891         dest_i = 0;
1892         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1893
1894                 /* find the first dest layer with type >= the source type
1895                  * (this should work because layers are ordered by type)
1896                  */
1897                 while(dest_i < dest->totlayer
1898                           && dest->layers[dest_i].type < source->layers[src_i].type)
1899                         ++dest_i;
1900
1901                 /* if there are no more dest layers, we're done */
1902                 if(dest_i >= dest->totlayer) return;
1903
1904                 /* if we found a matching layer, copy the data */
1905                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1906                         int offset = source->layers[src_i].offset;
1907                         char *src_data = (char*)src_block + offset;
1908                         char *dest_data = dest->layers[dest_i].data;
1909
1910                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
1911                         dest_offset = dest_index * typeInfo->size;
1912
1913                         if(typeInfo->copy)
1914                                 typeInfo->copy(src_data, dest_data + dest_offset, 1);
1915                         else
1916                                 memcpy(dest_data + dest_offset, src_data, typeInfo->size);
1917
1918                         /* if there are multiple source & dest layers of the same type,
1919                          * we don't want to copy all source layers to the same dest, so
1920                          * increment dest_i
1921                          */
1922                         ++dest_i;
1923                 }
1924         }
1925
1926 }
1927
1928 /*Bmesh functions*/
1929 /*needed to convert to/from different face reps*/
1930 void CustomData_to_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata)
1931 {
1932         int i;
1933         for(i=0; i < fdata->totlayer; i++){
1934                 if(fdata->layers[i].type == CD_MTFACE){
1935                         CustomData_add_layer(pdata, CD_MTEXPOLY, CD_CALLOC, &(fdata->layers[i].name), 0);
1936                         CustomData_add_layer(ldata, CD_MLOOPUV, CD_CALLOC, &(fdata->layers[i].name), 0);
1937                 }
1938                 else if(fdata->layers[i].type == CD_MCOL)
1939                         CustomData_add_layer(ldata, CD_MLOOPCOL, CD_CALLOC, &(fdata->layers[i].name), 0);
1940         }               
1941 }
1942 void CustomData_from_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata, int total){
1943         int i;
1944         for(i=0; i < pdata->totlayer; i++){
1945                 if(pdata->layers[i].type == CD_MTEXPOLY)
1946                         CustomData_add_layer(fdata, CD_MTFACE, CD_CALLOC, &(pdata->layers[i].name), total);
1947         }
1948         for(i=0; i < ldata->totlayer; i++){
1949                 if(ldata->layers[i].type == CD_MLOOPCOL)
1950                         CustomData_add_layer(fdata, CD_MCOL, CD_CALLOC, &(ldata->layers[i].name), total);
1951         }
1952 }
1953
1954
1955 void CustomData_bmesh_init_pool(CustomData *data, int allocsize){
1956         if(data->totlayer)data->pool = BLI_mempool_create(data->totsize, allocsize, allocsize, 0);
1957 }
1958
1959 void CustomData_bmesh_free_block(CustomData *data, void **block)
1960 {
1961         const LayerTypeInfo *typeInfo;
1962         int i;
1963
1964         if(!*block) return;
1965         for(i = 0; i < data->totlayer; ++i) {
1966                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
1967                         typeInfo = layerType_getInfo(data->layers[i].type);
1968
1969                         if(typeInfo->free) {
1970                                 int offset = data->layers[i].offset;
1971                                 typeInfo->free((char*)*block + offset, 1, typeInfo->size);
1972                         }
1973                 }
1974         }
1975
1976         BLI_mempool_free(data->pool, *block);
1977         *block = NULL;
1978 }
1979
1980 static void CustomData_bmesh_alloc_block(CustomData *data, void **block)
1981 {
1982
1983         if (*block)
1984                 CustomData_bmesh_free_block(data, block);
1985
1986         if (data->totsize > 0)
1987                 *block = BLI_mempool_calloc(data->pool);
1988         else
1989                 *block = NULL;
1990 }
1991
1992 void CustomData_bmesh_copy_data(const CustomData *source, CustomData *dest,
1993                                                         void *src_block, void **dest_block)
1994 {
1995         const LayerTypeInfo *typeInfo;
1996         int dest_i, src_i;
1997
1998         if (!*dest_block)
1999                 CustomData_bmesh_alloc_block(dest, dest_block);
2000         
2001         /* copies a layer at a time */
2002         dest_i = 0;
2003         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2004
2005                 /* find the first dest layer with type >= the source type
2006                  * (this should work because layers are ordered by type)
2007                  */
2008                 while(dest_i < dest->totlayer
2009                           && dest->layers[dest_i].type < source->layers[src_i].type)
2010                         ++dest_i;
2011
2012                 /* if there are no more dest layers, we're done */
2013                 if(dest_i >= dest->totlayer) return;
2014
2015                 /* if we found a matching layer, copy the data */
2016                 if(dest->layers[dest_i].type == source->layers[src_i].type &&
2017                         strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
2018                         char *src_data = (char*)src_block + source->layers[src_i].offset;
2019                         char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
2020
2021                         typeInfo = layerType_getInfo(source->layers[src_i].type);
2022
2023                         if(typeInfo->copy)
2024                                 typeInfo->copy(src_data, dest_data, 1);
2025                         else
2026                                 memcpy(dest_data, src_data, typeInfo->size);
2027
2028                         /* if there are multiple source & dest layers of the same type,
2029                          * we don't want to copy all source layers to the same dest, so
2030                          * increment dest_i
2031                          */
2032                         ++dest_i;
2033                 }
2034         }
2035 }
2036
2037 /*Bmesh Custom Data Functions. Should replace editmesh ones with these as well, due to more effecient memory alloc*/
2038 void *CustomData_bmesh_get(const CustomData *data, void *block, int type)
2039 {
2040         int layer_index;
2041         
2042         /* get the layer index of the first layer of type */
2043         layer_index = CustomData_get_active_layer_index(data, type);
2044         if(layer_index < 0) return NULL;
2045
2046         return (char *)block + data->layers[layer_index].offset;
2047 }
2048
2049 void *CustomData_bmesh_get_n(const CustomData *data, void *block, int type, int n)
2050 {
2051         int layer_index;
2052         
2053         /* get the layer index of the first layer of type */
2054         layer_index = CustomData_get_layer_index(data, type);
2055         if(layer_index < 0) return NULL;
2056
2057         return (char *)block + data->layers[layer_index+n].offset;
2058 }
2059
2060 void CustomData_bmesh_set(const CustomData *data, void *block, int type, void *source)
2061 {
2062         void *dest = CustomData_bmesh_get(data, block, type);
2063         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2064
2065         if(!dest) return;
2066
2067         if(typeInfo->copy)
2068                 typeInfo->copy(source, dest, 1);
2069         else
2070                 memcpy(dest, source, typeInfo->size);
2071 }
2072
2073 void CustomData_bmesh_set_n(CustomData *data, void *block, int type, int n, void *source)
2074 {
2075         void *dest = CustomData_bmesh_get_n(data, block, type, n);
2076         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2077
2078         if(!dest) return;
2079
2080         if(typeInfo->copy)
2081                 typeInfo->copy(source, dest, 1);
2082         else
2083                 memcpy(dest, source, typeInfo->size);
2084 }
2085
2086 void CustomData_bmesh_interp(CustomData *data, void **src_blocks, float *weights,
2087                                                   float *sub_weights, int count, void *dest_block)
2088 {
2089         int i, j;
2090         void *source_buf[SOURCE_BUF_SIZE];
2091         void **sources = source_buf;
2092
2093         /* slow fallback in case we're interpolating a ridiculous number of
2094          * elements
2095          */
2096         if(count > SOURCE_BUF_SIZE)
2097                 sources = MEM_callocN(sizeof(*sources) * count,
2098                                                           "CustomData_interp sources");
2099
2100         /* interpolates a layer at a time */
2101         for(i = 0; i < data->totlayer; ++i) {
2102                 CustomDataLayer *layer = &data->layers[i];
2103                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
2104                 if(typeInfo->interp) {
2105                         for(j = 0; j < count; ++j)
2106                                 sources[j] = (char *)src_blocks[j] + layer->offset;
2107
2108                         typeInfo->interp(sources, weights, sub_weights, count,
2109                                                           (char *)dest_block + layer->offset);
2110                 }
2111         }
2112
2113         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
2114 }
2115
2116 void CustomData_bmesh_set_default(CustomData *data, void **block)
2117 {
2118         const LayerTypeInfo *typeInfo;
2119         int i;
2120
2121         if (!*block)
2122                 CustomData_bmesh_alloc_block(data, block);
2123
2124         for(i = 0; i < data->totlayer; ++i) {
2125                 int offset = data->layers[i].offset;
2126
2127                 typeInfo = layerType_getInfo(data->layers[i].type);
2128
2129                 if(typeInfo->set_default)
2130                         typeInfo->set_default((char*)*block + offset, 1);
2131         }
2132 }
2133
2134 void CustomData_to_bmesh_block(const CustomData *source, CustomData *dest,
2135                                                         int src_index, void **dest_block)
2136 {
2137         const LayerTypeInfo *typeInfo;
2138         int dest_i, src_i, src_offset;
2139
2140         if (!*dest_block)
2141                 CustomData_bmesh_alloc_block(dest, dest_block);
2142         
2143         /* copies a layer at a time */
2144         dest_i = 0;
2145         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2146
2147                 /* find the first dest layer with type >= the source type
2148                  * (this should work because layers are ordered by type)
2149                  */
2150                 while(dest_i < dest->totlayer
2151                           && dest->layers[dest_i].type < source->layers[src_i].type)
2152                         ++dest_i;
2153
2154                 /* if there are no more dest layers, we're done */
2155                 if(dest_i >= dest->totlayer) return;
2156
2157                 /* if we found a matching layer, copy the data */
2158                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2159                         int offset = dest->layers[dest_i].offset;
2160                         char *src_data = source->layers[src_i].data;
2161                         char *dest_data = (char*)*dest_block + offset;
2162
2163                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2164                         src_offset = src_index * typeInfo->size;
2165
2166                         if(typeInfo->copy)
2167                                 typeInfo->copy(src_data + src_offset, dest_data, 1);
2168                         else
2169                                 memcpy(dest_data, src_data + src_offset, typeInfo->size);
2170
2171                         /* if there are multiple source & dest layers of the same type,
2172                          * we don't want to copy all source layers to the same dest, so
2173                          * increment dest_i
2174                          */
2175                         ++dest_i;
2176                 }
2177         }
2178 }
2179
2180 void CustomData_from_bmesh_block(const CustomData *source, CustomData *dest,
2181                                                           void *src_block, int dest_index)
2182 {
2183         const LayerTypeInfo *typeInfo;
2184         int dest_i, src_i, dest_offset;
2185
2186         /* copies a layer at a time */
2187         dest_i = 0;
2188         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2189
2190                 /* find the first dest layer with type >= the source type
2191                  * (this should work because layers are ordered by type)
2192                  */
2193                 while(dest_i < dest->totlayer
2194                           && dest->layers[dest_i].type < source->layers[src_i].type)
2195                         ++dest_i;
2196
2197                 /* if there are no more dest layers, we're done */
2198                 if(dest_i >= dest->totlayer) return;
2199
2200                 /* if we found a matching layer, copy the data */
2201                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2202                         int offset = source->layers[src_i].offset;
2203                         char *src_data = (char*)src_block + offset;
2204                         char *dest_data = dest->layers[dest_i].data;
2205
2206                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2207                         dest_offset = dest_index * typeInfo->size;
2208
2209                         if(typeInfo->copy)
2210                                 typeInfo->copy(src_data, dest_data + dest_offset, 1);
2211                         else
2212                                 memcpy(dest_data + dest_offset, src_data, typeInfo->size);
2213
2214                         /* if there are multiple source & dest layers of the same type,
2215                          * we don't want to copy all source layers to the same dest, so
2216                          * increment dest_i
2217                          */
2218                         ++dest_i;
2219                 }
2220         }
2221
2222 }
2223
2224 void CustomData_file_write_info(int type, char **structname, int *structnum)
2225 {
2226         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2227
2228         *structname = typeInfo->structname;
2229         *structnum = typeInfo->structnum;
2230 }
2231
2232 int CustomData_sizeof(int type)
2233 {
2234         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2235
2236         return typeInfo->size;
2237 }
2238
2239 const char *CustomData_layertype_name(int type)
2240 {
2241         return layerType_getName(type);
2242 }
2243
2244 static int  CustomData_is_property_layer(int type)
2245 {
2246         if((type == CD_PROP_FLT) || (type == CD_PROP_INT) || (type == CD_PROP_STR))
2247                 return 1;
2248         return 0;
2249 }
2250
2251 void CustomData_set_layer_unique_name(CustomData *data, int index)
2252 {
2253         char tempname[64];
2254         int number, i, type;
2255         char *dot, *name;
2256         CustomDataLayer *layer, *nlayer= &data->layers[index];
2257         const LayerTypeInfo *typeInfo= layerType_getInfo(nlayer->type);
2258
2259         if (!typeInfo->defaultname)
2260                 return;
2261
2262         type = nlayer->type;
2263         name = nlayer->name;
2264
2265         if (name[0] == '\0')
2266                 BLI_strncpy(nlayer->name, typeInfo->defaultname, sizeof(nlayer->name));
2267         
2268         /* see if there is a duplicate */
2269         for(i=0; i<data->totlayer; i++) {
2270                 layer = &data->layers[i];
2271                 
2272                 if(CustomData_is_property_layer(type)){
2273                         if(i!=index && CustomData_is_property_layer(layer->type) && 
2274                                 strcmp(layer->name, name)==0)
2275                                         break;  
2276                 
2277                 }
2278                 else{
2279                         if(i!=index && layer->type==type && strcmp(layer->name, name)==0)
2280                                 break;
2281                 }
2282         }
2283
2284         if(i == data->totlayer)
2285                 return;
2286
2287         /* strip off the suffix */
2288         dot = strchr(nlayer->name, '.');
2289         if(dot) *dot=0;
2290         
2291         for(number=1; number <=999; number++) {
2292                 sprintf(tempname, "%s.%03d", nlayer->name, number);
2293
2294                 for(i=0; i<data->totlayer; i++) {
2295                         layer = &data->layers[i];
2296                         
2297                         if(CustomData_is_property_layer(type)){
2298                                 if(i!=index && CustomData_is_property_layer(layer->type) && 
2299                                         strcmp(layer->name, tempname)==0)
2300
2301                                 break;
2302                         }
2303                         else{
2304                                 if(i!=index && layer->type==type && strcmp(layer->name, tempname)==0)
2305                                         break;
2306                         }
2307                 }
2308
2309                 if(i == data->totlayer) {
2310                         BLI_strncpy(nlayer->name, tempname, sizeof(nlayer->name));
2311                         return;
2312                 }
2313         }       
2314 }
2315
2316 int CustomData_verify_versions(struct CustomData *data, int index)
2317 {
2318         const LayerTypeInfo *typeInfo;
2319         CustomDataLayer *layer = &data->layers[index];
2320         int i, keeplayer = 1;
2321
2322         if (layer->type >= CD_NUMTYPES) {
2323                 keeplayer = 0; /* unknown layer type from future version */
2324         }
2325         else {
2326                 typeInfo = layerType_getInfo(layer->type);
2327
2328                 if (!typeInfo->defaultname && (index > 0) &&
2329                         data->layers[index-1].type == layer->type)
2330                         keeplayer = 0; /* multiple layers of which we only support one */
2331         }
2332
2333         if (!keeplayer) {
2334                 for (i=index+1; i < data->totlayer; ++i)
2335                         data->layers[i-1] = data->layers[i];
2336                 data->totlayer--;
2337         }
2338
2339         return keeplayer;
2340 }
2341
2342 /****************************** External Files *******************************/
2343
2344 static void customdata_external_filename(char filename[FILE_MAX], ID *id, CustomDataExternal *external)
2345 {
2346         char *path = (id->lib)? id->lib->filepath: G.main->name;
2347
2348         BLI_strncpy(filename, external->filename, FILE_MAX);
2349         BLI_path_abs(filename, path);
2350 }
2351
2352 void CustomData_external_reload(CustomData *data, ID *UNUSED(id), CustomDataMask mask, int totelem)
2353 {
2354         CustomDataLayer *layer;
2355         const LayerTypeInfo *typeInfo;
2356         int i;
2357
2358         for(i=0; i<data->totlayer; i++) {
2359                 layer = &data->layers[i];
2360                 typeInfo = layerType_getInfo(layer->type);
2361
2362                 if(!(mask & (1<<layer->type)));
2363                 else if((layer->flag & CD_FLAG_EXTERNAL) && (layer->flag & CD_FLAG_IN_MEMORY)) {
2364                         if(typeInfo->free)
2365                                 typeInfo->free(layer->data, totelem, typeInfo->size);
2366                         layer->flag &= ~CD_FLAG_IN_MEMORY;
2367                 }
2368         }
2369 }
2370
2371 void CustomData_external_read(CustomData *data, ID *id, CustomDataMask mask, int totelem)
2372 {
2373         CustomDataExternal *external= data->external;
2374         CustomDataLayer *layer;
2375         CDataFile *cdf;
2376         CDataFileLayer *blay;
2377         char filename[FILE_MAX];
2378         const LayerTypeInfo *typeInfo;
2379         int i, update = 0;
2380
2381         if(!external)
2382                 return;
2383         
2384         for(i=0; i<data->totlayer; i++) {
2385                 layer = &data->layers[i];
2386                 typeInfo = layerType_getInfo(layer->type);
2387
2388                 if(!(mask & (1<<layer->type)));
2389                 else if(layer->flag & CD_FLAG_IN_MEMORY);
2390                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read)
2391                         update= 1;
2392         }
2393
2394         if(!update)
2395                 return;
2396
2397         customdata_external_filename(filename, id, external);
2398
2399         cdf= cdf_create(CDF_TYPE_MESH);
2400         if(!cdf_read_open(cdf, filename)) {
2401                 fprintf(stderr, "Failed to read %s layer from %s.\n", layerType_getName(layer->type), filename);
2402                 return;
2403         }
2404
2405         for(i=0; i<data->totlayer; i++) {
2406                 layer = &data->layers[i];
2407                 typeInfo = layerType_getInfo(layer->type);
2408
2409                 if(!(mask & (1<<layer->type)));
2410                 else if(layer->flag & CD_FLAG_IN_MEMORY);
2411                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read) {
2412                         blay= cdf_layer_find(cdf, layer->type, layer->name);
2413
2414                         if(blay) {
2415                                 if(cdf_read_layer(cdf, blay)) {
2416                                         if(typeInfo->read(cdf, layer->data, totelem));
2417                                         else break;
2418                                         layer->flag |= CD_FLAG_IN_MEMORY;
2419                                 }
2420                                 else
2421                                         break;
2422                         }
2423                 }
2424         }
2425
2426         cdf_read_close(cdf);
2427         cdf_free(cdf);
2428 }
2429
2430 void CustomData_external_write(CustomData *data, ID *id, CustomDataMask mask, int totelem, int free)
2431 {
2432         CustomDataExternal *external= data->external;
2433         CustomDataLayer *layer;
2434         CDataFile *cdf;
2435         CDataFileLayer *blay;
2436         const LayerTypeInfo *typeInfo;
2437         int i, update = 0;
2438         char filename[FILE_MAX];
2439
2440         if(!external)
2441                 return;
2442
2443         /* test if there is anything to write */
2444         for(i=0; i<data->totlayer; i++) {
2445                 layer = &data->layers[i];
2446                 typeInfo = layerType_getInfo(layer->type);
2447
2448                 if(!(mask & (1<<layer->type)));
2449                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write)
2450                         update= 1;
2451         }
2452
2453         if(!update)
2454                 return;
2455
2456         /* make sure data is read before we try to write */
2457         CustomData_external_read(data, id, mask, totelem);
2458         customdata_external_filename(filename, id, external);
2459
2460         cdf= cdf_create(CDF_TYPE_MESH);
2461
2462         for(i=0; i<data->totlayer; i++) {
2463                 layer = &data->layers[i];
2464                 typeInfo = layerType_getInfo(layer->type);
2465
2466                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->filesize) {
2467                         if(layer->flag & CD_FLAG_IN_MEMORY) {
2468                                 cdf_layer_add(cdf, layer->type, layer->name,
2469                                         typeInfo->filesize(cdf, layer->data, totelem));
2470                         }
2471                         else {
2472                                 cdf_free(cdf);
2473                                 return; /* read failed for a layer! */
2474                         }
2475                 }
2476         }
2477
2478         if(!cdf_write_open(cdf, filename)) {
2479                 fprintf(stderr, "Failed to open %s for writing.\n", filename);
2480                 return;
2481         }
2482
2483         for(i=0; i<data->totlayer; i++) {
2484                 layer = &data->layers[i];
2485                 typeInfo = layerType_getInfo(layer->type);
2486
2487                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) {
2488                         blay= cdf_layer_find(cdf, layer->type, layer->name);
2489
2490                         if(cdf_write_layer(cdf, blay)) {
2491                                 if(typeInfo->write(cdf, layer->data, totelem));
2492                                 else break;
2493                         }
2494                         else
2495                                 break;
2496                 }
2497         }
2498
2499         if(i != data->totlayer) {
2500                 fprintf(stderr, "Failed to write data to %s.\n", filename);
2501                 cdf_free(cdf);
2502                 return;
2503         }
2504
2505         for(i=0; i<data->totlayer; i++) {
2506                 layer = &data->layers[i];
2507                 typeInfo = layerType_getInfo(layer->type);
2508
2509                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) {
2510                         if(free) {
2511                                 if(typeInfo->free)
2512                                         typeInfo->free(layer->data, totelem, typeInfo->size);
2513                                 layer->flag &= ~CD_FLAG_IN_MEMORY;
2514                         }
2515                 }
2516         }
2517
2518         cdf_write_close(cdf);
2519         cdf_free(cdf);
2520 }
2521
2522 void CustomData_external_add(CustomData *data, ID *UNUSED(id), int type, int UNUSED(totelem), const char *filename)
2523 {
2524         CustomDataExternal *external= data->external;
2525         CustomDataLayer *layer;
2526         int layer_index;
2527
2528         layer_index = CustomData_get_active_layer_index(data, type);
2529         if(layer_index < 0) return;
2530
2531         layer = &data->layers[layer_index];
2532
2533         if(layer->flag & CD_FLAG_EXTERNAL)
2534                 return;
2535
2536         if(!external) {
2537                 external= MEM_callocN(sizeof(CustomDataExternal), "CustomDataExternal");
2538                 data->external= external;
2539         }
2540         BLI_strncpy(external->filename, filename, sizeof(external->filename));
2541
2542         layer->flag |= CD_FLAG_EXTERNAL|CD_FLAG_IN_MEMORY;
2543 }
2544
2545 void CustomData_external_remove(CustomData *data, ID *id, int type, int totelem)
2546 {
2547         CustomDataExternal *external= data->external;
2548         CustomDataLayer *layer;
2549         //char filename[FILE_MAX];
2550         int layer_index; // i, remove_file;
2551
2552         layer_index = CustomData_get_active_layer_index(data, type);
2553         if(layer_index < 0) return;
2554
2555         layer = &data->layers[layer_index];
2556
2557         if(!external)
2558                 return;
2559
2560         if(layer->flag & CD_FLAG_EXTERNAL) {
2561                 if(!(layer->flag & CD_FLAG_IN_MEMORY))
2562                         CustomData_external_read(data, id, (1<<layer->type), totelem);
2563
2564                 layer->flag &= ~CD_FLAG_EXTERNAL;
2565
2566 #if 0
2567                 remove_file= 1;
2568                 for(i=0; i<data->totlayer; i++)
2569                         if(data->layers[i].flag & CD_FLAG_EXTERNAL)
2570                                 remove_file= 0;
2571
2572                 if(remove_file) {
2573                         customdata_external_filename(filename, id, external);
2574                         cdf_remove(filename);
2575                         CustomData_external_free(data);
2576                 }
2577 #endif
2578         }
2579 }
2580
2581 int CustomData_external_test(CustomData *data, int type)
2582 {
2583         CustomDataLayer *layer;
2584         int layer_index;
2585
2586         layer_index = CustomData_get_active_layer_index(data, type);
2587         if(layer_index < 0) return 0;
2588
2589         layer = &data->layers[layer_index];
2590         return (layer->flag & CD_FLAG_EXTERNAL);
2591 }
2592
2593 #if 0
2594 void CustomData_external_remove_object(CustomData *data, ID *id)
2595 {
2596         CustomDataExternal *external= data->external;
2597         char filename[FILE_MAX];
2598
2599         if(!external)
2600                 return;
2601
2602         customdata_external_filename(filename, id, external);
2603         cdf_remove(filename);
2604         CustomData_external_free(data);
2605 }
2606 #endif
2607