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