Make sure separation between modifier keys is communicated from GHOST upwards too...
[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                 float z[3] = {0,0,0};
506                 copy_v3_v3(d->disps[i], z);
507         }
508
509         /* For now, some restrictions on the input */
510         if(count != 1 || !sub_weights) return;
511
512         st = sqrt(d->totdisp);
513         stl = st - 1;
514
515         sw = (void*)sub_weights;
516         for(i = 0; i < 4; ++i) {
517                 crn[i][0] = 0 * sw[i][0] + stl * sw[i][1] + stl * sw[i][2] + 0 * sw[i][3];
518                 crn[i][1] = 0 * sw[i][0] + 0 * sw[i][1] + stl * sw[i][2] + stl * sw[i][3];
519         }
520
521         s = sources[0];
522         for(y = 0; y < st; ++y) {
523                 for(x = 0; x < st; ++x) {
524                         /* One suspects this code could be cleaner. */
525                         float xl = (float)x / (st - 1);
526                         float yl = (float)y / (st - 1);
527                         float mid1[2] = {crn[0][0] * (1 - xl) + crn[1][0] * xl,
528                                          crn[0][1] * (1 - xl) + crn[1][1] * xl};
529                         float mid2[2] = {crn[3][0] * (1 - xl) + crn[2][0] * xl,
530                                          crn[3][1] * (1 - xl) + crn[2][1] * xl};
531                         float mid3[2] = {mid1[0] * (1 - yl) + mid2[0] * yl,
532                                          mid1[1] * (1 - yl) + mid2[1] * yl};
533
534                         float srcdisp[3];
535
536                         mdisps_bilinear(srcdisp, s->disps, st, mid3[0], mid3[1]);
537                         copy_v3_v3(d->disps[y * st + x], srcdisp);
538                 }
539         }
540 #else
541         if(d->disps) {
542                 for(i = 0; i < d->totdisp; ++i)
543                         zero_v3(d->disps[i]);
544         }
545 #endif
546 }
547
548 static void layerCopy_mdisps(const void *source, void *dest, int count)
549 {
550         int i;
551         const MDisps *s = source;
552         MDisps *d = dest;
553
554         for(i = 0; i < count; ++i) {
555                 if(s[i].disps) {
556                         d[i].disps = MEM_dupallocN(s[i].disps);
557                         d[i].totdisp = s[i].totdisp;
558                 }
559                 else {
560                         d[i].disps = NULL;
561                         d[i].totdisp = 0;
562                 }
563                 
564         }
565 }
566
567 static void layerFree_mdisps(void *data, int count, int UNUSED(size))
568 {
569         int i;
570         MDisps *d = data;
571
572         for(i = 0; i < count; ++i) {
573                 if(d[i].disps)
574                         MEM_freeN(d[i].disps);
575                 d[i].disps = NULL;
576                 d[i].totdisp = 0;
577         }
578 }
579
580 static int layerRead_mdisps(CDataFile *cdf, void *data, int count)
581 {
582         MDisps *d = data;
583         int i;
584
585         for(i = 0; i < count; ++i) {
586                 if(!d[i].disps)
587                         d[i].disps = MEM_callocN(sizeof(float)*3*d[i].totdisp, "mdisps read");
588
589                 if(!cdf_read_data(cdf, d[i].totdisp*3*sizeof(float), d[i].disps)) {
590                         printf("failed to read multires displacement %d/%d %d\n", i, count, d[i].totdisp);
591                         return 0;
592                 }
593         }
594
595         return 1;
596 }
597
598 static int layerWrite_mdisps(CDataFile *cdf, void *data, int count)
599 {
600         MDisps *d = data;
601         int i;
602
603         for(i = 0; i < count; ++i) {
604                 if(!cdf_write_data(cdf, d[i].totdisp*3*sizeof(float), d[i].disps)) {
605                         printf("failed to write multires displacement %d/%d %d\n", i, count, d[i].totdisp);
606                         return 0;
607                 }
608         }
609
610         return 1;
611 }
612
613 static size_t layerFilesize_mdisps(CDataFile *UNUSED(cdf), void *data, int count)
614 {
615         MDisps *d = data;
616         size_t size = 0;
617         int i;
618
619         for(i = 0; i < count; ++i)
620                 size += d[i].totdisp*3*sizeof(float);
621
622         return size;
623 }
624
625 /* --------- */
626
627 static void layerDefault_mloopcol(void *data, int count)
628 {
629         static MLoopCol default_mloopcol = {255,255,255,255};
630         MLoopCol *mlcol = (MLoopCol*)data;
631         int i;
632         for(i = 0; i < count; i++)
633                 mlcol[i] = default_mloopcol;
634
635 }
636
637 static void layerInterp_mloopcol(void **sources, float *weights,
638                                 float *sub_weights, int count, void *dest)
639 {
640         MLoopCol *mc = dest;
641         int i;
642         float *sub_weight;
643         struct {
644                 float a;
645                 float r;
646                 float g;
647                 float b;
648         } col;
649         col.a = col.r = col.g = col.b = 0;
650
651         sub_weight = sub_weights;
652         for(i = 0; i < count; ++i){
653                 float weight = weights ? weights[i] : 1;
654                 MLoopCol *src = sources[i];
655                 if(sub_weights){
656                         col.a += src->a * (*sub_weight) * weight;
657                         col.r += src->r * (*sub_weight) * weight;
658                         col.g += src->g * (*sub_weight) * weight;
659                         col.b += src->b * (*sub_weight) * weight;
660                         sub_weight++;           
661                 } else {
662                         col.a += src->a * weight;
663                         col.r += src->r * weight;
664                         col.g += src->g * weight;
665                         col.b += src->b * weight;
666                 }
667         }
668         
669         /* Subdivide smooth or fractal can cause problems without clamping
670          * although weights should also not cause this situation */
671         CLAMP(col.a, 0.0f, 255.0f);
672         CLAMP(col.r, 0.0f, 255.0f);
673         CLAMP(col.g, 0.0f, 255.0f);
674         CLAMP(col.b, 0.0f, 255.0f);
675         
676         mc->a = (int)col.a;
677         mc->r = (int)col.r;
678         mc->g = (int)col.g;
679         mc->b = (int)col.b;
680 }
681 static void layerInterp_mloopuv(void **sources, float *weights,
682                                 float *sub_weights, int count, void *dest)
683 {
684         MLoopUV *mluv = dest;
685         int i;
686         float *sub_weight;
687         struct {
688                 float u;
689                 float v;
690         }uv;
691         uv.u = uv.v = 0.0;
692
693         sub_weight = sub_weights;
694         for(i = 0; i < count; ++i){
695                 float weight = weights ? weights[i] : 1;
696                 MLoopUV *src = sources[i];
697                 if(sub_weights){
698                         uv.u += src->uv[0] * (*sub_weight) * weight;
699                         uv.v += src->uv[1] * (*sub_weight) * weight;
700                         sub_weight++;           
701                 } else {
702                         uv.u += src->uv[0] * weight;
703                         uv.v += src->uv[1] * weight;
704                 }
705         }
706         mluv->uv[0] = uv.u;
707         mluv->uv[1] = uv.v;
708 }
709
710 static void layerInterp_mcol(void **sources, float *weights,
711                                                          float *sub_weights, int count, void *dest)
712 {
713         MCol *mc = dest;
714         int i, j, k;
715         struct {
716                 float a;
717                 float r;
718                 float g;
719                 float b;
720         } col[4];
721         float *sub_weight;
722
723         if(count <= 0) return;
724
725         memset(col, 0, sizeof(col));
726         
727         sub_weight = sub_weights;
728         for(i = 0; i < count; ++i) {
729                 float weight = weights ? weights[i] : 1;
730
731                 for(j = 0; j < 4; ++j) {
732                         if(sub_weights) {
733                                 MCol *src = sources[i];
734                                 for(k = 0; k < 4; ++k, ++sub_weight, ++src) {
735                                         col[j].a += src->a * (*sub_weight) * weight;
736                                         col[j].r += src->r * (*sub_weight) * weight;
737                                         col[j].g += src->g * (*sub_weight) * weight;
738                                         col[j].b += src->b * (*sub_weight) * weight;
739                                 }
740                         } else {
741                                 MCol *src = sources[i];
742                                 col[j].a += src[j].a * weight;
743                                 col[j].r += src[j].r * weight;
744                                 col[j].g += src[j].g * weight;
745                                 col[j].b += src[j].b * weight;
746                         }
747                 }
748         }
749
750         for(j = 0; j < 4; ++j) {
751                 
752                 /* Subdivide smooth or fractal can cause problems without clamping
753                  * although weights should also not cause this situation */
754                 CLAMP(col[j].a, 0.0f, 255.0f);
755                 CLAMP(col[j].r, 0.0f, 255.0f);
756                 CLAMP(col[j].g, 0.0f, 255.0f);
757                 CLAMP(col[j].b, 0.0f, 255.0f);
758                 
759                 mc[j].a = (int)col[j].a;
760                 mc[j].r = (int)col[j].r;
761                 mc[j].g = (int)col[j].g;
762                 mc[j].b = (int)col[j].b;
763         }
764 }
765
766 static void layerSwap_mcol(void *data, const int *corner_indices)
767 {
768         MCol *mcol = data;
769         MCol col[4];
770         int j;
771
772         for(j = 0; j < 4; ++j)
773                 col[j] = mcol[corner_indices[j]];
774
775         memcpy(mcol, col, sizeof(col));
776 }
777
778 static void layerDefault_mcol(void *data, int count)
779 {
780         static MCol default_mcol = {255, 255, 255, 255};
781         MCol *mcol = (MCol*)data;
782         int i;
783
784         for(i = 0; i < 4*count; i++)
785                 mcol[i] = default_mcol;
786 }
787
788
789
790 const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = {
791         {sizeof(MVert), "MVert", 1, NULL, NULL, NULL, NULL, NULL, NULL},
792         {sizeof(MSticky), "MSticky", 1, NULL, NULL, NULL, layerInterp_msticky, NULL,
793          NULL},
794         {sizeof(MDeformVert), "MDeformVert", 1, NULL, layerCopy_mdeformvert,
795          layerFree_mdeformvert, layerInterp_mdeformvert, NULL, NULL},
796         {sizeof(MEdge), "MEdge", 1, NULL, NULL, NULL, NULL, NULL, NULL},
797         {sizeof(MFace), "MFace", 1, NULL, NULL, NULL, NULL, NULL, NULL},
798         {sizeof(MTFace), "MTFace", 1, "UVTex", layerCopy_tface, NULL,
799          layerInterp_tface, layerSwap_tface, layerDefault_tface},
800         /* 4 MCol structs per face */
801         {sizeof(MCol)*4, "MCol", 4, "Col", NULL, NULL, layerInterp_mcol,
802          layerSwap_mcol, layerDefault_mcol},
803         {sizeof(int), "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
804         /* 3 floats per normal vector */
805         {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
806         {sizeof(int), "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
807         {sizeof(MFloatProperty), "MFloatProperty",1,"Float",NULL,NULL,NULL,NULL},
808         {sizeof(MIntProperty), "MIntProperty",1,"Int",NULL,NULL,NULL,NULL},
809         {sizeof(MStringProperty), "MStringProperty",1,"String",NULL,NULL,NULL,NULL},
810         {sizeof(OrigSpaceFace), "OrigSpaceFace", 1, "UVTex", layerCopy_origspace_face, NULL,
811          layerInterp_origspace_face, layerSwap_origspace_face, layerDefault_origspace_face},
812         {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
813         {sizeof(MTexPoly), "MTexPoly", 1, "Face Texture", NULL, NULL, NULL, NULL, NULL},
814         {sizeof(MLoopUV), "MLoopUV", 1, "UV coord", NULL, NULL, layerInterp_mloopuv, NULL, NULL},
815         {sizeof(MLoopCol), "MLoopCol", 1, "Col", NULL, NULL, layerInterp_mloopcol, NULL, layerDefault_mloopcol},
816         {sizeof(float)*3*4, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
817         {sizeof(MDisps), "MDisps", 1, NULL, layerCopy_mdisps,
818          layerFree_mdisps, layerInterp_mdisps, layerSwap_mdisps, NULL, layerRead_mdisps, layerWrite_mdisps, layerFilesize_mdisps},
819         {sizeof(MCol)*4, "MCol", 4, "WeightCol", NULL, NULL, layerInterp_mcol,
820          layerSwap_mcol, layerDefault_mcol},
821          {sizeof(MCol)*4, "MCol", 4, "IDCol", NULL, NULL, layerInterp_mcol,
822          layerSwap_mcol, layerDefault_mcol},
823          {sizeof(MCol)*4, "MCol", 4, "TexturedCol", NULL, NULL, layerInterp_mcol,
824          layerSwap_mcol, layerDefault_mcol},
825         {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL}
826 };
827
828 const char *LAYERTYPENAMES[CD_NUMTYPES] = {
829         /*   0-4 */ "CDMVert", "CDMSticky", "CDMDeformVert", "CDMEdge", "CDMFace",
830         /*   5-9 */ "CDMTFace", "CDMCol", "CDOrigIndex", "CDNormal", "CDFlags",
831         /* 10-14 */ "CDMFloatProperty", "CDMIntProperty","CDMStringProperty", "CDOrigSpace", "CDOrco",
832         /* 15-19 */ "CDMTexPoly", "CDMLoopUV", "CDMloopCol", "CDTangent", "CDMDisps",
833         /* 20-23 */"CDWeightMCol", "CDIDMCol", "CDTextureMCol", "CDClothOrco"
834 };
835
836 const CustomDataMask CD_MASK_BAREMESH =
837         CD_MASK_MVERT | CD_MASK_MEDGE | CD_MASK_MFACE;
838 const CustomDataMask CD_MASK_MESH =
839         CD_MASK_MVERT | CD_MASK_MEDGE | CD_MASK_MFACE |
840         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE | CD_MASK_MCOL |
841         CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR | CD_MASK_MDISPS;
842 const CustomDataMask CD_MASK_EDITMESH =
843         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE |
844         CD_MASK_MCOL|CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR | CD_MASK_MDISPS;
845 const CustomDataMask CD_MASK_DERIVEDMESH =
846         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE |
847         CD_MASK_MCOL | CD_MASK_ORIGINDEX | CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_CLOTH_ORCO |
848         CD_MASK_PROP_STR | CD_MASK_ORIGSPACE | CD_MASK_ORCO | CD_MASK_TANGENT | CD_MASK_WEIGHT_MCOL;
849 const CustomDataMask CD_MASK_BMESH = 
850         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR;
851 const CustomDataMask CD_MASK_FACECORNERS =
852         CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_MTEXPOLY | CD_MASK_MLOOPUV |
853         CD_MASK_MLOOPCOL;
854
855
856 static const LayerTypeInfo *layerType_getInfo(int type)
857 {
858         if(type < 0 || type >= CD_NUMTYPES) return NULL;
859
860         return &LAYERTYPEINFO[type];
861 }
862
863 static const char *layerType_getName(int type)
864 {
865         if(type < 0 || type >= CD_NUMTYPES) return NULL;
866
867         return LAYERTYPENAMES[type];
868 }
869
870 /********************* CustomData functions *********************/
871 static void customData_update_offsets(CustomData *data);
872
873 static CustomDataLayer *customData_add_layer__internal(CustomData *data,
874         int type, int alloctype, void *layerdata, int totelem, const char *name);
875
876 void CustomData_merge(const struct CustomData *source, struct CustomData *dest,
877                                           CustomDataMask mask, int alloctype, int totelem)
878 {
879         const LayerTypeInfo *typeInfo;
880         CustomDataLayer *layer, *newlayer;
881         int i, type, number = 0, lasttype = -1, lastactive = 0, lastrender = 0, lastclone = 0, lastmask = 0, lastflag = 0;
882
883         for(i = 0; i < source->totlayer; ++i) {
884                 layer = &source->layers[i];
885                 typeInfo = layerType_getInfo(layer->type);
886
887                 type = layer->type;
888
889                 if (type != lasttype) {
890                         number = 0;
891                         lastactive = layer->active;
892                         lastrender = layer->active_rnd;
893                         lastclone = layer->active_clone;
894                         lastmask = layer->active_mask;
895                         lasttype = type;
896                         lastflag = layer->flag;
897                 }
898                 else
899                         number++;
900
901                 if(lastflag & CD_FLAG_NOCOPY) continue;
902                 else if(!((int)mask & (int)(1 << (int)type))) continue;
903                 else if(number < CustomData_number_of_layers(dest, type)) continue;
904
905                 if((alloctype == CD_ASSIGN) && (lastflag & CD_FLAG_NOFREE))
906                         newlayer = customData_add_layer__internal(dest, type, CD_REFERENCE,
907                                 layer->data, totelem, layer->name);
908                 else
909                         newlayer = customData_add_layer__internal(dest, type, alloctype,
910                                 layer->data, totelem, layer->name);
911                 
912                 if(newlayer) {
913                         newlayer->active = lastactive;
914                         newlayer->active_rnd = lastrender;
915                         newlayer->active_clone = lastclone;
916                         newlayer->active_mask = lastmask;
917                         newlayer->flag |= lastflag & (CD_FLAG_EXTERNAL|CD_FLAG_IN_MEMORY);
918                 }
919         }
920 }
921
922 void CustomData_copy(const struct CustomData *source, struct CustomData *dest,
923                                          CustomDataMask mask, int alloctype, int totelem)
924 {
925         memset(dest, 0, sizeof(*dest));
926
927         if(source->external)
928                 dest->external= MEM_dupallocN(source->external);
929
930         CustomData_merge(source, dest, mask, alloctype, totelem);
931 }
932
933 static void customData_free_layer__internal(CustomDataLayer *layer, int totelem)
934 {
935         const LayerTypeInfo *typeInfo;
936
937         if(!(layer->flag & CD_FLAG_NOFREE) && layer->data) {
938                 typeInfo = layerType_getInfo(layer->type);
939
940                 if(typeInfo->free)
941                         typeInfo->free(layer->data, totelem, typeInfo->size);
942
943                 if(layer->data)
944                         MEM_freeN(layer->data);
945         }
946 }
947
948 static void CustomData_external_free(CustomData *data)
949 {
950         if(data->external) {
951                 MEM_freeN(data->external);
952                 data->external= NULL;
953         }
954 }
955
956 void CustomData_free(CustomData *data, int totelem)
957 {
958         int i;
959
960         for(i = 0; i < data->totlayer; ++i)
961                 customData_free_layer__internal(&data->layers[i], totelem);
962
963         if(data->layers)
964                 MEM_freeN(data->layers);
965         
966         CustomData_external_free(data);
967         
968         memset(data, 0, sizeof(*data));
969 }
970
971 static void customData_update_offsets(CustomData *data)
972 {
973         const LayerTypeInfo *typeInfo;
974         int i, offset = 0;
975
976         for(i = 0; i < data->totlayer; ++i) {
977                 typeInfo = layerType_getInfo(data->layers[i].type);
978
979                 data->layers[i].offset = offset;
980                 offset += typeInfo->size;
981         }
982
983         data->totsize = offset;
984 }
985
986 int CustomData_get_layer_index(const CustomData *data, int type)
987 {
988         int i; 
989
990         for(i=0; i < data->totlayer; ++i)
991                 if(data->layers[i].type == type)
992                         return i;
993
994         return -1;
995 }
996
997 int CustomData_get_named_layer_index(const CustomData *data, int type, char *name)
998 {
999         int i;
1000
1001         for(i=0; i < data->totlayer; ++i)
1002                 if(data->layers[i].type == type && strcmp(data->layers[i].name, name)==0)
1003                         return i;
1004
1005         return -1;
1006 }
1007
1008 int CustomData_get_active_layer_index(const CustomData *data, int type)
1009 {
1010         int i;
1011
1012         for(i=0; i < data->totlayer; ++i)
1013                 if(data->layers[i].type == type)
1014                         return i + data->layers[i].active;
1015
1016         return -1;
1017 }
1018
1019 int CustomData_get_render_layer_index(const CustomData *data, int type)
1020 {
1021         int i;
1022
1023         for(i=0; i < data->totlayer; ++i)
1024                 if(data->layers[i].type == type)
1025                         return i + data->layers[i].active_rnd;
1026
1027         return -1;
1028 }
1029
1030 int CustomData_get_clone_layer_index(const CustomData *data, int type)
1031 {
1032         int i;
1033
1034         for(i=0; i < data->totlayer; ++i)
1035                 if(data->layers[i].type == type)
1036                         return i + data->layers[i].active_clone;
1037
1038         return -1;
1039 }
1040
1041 int CustomData_get_stencil_layer_index(const CustomData *data, int type)
1042 {
1043         int i;
1044
1045         for(i=0; i < data->totlayer; ++i)
1046                 if(data->layers[i].type == type)
1047                         return i + data->layers[i].active_mask;
1048
1049         return -1;
1050 }
1051
1052 int CustomData_get_active_layer(const CustomData *data, int type)
1053 {
1054         int i;
1055
1056         for(i=0; i < data->totlayer; ++i)
1057                 if(data->layers[i].type == type)
1058                         return data->layers[i].active;
1059
1060         return -1;
1061 }
1062
1063 int CustomData_get_render_layer(const CustomData *data, int type)
1064 {
1065         int i;
1066
1067         for(i=0; i < data->totlayer; ++i)
1068                 if(data->layers[i].type == type)
1069                         return data->layers[i].active_rnd;
1070
1071         return -1;
1072 }
1073
1074 int CustomData_get_clone_layer(const CustomData *data, int type)
1075 {
1076         int i;
1077
1078         for(i=0; i < data->totlayer; ++i)
1079                 if(data->layers[i].type == type)
1080                         return data->layers[i].active_clone;
1081
1082         return -1;
1083 }
1084
1085 int CustomData_get_stencil_layer(const CustomData *data, int type)
1086 {
1087         int i;
1088
1089         for(i=0; i < data->totlayer; ++i)
1090                 if(data->layers[i].type == type)
1091                         return data->layers[i].active_mask;
1092
1093         return -1;
1094 }
1095
1096 void CustomData_set_layer_active(CustomData *data, int type, int n)
1097 {
1098         int i;
1099
1100         for(i=0; i < data->totlayer; ++i)
1101                 if(data->layers[i].type == type)
1102                         data->layers[i].active = n;
1103 }
1104
1105 void CustomData_set_layer_render(CustomData *data, int type, int n)
1106 {
1107         int i;
1108
1109         for(i=0; i < data->totlayer; ++i)
1110                 if(data->layers[i].type == type)
1111                         data->layers[i].active_rnd = n;
1112 }
1113
1114 void CustomData_set_layer_clone(CustomData *data, int type, int n)
1115 {
1116         int i;
1117
1118         for(i=0; i < data->totlayer; ++i)
1119                 if(data->layers[i].type == type)
1120                         data->layers[i].active_clone = n;
1121 }
1122
1123 void CustomData_set_layer_stencil(CustomData *data, int type, int n)
1124 {
1125         int i;
1126
1127         for(i=0; i < data->totlayer; ++i)
1128                 if(data->layers[i].type == type)
1129                         data->layers[i].active_mask = n;
1130 }
1131
1132 /* for using with an index from CustomData_get_active_layer_index and CustomData_get_render_layer_index */
1133 void CustomData_set_layer_active_index(CustomData *data, int type, int n)
1134 {
1135         int i;
1136
1137         for(i=0; i < data->totlayer; ++i)
1138                 if(data->layers[i].type == type)
1139                         data->layers[i].active = n-i;
1140 }
1141
1142 void CustomData_set_layer_render_index(CustomData *data, int type, int n)
1143 {
1144         int i;
1145
1146         for(i=0; i < data->totlayer; ++i)
1147                 if(data->layers[i].type == type)
1148                         data->layers[i].active_rnd = n-i;
1149 }
1150
1151 void CustomData_set_layer_clone_index(CustomData *data, int type, int n)
1152 {
1153         int i;
1154
1155         for(i=0; i < data->totlayer; ++i)
1156                 if(data->layers[i].type == type)
1157                         data->layers[i].active_clone = n-i;
1158 }
1159
1160 void CustomData_set_layer_stencil_index(CustomData *data, int type, int n)
1161 {
1162         int i;
1163
1164         for(i=0; i < data->totlayer; ++i)
1165                 if(data->layers[i].type == type)
1166                         data->layers[i].active_mask = n-i;
1167 }
1168
1169 void CustomData_set_layer_flag(struct CustomData *data, int type, int flag)
1170 {
1171         int i;
1172
1173         for(i=0; i < data->totlayer; ++i)
1174                 if(data->layers[i].type == type)
1175                         data->layers[i].flag |= flag;
1176 }
1177
1178 static int customData_resize(CustomData *data, int amount)
1179 {
1180         CustomDataLayer *tmp = MEM_callocN(sizeof(*tmp)*(data->maxlayer + amount),
1181                                                                            "CustomData->layers");
1182         if(!tmp) return 0;
1183
1184         data->maxlayer += amount;
1185         if (data->layers) {
1186                 memcpy(tmp, data->layers, sizeof(*tmp) * data->totlayer);
1187                 MEM_freeN(data->layers);
1188         }
1189         data->layers = tmp;
1190
1191         return 1;
1192 }
1193
1194 static CustomDataLayer *customData_add_layer__internal(CustomData *data,
1195         int type, int alloctype, void *layerdata, int totelem, const char *name)
1196 {
1197         const LayerTypeInfo *typeInfo= layerType_getInfo(type);
1198         int size = typeInfo->size * totelem, flag = 0, index = data->totlayer;
1199         void *newlayerdata;
1200
1201         if (!typeInfo->defaultname && CustomData_has_layer(data, type))
1202                 return &data->layers[CustomData_get_layer_index(data, type)];
1203
1204         if((alloctype == CD_ASSIGN) || (alloctype == CD_REFERENCE)) {
1205                 newlayerdata = layerdata;
1206         }
1207         else {
1208                 newlayerdata = MEM_callocN(size, layerType_getName(type));
1209                 if(!newlayerdata)
1210                         return NULL;
1211         }
1212
1213         if (alloctype == CD_DUPLICATE) {
1214                 if(typeInfo->copy)
1215                         typeInfo->copy(layerdata, newlayerdata, totelem);
1216                 else
1217                         memcpy(newlayerdata, layerdata, size);
1218         }
1219         else if (alloctype == CD_DEFAULT) {
1220                 if(typeInfo->set_default)
1221                         typeInfo->set_default((char*)newlayerdata, totelem);
1222         }
1223         else if (alloctype == CD_REFERENCE)
1224                 flag |= CD_FLAG_NOFREE;
1225
1226         if(index >= data->maxlayer) {
1227                 if(!customData_resize(data, CUSTOMDATA_GROW)) {
1228                         if(newlayerdata != layerdata)
1229                                 MEM_freeN(newlayerdata);
1230                         return NULL;
1231                 }
1232         }
1233         
1234         data->totlayer++;
1235
1236         /* keep layers ordered by type */
1237         for( ; index > 0 && data->layers[index - 1].type > type; --index)
1238                 data->layers[index] = data->layers[index - 1];
1239
1240         data->layers[index].type = type;
1241         data->layers[index].flag = flag;
1242         data->layers[index].data = newlayerdata;
1243
1244         if(name || (name=typeInfo->defaultname)) {
1245                 strcpy(data->layers[index].name, name);
1246                 CustomData_set_layer_unique_name(data, index);
1247         }
1248         else
1249                 data->layers[index].name[0] = '\0';
1250
1251         if(index > 0 && data->layers[index-1].type == type) {
1252                 data->layers[index].active = data->layers[index-1].active;
1253                 data->layers[index].active_rnd = data->layers[index-1].active_rnd;
1254                 data->layers[index].active_clone = data->layers[index-1].active_clone;
1255                 data->layers[index].active_mask = data->layers[index-1].active_mask;
1256         } else {
1257                 data->layers[index].active = 0;
1258                 data->layers[index].active_rnd = 0;
1259                 data->layers[index].active_clone = 0;
1260                 data->layers[index].active_mask = 0;
1261         }
1262         
1263         customData_update_offsets(data);
1264
1265         return &data->layers[index];
1266 }
1267
1268 void *CustomData_add_layer(CustomData *data, int type, int alloctype,
1269                                                    void *layerdata, int totelem)
1270 {
1271         CustomDataLayer *layer;
1272         const LayerTypeInfo *typeInfo= layerType_getInfo(type);
1273         
1274         layer = customData_add_layer__internal(data, type, alloctype, layerdata,
1275                                                                                    totelem, typeInfo->defaultname);
1276
1277         if(layer)
1278                 return layer->data;
1279
1280         return NULL;
1281 }
1282
1283 /*same as above but accepts a name*/
1284 void *CustomData_add_layer_named(CustomData *data, int type, int alloctype,
1285                                                    void *layerdata, int totelem, const char *name)
1286 {
1287         CustomDataLayer *layer;
1288         
1289         layer = customData_add_layer__internal(data, type, alloctype, layerdata,
1290                                                                                    totelem, name);
1291
1292         if(layer)
1293                 return layer->data;
1294
1295         return NULL;
1296 }
1297
1298
1299 int CustomData_free_layer(CustomData *data, int type, int totelem, int index)
1300 {
1301         int i;
1302         
1303         if (index < 0) return 0;
1304
1305         customData_free_layer__internal(&data->layers[index], totelem);
1306
1307         for (i=index+1; i < data->totlayer; ++i)
1308                 data->layers[i-1] = data->layers[i];
1309
1310         data->totlayer--;
1311
1312         /* if layer was last of type in array, set new active layer */
1313         if ((index >= data->totlayer) || (data->layers[index].type != type)) {
1314                 i = CustomData_get_layer_index(data, type);
1315                 
1316                 if (i >= 0)
1317                         for (; i < data->totlayer && data->layers[i].type == type; i++) {
1318                                 data->layers[i].active--;
1319                                 data->layers[i].active_rnd--;
1320                                 data->layers[i].active_clone--;
1321                                 data->layers[i].active_mask--;
1322                         }
1323         }
1324
1325         if (data->totlayer <= data->maxlayer-CUSTOMDATA_GROW)
1326                 customData_resize(data, -CUSTOMDATA_GROW);
1327
1328         customData_update_offsets(data);
1329
1330         return 1;
1331 }
1332
1333 int CustomData_free_layer_active(CustomData *data, int type, int totelem)
1334 {
1335         int index = 0;
1336         index = CustomData_get_active_layer_index(data, type);
1337         if (index < 0) return 0;
1338         return CustomData_free_layer(data, type, totelem, index);
1339 }
1340
1341
1342 void CustomData_free_layers(CustomData *data, int type, int totelem)
1343 {
1344         while (CustomData_has_layer(data, type))
1345                 CustomData_free_layer_active(data, type, totelem);
1346 }
1347
1348 int CustomData_has_layer(const CustomData *data, int type)
1349 {
1350         return (CustomData_get_layer_index(data, type) != -1);
1351 }
1352
1353 int CustomData_number_of_layers(const CustomData *data, int type)
1354 {
1355         int i, number = 0;
1356
1357         for(i = 0; i < data->totlayer; i++)
1358                 if(data->layers[i].type == type)
1359                         number++;
1360         
1361         return number;
1362 }
1363
1364 void *CustomData_duplicate_referenced_layer(struct CustomData *data, int type)
1365 {
1366         CustomDataLayer *layer;
1367         int layer_index;
1368
1369         /* get the layer index of the first layer of type */
1370         layer_index = CustomData_get_active_layer_index(data, type);
1371         if(layer_index < 0) return NULL;
1372
1373         layer = &data->layers[layer_index];
1374
1375         if (layer->flag & CD_FLAG_NOFREE) {
1376                 layer->data = MEM_dupallocN(layer->data);
1377                 layer->flag &= ~CD_FLAG_NOFREE;
1378         }
1379
1380         return layer->data;
1381 }
1382
1383 void *CustomData_duplicate_referenced_layer_named(struct CustomData *data,
1384                                                                                                   int type, char *name)
1385 {
1386         CustomDataLayer *layer;
1387         int layer_index;
1388
1389         /* get the layer index of the desired layer */
1390         layer_index = CustomData_get_named_layer_index(data, type, name);
1391         if(layer_index < 0) return NULL;
1392
1393         layer = &data->layers[layer_index];
1394
1395         if (layer->flag & CD_FLAG_NOFREE) {
1396                 layer->data = MEM_dupallocN(layer->data);
1397                 layer->flag &= ~CD_FLAG_NOFREE;
1398         }
1399
1400         return layer->data;
1401 }
1402
1403 void CustomData_free_temporary(CustomData *data, int totelem)
1404 {
1405         CustomDataLayer *layer;
1406         int i, j;
1407
1408         for(i = 0, j = 0; i < data->totlayer; ++i) {
1409                 layer = &data->layers[i];
1410
1411                 if (i != j)
1412                         data->layers[j] = data->layers[i];
1413
1414                 if ((layer->flag & CD_FLAG_TEMPORARY) == CD_FLAG_TEMPORARY)
1415                         customData_free_layer__internal(layer, totelem);
1416                 else
1417                         j++;
1418         }
1419
1420         data->totlayer = j;
1421
1422         if(data->totlayer <= data->maxlayer-CUSTOMDATA_GROW)
1423                 customData_resize(data, -CUSTOMDATA_GROW);
1424
1425         customData_update_offsets(data);
1426 }
1427
1428 void CustomData_set_only_copy(const struct CustomData *data,
1429                                                           CustomDataMask mask)
1430 {
1431         int i;
1432
1433         for(i = 0; i < data->totlayer; ++i)
1434                 if(!((int)mask & (int)(1 << (int)data->layers[i].type)))
1435                         data->layers[i].flag |= CD_FLAG_NOCOPY;
1436 }
1437
1438 void CustomData_copy_data(const CustomData *source, CustomData *dest,
1439                                                   int source_index, int dest_index, int count)
1440 {
1441         const LayerTypeInfo *typeInfo;
1442         int src_i, dest_i;
1443         int src_offset;
1444         int dest_offset;
1445
1446         /* copies a layer at a time */
1447         dest_i = 0;
1448         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1449
1450                 /* find the first dest layer with type >= the source type
1451                  * (this should work because layers are ordered by type)
1452                  */
1453                 while(dest_i < dest->totlayer
1454                           && dest->layers[dest_i].type < source->layers[src_i].type)
1455                         ++dest_i;
1456
1457                 /* if there are no more dest layers, we're done */
1458                 if(dest_i >= dest->totlayer) return;
1459
1460                 /* if we found a matching layer, copy the data */
1461                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1462                         char *src_data = source->layers[src_i].data;
1463                         char *dest_data = dest->layers[dest_i].data;
1464
1465                         typeInfo = layerType_getInfo(source->layers[src_i].type);
1466
1467                         src_offset = source_index * typeInfo->size;
1468                         dest_offset = dest_index * typeInfo->size;
1469
1470                         if(typeInfo->copy)
1471                                 typeInfo->copy(src_data + src_offset,
1472                                                                 dest_data + dest_offset,
1473                                                                 count);
1474                         else
1475                                 memcpy(dest_data + dest_offset,
1476                                            src_data + src_offset,
1477                                            count * typeInfo->size);
1478
1479                         /* if there are multiple source & dest layers of the same type,
1480                          * we don't want to copy all source layers to the same dest, so
1481                          * increment dest_i
1482                          */
1483                         ++dest_i;
1484                 }
1485         }
1486 }
1487
1488 void CustomData_free_elem(CustomData *data, int index, int count)
1489 {
1490         int i;
1491         const LayerTypeInfo *typeInfo;
1492
1493         for(i = 0; i < data->totlayer; ++i) {
1494                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
1495                         typeInfo = layerType_getInfo(data->layers[i].type);
1496
1497                         if(typeInfo->free) {
1498                                 int offset = typeInfo->size * index;
1499
1500                                 typeInfo->free((char *)data->layers[i].data + offset,
1501                                                            count, typeInfo->size);
1502                         }
1503                 }
1504         }
1505 }
1506
1507 #define SOURCE_BUF_SIZE 100
1508
1509 void CustomData_interp(const CustomData *source, CustomData *dest,
1510                                            int *src_indices, float *weights, float *sub_weights,
1511                                            int count, int dest_index)
1512 {
1513         int src_i, dest_i;
1514         int dest_offset;
1515         int j;
1516         void *source_buf[SOURCE_BUF_SIZE];
1517         void **sources = source_buf;
1518
1519         /* slow fallback in case we're interpolating a ridiculous number of
1520          * elements
1521          */
1522         if(count > SOURCE_BUF_SIZE)
1523                 sources = MEM_callocN(sizeof(*sources) * count,
1524                                                           "CustomData_interp sources");
1525
1526         /* interpolates a layer at a time */
1527         dest_i = 0;
1528         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1529                 const LayerTypeInfo *typeInfo= layerType_getInfo(source->layers[src_i].type);
1530                 if(!typeInfo->interp) continue;
1531
1532                 /* find the first dest layer with type >= the source type
1533                  * (this should work because layers are ordered by type)
1534                  */
1535                 while(dest_i < dest->totlayer
1536                           && dest->layers[dest_i].type < source->layers[src_i].type)
1537                         ++dest_i;
1538
1539                 /* if there are no more dest layers, we're done */
1540                 if(dest_i >= dest->totlayer) return;
1541
1542                 /* if we found a matching layer, copy the data */
1543                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1544                         void *src_data = source->layers[src_i].data;
1545
1546                         for(j = 0; j < count; ++j)
1547                                 sources[j] = (char *)src_data
1548                                                          + typeInfo->size * src_indices[j];
1549
1550                         dest_offset = dest_index * typeInfo->size;
1551
1552                         typeInfo->interp(sources, weights, sub_weights, count,
1553                                                    (char *)dest->layers[dest_i].data + dest_offset);
1554
1555                         /* if there are multiple source & dest layers of the same type,
1556                          * we don't want to copy all source layers to the same dest, so
1557                          * increment dest_i
1558                          */
1559                         ++dest_i;
1560                 }
1561         }
1562
1563         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
1564 }
1565
1566 void CustomData_swap(struct CustomData *data, int index, const int *corner_indices)
1567 {
1568         const LayerTypeInfo *typeInfo;
1569         int i;
1570
1571         for(i = 0; i < data->totlayer; ++i) {
1572                 typeInfo = layerType_getInfo(data->layers[i].type);
1573
1574                 if(typeInfo->swap) {
1575                         int offset = typeInfo->size * index;
1576
1577                         typeInfo->swap((char *)data->layers[i].data + offset, corner_indices);
1578                 }
1579         }
1580 }
1581
1582 void *CustomData_get(const CustomData *data, int index, int type)
1583 {
1584         int offset;
1585         int layer_index;
1586         
1587         /* get the layer index of the active layer of type */
1588         layer_index = CustomData_get_active_layer_index(data, type);
1589         if(layer_index < 0) return NULL;
1590
1591         /* get the offset of the desired element */
1592         offset = layerType_getInfo(type)->size * index;
1593
1594         return (char *)data->layers[layer_index].data + offset;
1595 }
1596
1597 void *CustomData_get_layer(const CustomData *data, int type)
1598 {
1599         /* get the layer index of the active layer of type */
1600         int layer_index = CustomData_get_active_layer_index(data, type);
1601         if(layer_index < 0) return NULL;
1602
1603         return data->layers[layer_index].data;
1604 }
1605
1606 void *CustomData_get_layer_n(const CustomData *data, int type, int n)
1607 {
1608         /* get the layer index of the active layer of type */
1609         int layer_index = CustomData_get_layer_index(data, type);
1610         if(layer_index < 0) return NULL;
1611
1612         return data->layers[layer_index+n].data;
1613 }
1614
1615 void *CustomData_get_layer_named(const struct CustomData *data, int type,
1616                                                                  char *name)
1617 {
1618         int layer_index = CustomData_get_named_layer_index(data, type, name);
1619         if(layer_index < 0) return NULL;
1620
1621         return data->layers[layer_index].data;
1622 }
1623
1624 void *CustomData_set_layer(const CustomData *data, int type, void *ptr)
1625 {
1626         /* get the layer index of the first layer of type */
1627         int layer_index = CustomData_get_active_layer_index(data, type);
1628
1629         if(layer_index < 0) return NULL;
1630
1631         data->layers[layer_index].data = ptr;
1632
1633         return ptr;
1634 }
1635
1636 void *CustomData_set_layer_n(const struct CustomData *data, int type, int n, void *ptr)
1637 {
1638         /* get the layer index of the first layer of type */
1639         int layer_index = CustomData_get_layer_index(data, type);
1640         if(layer_index < 0) return NULL;
1641
1642         data->layers[layer_index+n].data = ptr;
1643
1644         return ptr;
1645 }
1646
1647 void CustomData_set(const CustomData *data, int index, int type, void *source)
1648 {
1649         void *dest = CustomData_get(data, index, type);
1650         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1651
1652         if(!dest) return;
1653
1654         if(typeInfo->copy)
1655                 typeInfo->copy(source, dest, 1);
1656         else
1657                 memcpy(dest, source, typeInfo->size);
1658 }
1659
1660 /* EditMesh functions */
1661
1662 void CustomData_em_free_block(CustomData *data, void **block)
1663 {
1664         const LayerTypeInfo *typeInfo;
1665         int i;
1666
1667         if(!*block) return;
1668
1669         for(i = 0; i < data->totlayer; ++i) {
1670                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
1671                         typeInfo = layerType_getInfo(data->layers[i].type);
1672
1673                         if(typeInfo->free) {
1674                                 int offset = data->layers[i].offset;
1675                                 typeInfo->free((char*)*block + offset, 1, typeInfo->size);
1676                         }
1677                 }
1678         }
1679
1680         MEM_freeN(*block);
1681         *block = NULL;
1682 }
1683
1684 static void CustomData_em_alloc_block(CustomData *data, void **block)
1685 {
1686         /* TODO: optimize free/alloc */
1687
1688         if (*block)
1689                 CustomData_em_free_block(data, block);
1690
1691         if (data->totsize > 0)
1692                 *block = MEM_callocN(data->totsize, "CustomData EM block");
1693         else
1694                 *block = NULL;
1695 }
1696
1697 void CustomData_em_copy_data(const CustomData *source, CustomData *dest,
1698                                                         void *src_block, void **dest_block)
1699 {
1700         const LayerTypeInfo *typeInfo;
1701         int dest_i, src_i;
1702
1703         if (!*dest_block)
1704                 CustomData_em_alloc_block(dest, dest_block);
1705         
1706         /* copies a layer at a time */
1707         dest_i = 0;
1708         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1709
1710                 /* find the first dest layer with type >= the source type
1711                  * (this should work because layers are ordered by type)
1712                  */
1713                 while(dest_i < dest->totlayer
1714                           && dest->layers[dest_i].type < source->layers[src_i].type)
1715                         ++dest_i;
1716
1717                 /* if there are no more dest layers, we're done */
1718                 if(dest_i >= dest->totlayer) return;
1719
1720                 /* if we found a matching layer, copy the data */
1721                 if(dest->layers[dest_i].type == source->layers[src_i].type &&
1722                         strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
1723                         char *src_data = (char*)src_block + source->layers[src_i].offset;
1724                         char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
1725
1726                         typeInfo = layerType_getInfo(source->layers[src_i].type);
1727
1728                         if(typeInfo->copy)
1729                                 typeInfo->copy(src_data, dest_data, 1);
1730                         else
1731                                 memcpy(dest_data, src_data, typeInfo->size);
1732
1733                         /* if there are multiple source & dest layers of the same type,
1734                          * we don't want to copy all source layers to the same dest, so
1735                          * increment dest_i
1736                          */
1737                         ++dest_i;
1738                 }
1739         }
1740 }
1741
1742 void *CustomData_em_get(const CustomData *data, void *block, int type)
1743 {
1744         int layer_index;
1745         
1746         /* get the layer index of the first layer of type */
1747         layer_index = CustomData_get_active_layer_index(data, type);
1748         if(layer_index < 0) return NULL;
1749
1750         return (char *)block + data->layers[layer_index].offset;
1751 }
1752
1753 void *CustomData_em_get_n(const CustomData *data, void *block, int type, int n)
1754 {
1755         int layer_index;
1756         
1757         /* get the layer index of the first layer of type */
1758         layer_index = CustomData_get_layer_index(data, type);
1759         if(layer_index < 0) return NULL;
1760
1761         return (char *)block + data->layers[layer_index+n].offset;
1762 }
1763
1764 void CustomData_em_set(CustomData *data, void *block, int type, void *source)
1765 {
1766         void *dest = CustomData_em_get(data, block, type);
1767         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1768
1769         if(!dest) return;
1770
1771         if(typeInfo->copy)
1772                 typeInfo->copy(source, dest, 1);
1773         else
1774                 memcpy(dest, source, typeInfo->size);
1775 }
1776
1777 void CustomData_em_set_n(CustomData *data, void *block, int type, int n, void *source)
1778 {
1779         void *dest = CustomData_em_get_n(data, block, type, n);
1780         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1781
1782         if(!dest) return;
1783
1784         if(typeInfo->copy)
1785                 typeInfo->copy(source, dest, 1);
1786         else
1787                 memcpy(dest, source, typeInfo->size);
1788 }
1789
1790 void CustomData_em_interp(CustomData *data, void **src_blocks, float *weights,
1791                                                   float *sub_weights, int count, void *dest_block)
1792 {
1793         int i, j;
1794         void *source_buf[SOURCE_BUF_SIZE];
1795         void **sources = source_buf;
1796
1797         /* slow fallback in case we're interpolating a ridiculous number of
1798          * elements
1799          */
1800         if(count > SOURCE_BUF_SIZE)
1801                 sources = MEM_callocN(sizeof(*sources) * count,
1802                                                           "CustomData_interp sources");
1803
1804         /* interpolates a layer at a time */
1805         for(i = 0; i < data->totlayer; ++i) {
1806                 CustomDataLayer *layer = &data->layers[i];
1807                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
1808
1809                 if(typeInfo->interp) {
1810                         for(j = 0; j < count; ++j)
1811                                 sources[j] = (char *)src_blocks[j] + layer->offset;
1812
1813                         typeInfo->interp(sources, weights, sub_weights, count,
1814                                                           (char *)dest_block + layer->offset);
1815                 }
1816         }
1817
1818         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
1819 }
1820
1821 void CustomData_em_set_default(CustomData *data, void **block)
1822 {
1823         const LayerTypeInfo *typeInfo;
1824         int i;
1825
1826         if (!*block)
1827                 CustomData_em_alloc_block(data, block);
1828
1829         for(i = 0; i < data->totlayer; ++i) {
1830                 int offset = data->layers[i].offset;
1831
1832                 typeInfo = layerType_getInfo(data->layers[i].type);
1833
1834                 if(typeInfo->set_default)
1835                         typeInfo->set_default((char*)*block + offset, 1);
1836         }
1837 }
1838
1839 void CustomData_to_em_block(const CustomData *source, CustomData *dest,
1840                                                         int src_index, void **dest_block)
1841 {
1842         const LayerTypeInfo *typeInfo;
1843         int dest_i, src_i, src_offset;
1844
1845         if (!*dest_block)
1846                 CustomData_em_alloc_block(dest, dest_block);
1847         
1848         /* copies a layer at a time */
1849         dest_i = 0;
1850         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1851
1852                 /* find the first dest layer with type >= the source type
1853                  * (this should work because layers are ordered by type)
1854                  */
1855                 while(dest_i < dest->totlayer
1856                           && dest->layers[dest_i].type < source->layers[src_i].type)
1857                         ++dest_i;
1858
1859                 /* if there are no more dest layers, we're done */
1860                 if(dest_i >= dest->totlayer) return;
1861
1862                 /* if we found a matching layer, copy the data */
1863                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1864                         int offset = dest->layers[dest_i].offset;
1865                         char *src_data = source->layers[src_i].data;
1866                         char *dest_data = (char*)*dest_block + offset;
1867
1868                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
1869                         src_offset = src_index * typeInfo->size;
1870
1871                         if(typeInfo->copy)
1872                                 typeInfo->copy(src_data + src_offset, dest_data, 1);
1873                         else
1874                                 memcpy(dest_data, src_data + src_offset, typeInfo->size);
1875
1876                         /* if there are multiple source & dest layers of the same type,
1877                          * we don't want to copy all source layers to the same dest, so
1878                          * increment dest_i
1879                          */
1880                         ++dest_i;
1881                 }
1882         }
1883 }
1884
1885 void CustomData_from_em_block(const CustomData *source, CustomData *dest,
1886                                                           void *src_block, int dest_index)
1887 {
1888         const LayerTypeInfo *typeInfo;
1889         int dest_i, src_i, dest_offset;
1890
1891         /* copies a layer at a time */
1892         dest_i = 0;
1893         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1894
1895                 /* find the first dest layer with type >= the source type
1896                  * (this should work because layers are ordered by type)
1897                  */
1898                 while(dest_i < dest->totlayer
1899                           && dest->layers[dest_i].type < source->layers[src_i].type)
1900                         ++dest_i;
1901
1902                 /* if there are no more dest layers, we're done */
1903                 if(dest_i >= dest->totlayer) return;
1904
1905                 /* if we found a matching layer, copy the data */
1906                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1907                         int offset = source->layers[src_i].offset;
1908                         char *src_data = (char*)src_block + offset;
1909                         char *dest_data = dest->layers[dest_i].data;
1910
1911                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
1912                         dest_offset = dest_index * typeInfo->size;
1913
1914                         if(typeInfo->copy)
1915                                 typeInfo->copy(src_data, dest_data + dest_offset, 1);
1916                         else
1917                                 memcpy(dest_data + dest_offset, src_data, typeInfo->size);
1918
1919                         /* if there are multiple source & dest layers of the same type,
1920                          * we don't want to copy all source layers to the same dest, so
1921                          * increment dest_i
1922                          */
1923                         ++dest_i;
1924                 }
1925         }
1926
1927 }
1928
1929 /*Bmesh functions*/
1930 /*needed to convert to/from different face reps*/
1931 void CustomData_to_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata)
1932 {
1933         int i;
1934         for(i=0; i < fdata->totlayer; i++){
1935                 if(fdata->layers[i].type == CD_MTFACE){
1936                         CustomData_add_layer(pdata, CD_MTEXPOLY, CD_CALLOC, &(fdata->layers[i].name), 0);
1937                         CustomData_add_layer(ldata, CD_MLOOPUV, CD_CALLOC, &(fdata->layers[i].name), 0);
1938                 }
1939                 else if(fdata->layers[i].type == CD_MCOL)
1940                         CustomData_add_layer(ldata, CD_MLOOPCOL, CD_CALLOC, &(fdata->layers[i].name), 0);
1941         }               
1942 }
1943 void CustomData_from_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata, int total){
1944         int i;
1945         for(i=0; i < pdata->totlayer; i++){
1946                 if(pdata->layers[i].type == CD_MTEXPOLY)
1947                         CustomData_add_layer(fdata, CD_MTFACE, CD_CALLOC, &(pdata->layers[i].name), total);
1948         }
1949         for(i=0; i < ldata->totlayer; i++){
1950                 if(ldata->layers[i].type == CD_MLOOPCOL)
1951                         CustomData_add_layer(fdata, CD_MCOL, CD_CALLOC, &(ldata->layers[i].name), total);
1952         }
1953 }
1954
1955
1956 void CustomData_bmesh_init_pool(CustomData *data, int allocsize){
1957         if(data->totlayer)data->pool = BLI_mempool_create(data->totsize, allocsize, allocsize, 0);
1958 }
1959
1960 void CustomData_bmesh_free_block(CustomData *data, void **block)
1961 {
1962         const LayerTypeInfo *typeInfo;
1963         int i;
1964
1965         if(!*block) return;
1966         for(i = 0; i < data->totlayer; ++i) {
1967                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
1968                         typeInfo = layerType_getInfo(data->layers[i].type);
1969
1970                         if(typeInfo->free) {
1971                                 int offset = data->layers[i].offset;
1972                                 typeInfo->free((char*)*block + offset, 1, typeInfo->size);
1973                         }
1974                 }
1975         }
1976
1977         BLI_mempool_free(data->pool, *block);
1978         *block = NULL;
1979 }
1980
1981 static void CustomData_bmesh_alloc_block(CustomData *data, void **block)
1982 {
1983
1984         if (*block)
1985                 CustomData_bmesh_free_block(data, block);
1986
1987         if (data->totsize > 0)
1988                 *block = BLI_mempool_calloc(data->pool);
1989         else
1990                 *block = NULL;
1991 }
1992
1993 void CustomData_bmesh_copy_data(const CustomData *source, CustomData *dest,
1994                                                         void *src_block, void **dest_block)
1995 {
1996         const LayerTypeInfo *typeInfo;
1997         int dest_i, src_i;
1998
1999         if (!*dest_block)
2000                 CustomData_bmesh_alloc_block(dest, dest_block);
2001         
2002         /* copies a layer at a time */
2003         dest_i = 0;
2004         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2005
2006                 /* find the first dest layer with type >= the source type
2007                  * (this should work because layers are ordered by type)
2008                  */
2009                 while(dest_i < dest->totlayer
2010                           && dest->layers[dest_i].type < source->layers[src_i].type)
2011                         ++dest_i;
2012
2013                 /* if there are no more dest layers, we're done */
2014                 if(dest_i >= dest->totlayer) return;
2015
2016                 /* if we found a matching layer, copy the data */
2017                 if(dest->layers[dest_i].type == source->layers[src_i].type &&
2018                         strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
2019                         char *src_data = (char*)src_block + source->layers[src_i].offset;
2020                         char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
2021
2022                         typeInfo = layerType_getInfo(source->layers[src_i].type);
2023
2024                         if(typeInfo->copy)
2025                                 typeInfo->copy(src_data, dest_data, 1);
2026                         else
2027                                 memcpy(dest_data, src_data, typeInfo->size);
2028
2029                         /* if there are multiple source & dest layers of the same type,
2030                          * we don't want to copy all source layers to the same dest, so
2031                          * increment dest_i
2032                          */
2033                         ++dest_i;
2034                 }
2035         }
2036 }
2037
2038 /*Bmesh Custom Data Functions. Should replace editmesh ones with these as well, due to more effecient memory alloc*/
2039 void *CustomData_bmesh_get(const CustomData *data, void *block, int type)
2040 {
2041         int layer_index;
2042         
2043         /* get the layer index of the first layer of type */
2044         layer_index = CustomData_get_active_layer_index(data, type);
2045         if(layer_index < 0) return NULL;
2046
2047         return (char *)block + data->layers[layer_index].offset;
2048 }
2049
2050 void *CustomData_bmesh_get_n(const CustomData *data, void *block, int type, int n)
2051 {
2052         int layer_index;
2053         
2054         /* get the layer index of the first layer of type */
2055         layer_index = CustomData_get_layer_index(data, type);
2056         if(layer_index < 0) return NULL;
2057
2058         return (char *)block + data->layers[layer_index+n].offset;
2059 }
2060
2061 void CustomData_bmesh_set(const CustomData *data, void *block, int type, void *source)
2062 {
2063         void *dest = CustomData_bmesh_get(data, block, type);
2064         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2065
2066         if(!dest) return;
2067
2068         if(typeInfo->copy)
2069                 typeInfo->copy(source, dest, 1);
2070         else
2071                 memcpy(dest, source, typeInfo->size);
2072 }
2073
2074 void CustomData_bmesh_set_n(CustomData *data, void *block, int type, int n, void *source)
2075 {
2076         void *dest = CustomData_bmesh_get_n(data, block, type, n);
2077         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2078
2079         if(!dest) return;
2080
2081         if(typeInfo->copy)
2082                 typeInfo->copy(source, dest, 1);
2083         else
2084                 memcpy(dest, source, typeInfo->size);
2085 }
2086
2087 void CustomData_bmesh_interp(CustomData *data, void **src_blocks, float *weights,
2088                                                   float *sub_weights, int count, void *dest_block)
2089 {
2090         int i, j;
2091         void *source_buf[SOURCE_BUF_SIZE];
2092         void **sources = source_buf;
2093
2094         /* slow fallback in case we're interpolating a ridiculous number of
2095          * elements
2096          */
2097         if(count > SOURCE_BUF_SIZE)
2098                 sources = MEM_callocN(sizeof(*sources) * count,
2099                                                           "CustomData_interp sources");
2100
2101         /* interpolates a layer at a time */
2102         for(i = 0; i < data->totlayer; ++i) {
2103                 CustomDataLayer *layer = &data->layers[i];
2104                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
2105                 if(typeInfo->interp) {
2106                         for(j = 0; j < count; ++j)
2107                                 sources[j] = (char *)src_blocks[j] + layer->offset;
2108
2109                         typeInfo->interp(sources, weights, sub_weights, count,
2110                                                           (char *)dest_block + layer->offset);
2111                 }
2112         }
2113
2114         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
2115 }
2116
2117 void CustomData_bmesh_set_default(CustomData *data, void **block)
2118 {
2119         const LayerTypeInfo *typeInfo;
2120         int i;
2121
2122         if (!*block)
2123                 CustomData_bmesh_alloc_block(data, block);
2124
2125         for(i = 0; i < data->totlayer; ++i) {
2126                 int offset = data->layers[i].offset;
2127
2128                 typeInfo = layerType_getInfo(data->layers[i].type);
2129
2130                 if(typeInfo->set_default)
2131                         typeInfo->set_default((char*)*block + offset, 1);
2132         }
2133 }
2134
2135 void CustomData_to_bmesh_block(const CustomData *source, CustomData *dest,
2136                                                         int src_index, void **dest_block)
2137 {
2138         const LayerTypeInfo *typeInfo;
2139         int dest_i, src_i, src_offset;
2140
2141         if (!*dest_block)
2142                 CustomData_bmesh_alloc_block(dest, dest_block);
2143         
2144         /* copies a layer at a time */
2145         dest_i = 0;
2146         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2147
2148                 /* find the first dest layer with type >= the source type
2149                  * (this should work because layers are ordered by type)
2150                  */
2151                 while(dest_i < dest->totlayer
2152                           && dest->layers[dest_i].type < source->layers[src_i].type)
2153                         ++dest_i;
2154
2155                 /* if there are no more dest layers, we're done */
2156                 if(dest_i >= dest->totlayer) return;
2157
2158                 /* if we found a matching layer, copy the data */
2159                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2160                         int offset = dest->layers[dest_i].offset;
2161                         char *src_data = source->layers[src_i].data;
2162                         char *dest_data = (char*)*dest_block + offset;
2163
2164                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2165                         src_offset = src_index * typeInfo->size;
2166
2167                         if(typeInfo->copy)
2168                                 typeInfo->copy(src_data + src_offset, dest_data, 1);
2169                         else
2170                                 memcpy(dest_data, src_data + src_offset, typeInfo->size);
2171
2172                         /* if there are multiple source & dest layers of the same type,
2173                          * we don't want to copy all source layers to the same dest, so
2174                          * increment dest_i
2175                          */
2176                         ++dest_i;
2177                 }
2178         }
2179 }
2180
2181 void CustomData_from_bmesh_block(const CustomData *source, CustomData *dest,
2182                                                           void *src_block, int dest_index)
2183 {
2184         const LayerTypeInfo *typeInfo;
2185         int dest_i, src_i, dest_offset;
2186
2187         /* copies a layer at a time */
2188         dest_i = 0;
2189         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2190
2191                 /* find the first dest layer with type >= the source type
2192                  * (this should work because layers are ordered by type)
2193                  */
2194                 while(dest_i < dest->totlayer
2195                           && dest->layers[dest_i].type < source->layers[src_i].type)
2196                         ++dest_i;
2197
2198                 /* if there are no more dest layers, we're done */
2199                 if(dest_i >= dest->totlayer) return;
2200
2201                 /* if we found a matching layer, copy the data */
2202                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2203                         int offset = source->layers[src_i].offset;
2204                         char *src_data = (char*)src_block + offset;
2205                         char *dest_data = dest->layers[dest_i].data;
2206
2207                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2208                         dest_offset = dest_index * typeInfo->size;
2209
2210                         if(typeInfo->copy)
2211                                 typeInfo->copy(src_data, dest_data + dest_offset, 1);
2212                         else
2213                                 memcpy(dest_data + dest_offset, src_data, typeInfo->size);
2214
2215                         /* if there are multiple source & dest layers of the same type,
2216                          * we don't want to copy all source layers to the same dest, so
2217                          * increment dest_i
2218                          */
2219                         ++dest_i;
2220                 }
2221         }
2222
2223 }
2224
2225 void CustomData_file_write_info(int type, char **structname, int *structnum)
2226 {
2227         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2228
2229         *structname = typeInfo->structname;
2230         *structnum = typeInfo->structnum;
2231 }
2232
2233 int CustomData_sizeof(int type)
2234 {
2235         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2236
2237         return typeInfo->size;
2238 }
2239
2240 const char *CustomData_layertype_name(int type)
2241 {
2242         return layerType_getName(type);
2243 }
2244
2245 static int  CustomData_is_property_layer(int type)
2246 {
2247         if((type == CD_PROP_FLT) || (type == CD_PROP_INT) || (type == CD_PROP_STR))
2248                 return 1;
2249         return 0;
2250 }
2251
2252 void CustomData_set_layer_unique_name(CustomData *data, int index)
2253 {
2254         char tempname[64];
2255         int number, i, type;
2256         char *dot, *name;
2257         CustomDataLayer *layer, *nlayer= &data->layers[index];
2258         const LayerTypeInfo *typeInfo= layerType_getInfo(nlayer->type);
2259
2260         if (!typeInfo->defaultname)
2261                 return;
2262
2263         type = nlayer->type;
2264         name = nlayer->name;
2265
2266         if (name[0] == '\0')
2267                 BLI_strncpy(nlayer->name, typeInfo->defaultname, sizeof(nlayer->name));
2268         
2269         /* see if there is a duplicate */
2270         for(i=0; i<data->totlayer; i++) {
2271                 layer = &data->layers[i];
2272                 
2273                 if(CustomData_is_property_layer(type)){
2274                         if(i!=index && CustomData_is_property_layer(layer->type) && 
2275                                 strcmp(layer->name, name)==0)
2276                                         break;  
2277                 
2278                 }
2279                 else{
2280                         if(i!=index && layer->type==type && strcmp(layer->name, name)==0)
2281                                 break;
2282                 }
2283         }
2284
2285         if(i == data->totlayer)
2286                 return;
2287
2288         /* strip off the suffix */
2289         dot = strchr(nlayer->name, '.');
2290         if(dot) *dot=0;
2291         
2292         for(number=1; number <=999; number++) {
2293                 sprintf(tempname, "%s.%03d", nlayer->name, number);
2294
2295                 for(i=0; i<data->totlayer; i++) {
2296                         layer = &data->layers[i];
2297                         
2298                         if(CustomData_is_property_layer(type)){
2299                                 if(i!=index && CustomData_is_property_layer(layer->type) && 
2300                                         strcmp(layer->name, tempname)==0)
2301
2302                                 break;
2303                         }
2304                         else{
2305                                 if(i!=index && layer->type==type && strcmp(layer->name, tempname)==0)
2306                                         break;
2307                         }
2308                 }
2309
2310                 if(i == data->totlayer) {
2311                         BLI_strncpy(nlayer->name, tempname, sizeof(nlayer->name));
2312                         return;
2313                 }
2314         }       
2315 }
2316
2317 int CustomData_verify_versions(struct CustomData *data, int index)
2318 {
2319         const LayerTypeInfo *typeInfo;
2320         CustomDataLayer *layer = &data->layers[index];
2321         int i, keeplayer = 1;
2322
2323         if (layer->type >= CD_NUMTYPES) {
2324                 keeplayer = 0; /* unknown layer type from future version */
2325         }
2326         else {
2327                 typeInfo = layerType_getInfo(layer->type);
2328
2329                 if (!typeInfo->defaultname && (index > 0) &&
2330                         data->layers[index-1].type == layer->type)
2331                         keeplayer = 0; /* multiple layers of which we only support one */
2332         }
2333
2334         if (!keeplayer) {
2335                 for (i=index+1; i < data->totlayer; ++i)
2336                         data->layers[i-1] = data->layers[i];
2337                 data->totlayer--;
2338         }
2339
2340         return keeplayer;
2341 }
2342
2343 /****************************** External Files *******************************/
2344
2345 static void customdata_external_filename(char filename[FILE_MAX], ID *id, CustomDataExternal *external)
2346 {
2347         char *path = (id->lib)? id->lib->filepath: G.main->name;
2348
2349         BLI_strncpy(filename, external->filename, FILE_MAX);
2350         BLI_path_abs(filename, path);
2351 }
2352
2353 void CustomData_external_reload(CustomData *data, ID *UNUSED(id), CustomDataMask mask, int totelem)
2354 {
2355         CustomDataLayer *layer;
2356         const LayerTypeInfo *typeInfo;
2357         int i;
2358
2359         for(i=0; i<data->totlayer; i++) {
2360                 layer = &data->layers[i];
2361                 typeInfo = layerType_getInfo(layer->type);
2362
2363                 if(!(mask & (1<<layer->type)));
2364                 else if((layer->flag & CD_FLAG_EXTERNAL) && (layer->flag & CD_FLAG_IN_MEMORY)) {
2365                         if(typeInfo->free)
2366                                 typeInfo->free(layer->data, totelem, typeInfo->size);
2367                         layer->flag &= ~CD_FLAG_IN_MEMORY;
2368                 }
2369         }
2370 }
2371
2372 void CustomData_external_read(CustomData *data, ID *id, CustomDataMask mask, int totelem)
2373 {
2374         CustomDataExternal *external= data->external;
2375         CustomDataLayer *layer;
2376         CDataFile *cdf;
2377         CDataFileLayer *blay;
2378         char filename[FILE_MAX];
2379         const LayerTypeInfo *typeInfo;
2380         int i, update = 0;
2381
2382         if(!external)
2383                 return;
2384         
2385         for(i=0; i<data->totlayer; i++) {
2386                 layer = &data->layers[i];
2387                 typeInfo = layerType_getInfo(layer->type);
2388
2389                 if(!(mask & (1<<layer->type)));
2390                 else if(layer->flag & CD_FLAG_IN_MEMORY);
2391                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read)
2392                         update= 1;
2393         }
2394
2395         if(!update)
2396                 return;
2397
2398         customdata_external_filename(filename, id, external);
2399
2400         cdf= cdf_create(CDF_TYPE_MESH);
2401         if(!cdf_read_open(cdf, filename)) {
2402                 fprintf(stderr, "Failed to read %s layer from %s.\n", layerType_getName(layer->type), filename);
2403                 return;
2404         }
2405
2406         for(i=0; i<data->totlayer; i++) {
2407                 layer = &data->layers[i];
2408                 typeInfo = layerType_getInfo(layer->type);
2409
2410                 if(!(mask & (1<<layer->type)));
2411                 else if(layer->flag & CD_FLAG_IN_MEMORY);
2412                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read) {
2413                         blay= cdf_layer_find(cdf, layer->type, layer->name);
2414
2415                         if(blay) {
2416                                 if(cdf_read_layer(cdf, blay)) {
2417                                         if(typeInfo->read(cdf, layer->data, totelem));
2418                                         else break;
2419                                         layer->flag |= CD_FLAG_IN_MEMORY;
2420                                 }
2421                                 else
2422                                         break;
2423                         }
2424                 }
2425         }
2426
2427         cdf_read_close(cdf);
2428         cdf_free(cdf);
2429 }
2430
2431 void CustomData_external_write(CustomData *data, ID *id, CustomDataMask mask, int totelem, int free)
2432 {
2433         CustomDataExternal *external= data->external;
2434         CustomDataLayer *layer;
2435         CDataFile *cdf;
2436         CDataFileLayer *blay;
2437         const LayerTypeInfo *typeInfo;
2438         int i, update = 0;
2439         char filename[FILE_MAX];
2440
2441         if(!external)
2442                 return;
2443
2444         /* test if there is anything to write */
2445         for(i=0; i<data->totlayer; i++) {
2446                 layer = &data->layers[i];
2447                 typeInfo = layerType_getInfo(layer->type);
2448
2449                 if(!(mask & (1<<layer->type)));
2450                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write)
2451                         update= 1;
2452         }
2453
2454         if(!update)
2455                 return;
2456
2457         /* make sure data is read before we try to write */
2458         CustomData_external_read(data, id, mask, totelem);
2459         customdata_external_filename(filename, id, external);
2460
2461         cdf= cdf_create(CDF_TYPE_MESH);
2462
2463         for(i=0; i<data->totlayer; i++) {
2464                 layer = &data->layers[i];
2465                 typeInfo = layerType_getInfo(layer->type);
2466
2467                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->filesize) {
2468                         if(layer->flag & CD_FLAG_IN_MEMORY) {
2469                                 cdf_layer_add(cdf, layer->type, layer->name,
2470                                         typeInfo->filesize(cdf, layer->data, totelem));
2471                         }
2472                         else {
2473                                 cdf_free(cdf);
2474                                 return; /* read failed for a layer! */
2475                         }
2476                 }
2477         }
2478
2479         if(!cdf_write_open(cdf, filename)) {
2480                 fprintf(stderr, "Failed to open %s for writing.\n", filename);
2481                 return;
2482         }
2483
2484         for(i=0; i<data->totlayer; i++) {
2485                 layer = &data->layers[i];
2486                 typeInfo = layerType_getInfo(layer->type);
2487
2488                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) {
2489                         blay= cdf_layer_find(cdf, layer->type, layer->name);
2490
2491                         if(cdf_write_layer(cdf, blay)) {
2492                                 if(typeInfo->write(cdf, layer->data, totelem));
2493                                 else break;
2494                         }
2495                         else
2496                                 break;
2497                 }
2498         }
2499
2500         if(i != data->totlayer) {
2501                 fprintf(stderr, "Failed to write data to %s.\n", filename);
2502                 cdf_free(cdf);
2503                 return;
2504         }
2505
2506         for(i=0; i<data->totlayer; i++) {
2507                 layer = &data->layers[i];
2508                 typeInfo = layerType_getInfo(layer->type);
2509
2510                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) {
2511                         if(free) {
2512                                 if(typeInfo->free)
2513                                         typeInfo->free(layer->data, totelem, typeInfo->size);
2514                                 layer->flag &= ~CD_FLAG_IN_MEMORY;
2515                         }
2516                 }
2517         }
2518
2519         cdf_write_close(cdf);
2520         cdf_free(cdf);
2521 }
2522
2523 void CustomData_external_add(CustomData *data, ID *UNUSED(id), int type, int UNUSED(totelem), const char *filename)
2524 {
2525         CustomDataExternal *external= data->external;
2526         CustomDataLayer *layer;
2527         int layer_index;
2528
2529         layer_index = CustomData_get_active_layer_index(data, type);
2530         if(layer_index < 0) return;
2531
2532         layer = &data->layers[layer_index];
2533
2534         if(layer->flag & CD_FLAG_EXTERNAL)
2535                 return;
2536
2537         if(!external) {
2538                 external= MEM_callocN(sizeof(CustomDataExternal), "CustomDataExternal");
2539                 data->external= external;
2540         }
2541         BLI_strncpy(external->filename, filename, sizeof(external->filename));
2542
2543         layer->flag |= CD_FLAG_EXTERNAL|CD_FLAG_IN_MEMORY;
2544 }
2545
2546 void CustomData_external_remove(CustomData *data, ID *id, int type, int totelem)
2547 {
2548         CustomDataExternal *external= data->external;
2549         CustomDataLayer *layer;
2550         //char filename[FILE_MAX];
2551         int layer_index; // i, remove_file;
2552
2553         layer_index = CustomData_get_active_layer_index(data, type);
2554         if(layer_index < 0) return;
2555
2556         layer = &data->layers[layer_index];
2557
2558         if(!external)
2559                 return;
2560
2561         if(layer->flag & CD_FLAG_EXTERNAL) {
2562                 if(!(layer->flag & CD_FLAG_IN_MEMORY))
2563                         CustomData_external_read(data, id, (1<<layer->type), totelem);
2564
2565                 layer->flag &= ~CD_FLAG_EXTERNAL;
2566
2567 #if 0
2568                 remove_file= 1;
2569                 for(i=0; i<data->totlayer; i++)
2570                         if(data->layers[i].flag & CD_FLAG_EXTERNAL)
2571                                 remove_file= 0;
2572
2573                 if(remove_file) {
2574                         customdata_external_filename(filename, id, external);
2575                         cdf_remove(filename);
2576                         CustomData_external_free(data);
2577                 }
2578 #endif
2579         }
2580 }
2581
2582 int CustomData_external_test(CustomData *data, int type)
2583 {
2584         CustomDataLayer *layer;
2585         int layer_index;
2586
2587         layer_index = CustomData_get_active_layer_index(data, type);
2588         if(layer_index < 0) return 0;
2589
2590         layer = &data->layers[layer_index];
2591         return (layer->flag & CD_FLAG_EXTERNAL);
2592 }
2593
2594 #if 0
2595 void CustomData_external_remove_object(CustomData *data, ID *id)
2596 {
2597         CustomDataExternal *external= data->external;
2598         char filename[FILE_MAX];
2599
2600         if(!external)
2601                 return;
2602
2603         customdata_external_filename(filename, id, external);
2604         cdf_remove(filename);
2605         CustomData_external_free(data);
2606 }
2607 #endif
2608