=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         customData_update_typemap(data);
1225 }
1226
1227 int CustomData_get_layer_index(const CustomData *data, int type)
1228 {
1229         int i; 
1230
1231         for(i=0; i < data->totlayer; ++i)
1232                 if(data->layers[i].type == type)
1233                         return i;
1234
1235         return -1;
1236 }
1237
1238 int CustomData_get_layer_index_n(const struct CustomData *data, int type, int n)
1239 {
1240         int i; 
1241
1242         for(i=0; i < data->totlayer; ++i)
1243                 if(data->layers[i].type == type)
1244                         return i + n;
1245
1246         return -1;      
1247 }
1248
1249 int CustomData_get_named_layer_index(const CustomData *data, int type, const char *name)
1250 {
1251         int i;
1252
1253         for(i=0; i < data->totlayer; ++i)
1254                 if(data->layers[i].type == type && strcmp(data->layers[i].name, name)==0)
1255                         return i;
1256
1257         return -1;
1258 }
1259
1260 int CustomData_get_active_layer_index(const CustomData *data, int type)
1261 {
1262         if (!data->totlayer)
1263                 return -1;
1264
1265         if (data->typemap[type] != -1) {
1266                 return data->typemap[type] + data->layers[data->typemap[type]].active;
1267         }
1268
1269         return -1;
1270 }
1271
1272 int CustomData_get_render_layer_index(const CustomData *data, int type)
1273 {
1274         int i;
1275
1276         for(i=0; i < data->totlayer; ++i)
1277                 if(data->layers[i].type == type)
1278                         return i + data->layers[i].active_rnd;
1279
1280         return -1;
1281 }
1282
1283 int CustomData_get_clone_layer_index(const CustomData *data, int type)
1284 {
1285         int i;
1286
1287         for(i=0; i < data->totlayer; ++i)
1288                 if(data->layers[i].type == type)
1289                         return i + data->layers[i].active_clone;
1290
1291         return -1;
1292 }
1293
1294 int CustomData_get_stencil_layer_index(const CustomData *data, int type)
1295 {
1296         int i;
1297
1298         for(i=0; i < data->totlayer; ++i)
1299                 if(data->layers[i].type == type)
1300                         return i + data->layers[i].active_mask;
1301
1302         return -1;
1303 }
1304
1305 int CustomData_get_active_layer(const CustomData *data, int type)
1306 {
1307         int i;
1308
1309         for(i=0; i < data->totlayer; ++i)
1310                 if(data->layers[i].type == type)
1311                         return data->layers[i].active;
1312
1313         return -1;
1314 }
1315
1316 int CustomData_get_render_layer(const CustomData *data, int type)
1317 {
1318         int i;
1319
1320         for(i=0; i < data->totlayer; ++i)
1321                 if(data->layers[i].type == type)
1322                         return data->layers[i].active_rnd;
1323
1324         return -1;
1325 }
1326
1327 int CustomData_get_clone_layer(const CustomData *data, int type)
1328 {
1329         int i;
1330
1331         for(i=0; i < data->totlayer; ++i)
1332                 if(data->layers[i].type == type)
1333                         return data->layers[i].active_clone;
1334
1335         return -1;
1336 }
1337
1338 int CustomData_get_stencil_layer(const CustomData *data, int type)
1339 {
1340         int i;
1341
1342         for(i=0; i < data->totlayer; ++i)
1343                 if(data->layers[i].type == type)
1344                         return data->layers[i].active_mask;
1345
1346         return -1;
1347 }
1348
1349 void CustomData_set_layer_active(CustomData *data, int type, int n)
1350 {
1351         int i;
1352
1353         for(i=0; i < data->totlayer; ++i)
1354                 if(data->layers[i].type == type)
1355                         data->layers[i].active = n;
1356 }
1357
1358 void CustomData_set_layer_render(CustomData *data, int type, int n)
1359 {
1360         int i;
1361
1362         for(i=0; i < data->totlayer; ++i)
1363                 if(data->layers[i].type == type)
1364                         data->layers[i].active_rnd = n;
1365 }
1366
1367 void CustomData_set_layer_clone(CustomData *data, int type, int n)
1368 {
1369         int i;
1370
1371         for(i=0; i < data->totlayer; ++i)
1372                 if(data->layers[i].type == type)
1373                         data->layers[i].active_clone = n;
1374 }
1375
1376 void CustomData_set_layer_stencil(CustomData *data, int type, int n)
1377 {
1378         int i;
1379
1380         for(i=0; i < data->totlayer; ++i)
1381                 if(data->layers[i].type == type)
1382                         data->layers[i].active_mask = n;
1383 }
1384
1385 /* for using with an index from CustomData_get_active_layer_index and CustomData_get_render_layer_index */
1386 void CustomData_set_layer_active_index(CustomData *data, int type, int n)
1387 {
1388         int i;
1389
1390         for(i=0; i < data->totlayer; ++i)
1391                 if(data->layers[i].type == type)
1392                         data->layers[i].active = n-i;
1393 }
1394
1395 void CustomData_set_layer_render_index(CustomData *data, int type, int n)
1396 {
1397         int i;
1398
1399         for(i=0; i < data->totlayer; ++i)
1400                 if(data->layers[i].type == type)
1401                         data->layers[i].active_rnd = n-i;
1402 }
1403
1404 void CustomData_set_layer_clone_index(CustomData *data, int type, int n)
1405 {
1406         int i;
1407
1408         for(i=0; i < data->totlayer; ++i)
1409                 if(data->layers[i].type == type)
1410                         data->layers[i].active_clone = n-i;
1411 }
1412
1413 void CustomData_set_layer_stencil_index(CustomData *data, int type, int n)
1414 {
1415         int i;
1416
1417         for(i=0; i < data->totlayer; ++i)
1418                 if(data->layers[i].type == type)
1419                         data->layers[i].active_mask = n-i;
1420 }
1421
1422 void CustomData_set_layer_flag(struct CustomData *data, int type, int flag)
1423 {
1424         int i;
1425
1426         for(i=0; i < data->totlayer; ++i)
1427                 if(data->layers[i].type == type)
1428                         data->layers[i].flag |= flag;
1429 }
1430
1431 static int customData_resize(CustomData *data, int amount)
1432 {
1433         CustomDataLayer *tmp = MEM_callocN(sizeof(*tmp)*(data->maxlayer + amount),
1434                                                                            "CustomData->layers");
1435         if(!tmp) return 0;
1436
1437         data->maxlayer += amount;
1438         if (data->layers) {
1439                 memcpy(tmp, data->layers, sizeof(*tmp) * data->totlayer);
1440                 MEM_freeN(data->layers);
1441         }
1442         data->layers = tmp;
1443
1444         return 1;
1445 }
1446
1447 static CustomDataLayer *customData_add_layer__internal(CustomData *data,
1448         int type, int alloctype, void *layerdata, int totelem, const char *name)
1449 {
1450         const LayerTypeInfo *typeInfo= layerType_getInfo(type);
1451         int size = typeInfo->size * totelem, flag = 0, index = data->totlayer;
1452         void *newlayerdata;
1453
1454         if (!typeInfo->defaultname && CustomData_has_layer(data, type)) {
1455                 return &data->layers[CustomData_get_layer_index(data, type)];
1456         }
1457
1458         if((alloctype == CD_ASSIGN) || (alloctype == CD_REFERENCE)) {
1459                 newlayerdata = layerdata;
1460         }
1461         else {
1462                 newlayerdata = MEM_callocN(size, layerType_getName(type));
1463                 if(!newlayerdata)
1464                         return NULL;
1465         }
1466
1467         if (alloctype == CD_DUPLICATE && layerdata) {
1468                 if(typeInfo->copy)
1469                         typeInfo->copy(layerdata, newlayerdata, totelem);
1470                 else
1471                         memcpy(newlayerdata, layerdata, size);
1472         }
1473         else if (alloctype == CD_DEFAULT) {
1474                 if(typeInfo->set_default)
1475                         typeInfo->set_default((char*)newlayerdata, totelem);
1476         }
1477         else if (alloctype == CD_REFERENCE)
1478                 flag |= CD_FLAG_NOFREE;
1479
1480         if(index >= data->maxlayer) {
1481                 if(!customData_resize(data, CUSTOMDATA_GROW)) {
1482                         if(newlayerdata != layerdata)
1483                                 MEM_freeN(newlayerdata);
1484                         return NULL;
1485                 }
1486         }
1487         
1488         data->totlayer++;
1489
1490         /* keep layers ordered by type */
1491         for( ; index > 0 && data->layers[index - 1].type > type; --index)
1492                 data->layers[index] = data->layers[index - 1];
1493
1494         data->layers[index].type = type;
1495         data->layers[index].flag = flag;
1496         data->layers[index].data = newlayerdata;
1497
1498         if(name || (name=typeInfo->defaultname)) {
1499                 BLI_strncpy(data->layers[index].name, name, 32);
1500                 CustomData_set_layer_unique_name(data, index);
1501         }
1502         else
1503                 data->layers[index].name[0] = '\0';
1504
1505         if(index > 0 && data->layers[index-1].type == type) {
1506                 data->layers[index].active = data->layers[index-1].active;
1507                 data->layers[index].active_rnd = data->layers[index-1].active_rnd;
1508                 data->layers[index].active_clone = data->layers[index-1].active_clone;
1509                 data->layers[index].active_mask = data->layers[index-1].active_mask;
1510         } else {
1511                 data->layers[index].active = 0;
1512                 data->layers[index].active_rnd = 0;
1513                 data->layers[index].active_clone = 0;
1514                 data->layers[index].active_mask = 0;
1515         }
1516         
1517         customData_update_offsets(data);
1518
1519         return &data->layers[index];
1520 }
1521
1522 void *CustomData_add_layer(CustomData *data, int type, int alloctype,
1523                                                    void *layerdata, int totelem)
1524 {
1525         CustomDataLayer *layer;
1526         const LayerTypeInfo *typeInfo= layerType_getInfo(type);
1527         
1528         layer = customData_add_layer__internal(data, type, alloctype, layerdata,
1529                                                                                    totelem, typeInfo->defaultname);
1530         customData_update_typemap(data);
1531
1532         if(layer)
1533                 return layer->data;
1534
1535         return NULL;
1536 }
1537
1538 /*same as above but accepts a name*/
1539 void *CustomData_add_layer_named(CustomData *data, int type, int alloctype,
1540                                                    void *layerdata, int totelem, const char *name)
1541 {
1542         CustomDataLayer *layer;
1543         
1544         layer = customData_add_layer__internal(data, type, alloctype, layerdata,
1545                                                                                    totelem, name);
1546         customData_update_typemap(data);
1547
1548         if(layer)
1549                 return layer->data;
1550
1551         return NULL;
1552 }
1553
1554
1555 int CustomData_free_layer(CustomData *data, int type, int totelem, int index)
1556 {
1557         int i;
1558         
1559         if (index < 0) return 0;
1560
1561         customData_free_layer__internal(&data->layers[index], totelem);
1562
1563         for (i=index+1; i < data->totlayer; ++i)
1564                 data->layers[i-1] = data->layers[i];
1565
1566         data->totlayer--;
1567
1568         /* if layer was last of type in array, set new active layer */
1569         if ((index >= data->totlayer) || (data->layers[index].type != type)) {
1570                 i = CustomData_get_layer_index(data, type);
1571                 
1572                 if (i >= 0)
1573                         for (; i < data->totlayer && data->layers[i].type == type; i++) {
1574                                 data->layers[i].active--;
1575                                 data->layers[i].active_rnd--;
1576                                 data->layers[i].active_clone--;
1577                                 data->layers[i].active_mask--;
1578                         }
1579         }
1580
1581         if (data->totlayer <= data->maxlayer-CUSTOMDATA_GROW)
1582                 customData_resize(data, -CUSTOMDATA_GROW);
1583
1584         customData_update_offsets(data);
1585         customData_update_typemap(data);
1586
1587         return 1;
1588 }
1589
1590 int CustomData_free_layer_active(CustomData *data, int type, int totelem)
1591 {
1592         int index = 0;
1593         index = CustomData_get_active_layer_index(data, type);
1594         if (index < 0) return 0;
1595         return CustomData_free_layer(data, type, totelem, index);
1596 }
1597
1598
1599 void CustomData_free_layers(CustomData *data, int type, int totelem)
1600 {
1601         while (CustomData_has_layer(data, type))
1602                 CustomData_free_layer_active(data, type, totelem);
1603 }
1604
1605 int CustomData_has_layer(const CustomData *data, int type)
1606 {
1607         return (CustomData_get_layer_index(data, type) != -1);
1608 }
1609
1610 int CustomData_number_of_layers(const CustomData *data, int type)
1611 {
1612         int i, number = 0;
1613
1614         for(i = 0; i < data->totlayer; i++)
1615                 if(data->layers[i].type == type)
1616                         number++;
1617         
1618         return number;
1619 }
1620
1621 void *CustomData_duplicate_referenced_layer(struct CustomData *data, int type)
1622 {
1623         CustomDataLayer *layer;
1624         int layer_index;
1625
1626         /* get the layer index of the first layer of type */
1627         layer_index = CustomData_get_active_layer_index(data, type);
1628         if(layer_index < 0) return NULL;
1629
1630         layer = &data->layers[layer_index];
1631
1632         if (layer->flag & CD_FLAG_NOFREE) {
1633                 layer->data = MEM_dupallocN(layer->data);
1634                 layer->flag &= ~CD_FLAG_NOFREE;
1635         }
1636
1637         return layer->data;
1638 }
1639
1640 void *CustomData_duplicate_referenced_layer_named(struct CustomData *data,
1641                                                                                                   int type, const char *name)
1642 {
1643         CustomDataLayer *layer;
1644         int layer_index;
1645
1646         /* get the layer index of the desired layer */
1647         layer_index = CustomData_get_named_layer_index(data, type, name);
1648         if(layer_index < 0) return NULL;
1649
1650         layer = &data->layers[layer_index];
1651
1652         if (layer->flag & CD_FLAG_NOFREE) {
1653                 layer->data = MEM_dupallocN(layer->data);
1654                 layer->flag &= ~CD_FLAG_NOFREE;
1655         }
1656
1657         return layer->data;
1658 }
1659
1660 void CustomData_free_temporary(CustomData *data, int totelem)
1661 {
1662         CustomDataLayer *layer;
1663         int i, j;
1664
1665         for(i = 0, j = 0; i < data->totlayer; ++i) {
1666                 layer = &data->layers[i];
1667
1668                 if (i != j)
1669                         data->layers[j] = data->layers[i];
1670                 
1671                 if ((layer->flag & CD_FLAG_TEMPORARY) == CD_FLAG_TEMPORARY) {
1672                         customData_free_layer__internal(layer, totelem);
1673                 } else
1674                         j++;
1675         }
1676
1677         data->totlayer = j;
1678
1679         if(data->totlayer <= data->maxlayer-CUSTOMDATA_GROW)
1680                 customData_resize(data, -CUSTOMDATA_GROW);
1681
1682         customData_update_offsets(data);
1683 }
1684
1685 void CustomData_set_only_copy(const struct CustomData *data,
1686                                                           CustomDataMask mask)
1687 {
1688         int i;
1689
1690         for(i = 0; i < data->totlayer; ++i)
1691                 if(!((int)mask & (int)(1 << (int)data->layers[i].type)))
1692                         data->layers[i].flag |= CD_FLAG_NOCOPY;
1693 }
1694
1695 void CustomData_copy_elements(int type, void *source, void *dest, int count)
1696 {
1697         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1698
1699         if (typeInfo->copy)
1700                 typeInfo->copy(source, dest, count);
1701         else
1702                 memcpy(dest, source, typeInfo->size*count);
1703 }
1704
1705 void CustomData_copy_data(const CustomData *source, CustomData *dest,
1706                                                   int source_index, int dest_index, int count)
1707 {
1708         const LayerTypeInfo *typeInfo;
1709         int src_i, dest_i;
1710         int src_offset;
1711         int dest_offset;
1712
1713         /* copies a layer at a time */
1714         dest_i = 0;
1715         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1716
1717                 /* find the first dest layer with type >= the source type
1718                  * (this should work because layers are ordered by type)
1719                  */
1720                 while(dest_i < dest->totlayer
1721                           && dest->layers[dest_i].type < source->layers[src_i].type)
1722                         ++dest_i;
1723
1724                 /* if there are no more dest layers, we're done */
1725                 if(dest_i >= dest->totlayer) return;
1726
1727                 /* if we found a matching layer, copy the data */
1728                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1729                         char *src_data = source->layers[src_i].data;
1730                         char *dest_data = dest->layers[dest_i].data;
1731
1732                         typeInfo = layerType_getInfo(source->layers[src_i].type);
1733
1734                         src_offset = source_index * typeInfo->size;
1735                         dest_offset = dest_index * typeInfo->size;
1736                         
1737                         if (!src_data || !dest_data) {
1738                                 printf("eek! null data in CustomData_copy_data!\n");
1739                                 continue;
1740                         }
1741                         
1742                         if(typeInfo->copy)
1743                                 typeInfo->copy(src_data + src_offset,
1744                                                                 dest_data + dest_offset,
1745                                                                 count);
1746                         else
1747                                 memcpy(dest_data + dest_offset,
1748                                            src_data + src_offset,
1749                                            count * typeInfo->size);
1750
1751                         /* if there are multiple source & dest layers of the same type,
1752                          * we don't want to copy all source layers to the same dest, so
1753                          * increment dest_i
1754                          */
1755                         ++dest_i;
1756                 }
1757         }
1758 }
1759
1760 void CustomData_free_elem(CustomData *data, int index, int count)
1761 {
1762         int i;
1763         const LayerTypeInfo *typeInfo;
1764
1765         for(i = 0; i < data->totlayer; ++i) {
1766                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
1767                         typeInfo = layerType_getInfo(data->layers[i].type);
1768
1769                         if(typeInfo->free) {
1770                                 int offset = typeInfo->size * index;
1771
1772                                 typeInfo->free((char *)data->layers[i].data + offset,
1773                                                            count, typeInfo->size);
1774                         }
1775                 }
1776         }
1777 }
1778
1779 #define SOURCE_BUF_SIZE 100
1780
1781 void CustomData_interp(const CustomData *source, CustomData *dest,
1782                                            int *src_indices, float *weights, float *sub_weights,
1783                                            int count, int dest_index)
1784 {
1785         int src_i, dest_i;
1786         int dest_offset;
1787         int j;
1788         void *source_buf[SOURCE_BUF_SIZE];
1789         void **sources = source_buf;
1790
1791         /* slow fallback in case we're interpolating a ridiculous number of
1792          * elements
1793          */
1794         if(count > SOURCE_BUF_SIZE)
1795                 sources = MEM_callocN(sizeof(*sources) * count,
1796                                                           "CustomData_interp sources");
1797
1798         /* interpolates a layer at a time */
1799         dest_i = 0;
1800         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1801                 const LayerTypeInfo *typeInfo= layerType_getInfo(source->layers[src_i].type);
1802                 if(!typeInfo->interp) continue;
1803
1804                 /* find the first dest layer with type >= the source type
1805                  * (this should work because layers are ordered by type)
1806                  */
1807                 while(dest_i < dest->totlayer
1808                           && dest->layers[dest_i].type < source->layers[src_i].type)
1809                         ++dest_i;
1810
1811                 /* if there are no more dest layers, we're done */
1812                 if(dest_i >= dest->totlayer) return;
1813
1814                 /* if we found a matching layer, copy the data */
1815                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1816                         void *src_data = source->layers[src_i].data;
1817
1818                         for(j = 0; j < count; ++j)
1819                                 sources[j] = (char *)src_data
1820                                                          + typeInfo->size * src_indices[j];
1821
1822                         dest_offset = dest_index * typeInfo->size;
1823
1824                         typeInfo->interp(sources, weights, sub_weights, count,
1825                                                    (char *)dest->layers[dest_i].data + dest_offset);
1826
1827                         /* if there are multiple source & dest layers of the same type,
1828                          * we don't want to copy all source layers to the same dest, so
1829                          * increment dest_i
1830                          */
1831                         ++dest_i;
1832                 }
1833         }
1834
1835         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
1836 }
1837
1838 void CustomData_swap(struct CustomData *data, int index, const int *corner_indices)
1839 {
1840         const LayerTypeInfo *typeInfo;
1841         int i;
1842
1843         for(i = 0; i < data->totlayer; ++i) {
1844                 typeInfo = layerType_getInfo(data->layers[i].type);
1845
1846                 if(typeInfo->swap) {
1847                         int offset = typeInfo->size * index;
1848
1849                         typeInfo->swap((char *)data->layers[i].data + offset, corner_indices);
1850                 }
1851         }
1852 }
1853
1854 void *CustomData_get(const CustomData *data, int index, int type)
1855 {
1856         int offset;
1857         int layer_index;
1858         
1859         /* get the layer index of the active layer of type */
1860         layer_index = CustomData_get_active_layer_index(data, type);
1861         if(layer_index < 0) return NULL;
1862
1863         /* get the offset of the desired element */
1864         offset = layerType_getInfo(type)->size * index;
1865
1866         return (char *)data->layers[layer_index].data + offset;
1867 }
1868
1869 void *CustomData_get_n(const CustomData *data, int type, int index, int n)
1870 {
1871         int layer_index;
1872         int offset;
1873
1874         /* get the layer index of the first layer of type */
1875         layer_index = data->typemap[type];
1876         if(layer_index < 0) return NULL;
1877         
1878         offset = layerType_getInfo(type)->size * index;
1879         return (char *)data->layers[layer_index+n].data + offset;
1880 }
1881
1882 void *CustomData_get_layer(const CustomData *data, int type)
1883 {
1884         /* get the layer index of the active layer of type */
1885         int layer_index = CustomData_get_active_layer_index(data, type);
1886         if(layer_index < 0) return NULL;
1887
1888         return data->layers[layer_index].data;
1889 }
1890
1891 void *CustomData_get_layer_n(const CustomData *data, int type, int n)
1892 {
1893         /* get the layer index of the active layer of type */
1894         int layer_index = CustomData_get_layer_index(data, type);
1895         if(layer_index < 0) return NULL;
1896
1897         return data->layers[layer_index+n].data;
1898 }
1899
1900 void *CustomData_get_layer_named(const struct CustomData *data, int type,
1901                                                                  const char *name)
1902 {
1903         int layer_index = CustomData_get_named_layer_index(data, type, name);
1904         if(layer_index < 0) return NULL;
1905
1906         return data->layers[layer_index].data;
1907 }
1908
1909 void *CustomData_set_layer(const CustomData *data, int type, void *ptr)
1910 {
1911         /* get the layer index of the first layer of type */
1912         int layer_index = CustomData_get_active_layer_index(data, type);
1913
1914         if(layer_index < 0) return NULL;
1915
1916         data->layers[layer_index].data = ptr;
1917
1918         return ptr;
1919 }
1920
1921 void *CustomData_set_layer_n(const struct CustomData *data, int type, int n, void *ptr)
1922 {
1923         /* get the layer index of the first layer of type */
1924         int layer_index = CustomData_get_layer_index(data, type);
1925         if(layer_index < 0) return NULL;
1926
1927         data->layers[layer_index+n].data = ptr;
1928
1929         return ptr;
1930 }
1931
1932 void CustomData_set(const CustomData *data, int index, int type, void *source)
1933 {
1934         void *dest = CustomData_get(data, index, type);
1935         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1936
1937         if(!dest) return;
1938
1939         if(typeInfo->copy)
1940                 typeInfo->copy(source, dest, 1);
1941         else
1942                 memcpy(dest, source, typeInfo->size);
1943 }
1944
1945 /* EditMesh functions */
1946
1947 void CustomData_em_free_block(CustomData *data, void **block)
1948 {
1949         const LayerTypeInfo *typeInfo;
1950         int i;
1951
1952         if(!*block) return;
1953
1954         for(i = 0; i < data->totlayer; ++i) {
1955                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
1956                         typeInfo = layerType_getInfo(data->layers[i].type);
1957
1958                         if(typeInfo->free) {
1959                                 int offset = data->layers[i].offset;
1960                                 typeInfo->free((char*)*block + offset, 1, typeInfo->size);
1961                         }
1962                 }
1963         }
1964
1965         MEM_freeN(*block);
1966         *block = NULL;
1967 }
1968
1969 static void CustomData_em_alloc_block(CustomData *data, void **block)
1970 {
1971         /* TODO: optimize free/alloc */
1972
1973         if (*block)
1974                 CustomData_em_free_block(data, block);
1975
1976         if (data->totsize > 0)
1977                 *block = MEM_callocN(data->totsize, "CustomData EM block");
1978         else
1979                 *block = NULL;
1980 }
1981
1982 void CustomData_em_copy_data(const CustomData *source, CustomData *dest,
1983                                                         void *src_block, void **dest_block)
1984 {
1985         const LayerTypeInfo *typeInfo;
1986         int dest_i, src_i;
1987
1988         if (!*dest_block)
1989                 CustomData_em_alloc_block(dest, dest_block);
1990         
1991         /* copies a layer at a time */
1992         dest_i = 0;
1993         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1994
1995                 /* find the first dest layer with type >= the source type
1996                  * (this should work because layers are ordered by type)
1997                  */
1998                 while(dest_i < dest->totlayer
1999                           && dest->layers[dest_i].type < source->layers[src_i].type)
2000                         ++dest_i;
2001
2002                 /* if there are no more dest layers, we're done */
2003                 if(dest_i >= dest->totlayer) return;
2004
2005                 /* if we found a matching layer, copy the data */
2006                 if(dest->layers[dest_i].type == source->layers[src_i].type &&
2007                         strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
2008                         char *src_data = (char*)src_block + source->layers[src_i].offset;
2009                         char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
2010
2011                         typeInfo = layerType_getInfo(source->layers[src_i].type);
2012
2013                         if(typeInfo->copy)
2014                                 typeInfo->copy(src_data, dest_data, 1);
2015                         else
2016                                 memcpy(dest_data, src_data, typeInfo->size);
2017
2018                         /* if there are multiple source & dest layers of the same type,
2019                          * we don't want to copy all source layers to the same dest, so
2020                          * increment dest_i
2021                          */
2022                         ++dest_i;
2023                 }
2024         }
2025 }
2026
2027 void CustomData_em_validate_data(CustomData *data, void *block, int sub_elements)
2028 {
2029         int i;
2030         for(i = 0; i < data->totlayer; i++) {
2031                 const LayerTypeInfo *typeInfo = layerType_getInfo(data->layers[i].type);
2032                 char *leayer_data = (char*)block + data->layers[i].offset;
2033
2034                 if(typeInfo->validate)
2035                         typeInfo->validate(leayer_data, sub_elements);
2036         }
2037 }
2038
2039 void *CustomData_em_get(const CustomData *data, void *block, int type)
2040 {
2041         int layer_index;
2042         
2043         /* get the layer index of the first layer of type */
2044         layer_index = CustomData_get_active_layer_index(data, type);
2045         if(layer_index < 0) return NULL;
2046
2047         return (char *)block + data->layers[layer_index].offset;
2048 }
2049
2050 void *CustomData_em_get_n(const CustomData *data, void *block, int type, int n)
2051 {
2052         int layer_index;
2053         
2054         /* get the layer index of the first layer of type */
2055         layer_index = CustomData_get_layer_index(data, type);
2056         if(layer_index < 0) return NULL;
2057
2058         return (char *)block + data->layers[layer_index+n].offset;
2059 }
2060
2061 void CustomData_em_set(CustomData *data, void *block, int type, void *source)
2062 {
2063         void *dest = CustomData_em_get(data, block, type);
2064         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2065
2066         if(!dest) return;
2067
2068         if(typeInfo->copy)
2069                 typeInfo->copy(source, dest, 1);
2070         else
2071                 memcpy(dest, source, typeInfo->size);
2072 }
2073
2074 void CustomData_em_set_n(CustomData *data, void *block, int type, int n, void *source)
2075 {
2076         void *dest = CustomData_em_get_n(data, block, type, n);
2077         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2078
2079         if(!dest) return;
2080
2081         if(typeInfo->copy)
2082                 typeInfo->copy(source, dest, 1);
2083         else
2084                 memcpy(dest, source, typeInfo->size);
2085 }
2086
2087 void CustomData_em_interp(CustomData *data, void **src_blocks, float *weights,
2088                                                   float *sub_weights, int count, void *dest_block)
2089 {
2090         int i, j;
2091         void *source_buf[SOURCE_BUF_SIZE];
2092         void **sources = source_buf;
2093
2094         /* slow fallback in case we're interpolating a ridiculous number of
2095          * elements
2096          */
2097         if(count > SOURCE_BUF_SIZE)
2098                 sources = MEM_callocN(sizeof(*sources) * count,
2099                                                           "CustomData_interp sources");
2100
2101         /* interpolates a layer at a time */
2102         for(i = 0; i < data->totlayer; ++i) {
2103                 CustomDataLayer *layer = &data->layers[i];
2104                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
2105
2106                 if(typeInfo->interp) {
2107                         for(j = 0; j < count; ++j)
2108                                 sources[j] = (char *)src_blocks[j] + layer->offset;
2109
2110                         typeInfo->interp(sources, weights, sub_weights, count,
2111                                                           (char *)dest_block + layer->offset);
2112                 }
2113         }
2114
2115         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
2116 }
2117
2118 void CustomData_em_set_default(CustomData *data, void **block)
2119 {
2120         const LayerTypeInfo *typeInfo;
2121         int i;
2122
2123         if (!*block)
2124                 CustomData_em_alloc_block(data, block);
2125
2126         for(i = 0; i < data->totlayer; ++i) {
2127                 int offset = data->layers[i].offset;
2128
2129                 typeInfo = layerType_getInfo(data->layers[i].type);
2130
2131                 if(typeInfo->set_default)
2132                         typeInfo->set_default((char*)*block + offset, 1);
2133         }
2134 }
2135
2136 void CustomData_to_em_block(const CustomData *source, CustomData *dest,
2137                                                         int src_index, void **dest_block)
2138 {
2139         const LayerTypeInfo *typeInfo;
2140         int dest_i, src_i, src_offset;
2141
2142         if (!*dest_block)
2143                 CustomData_em_alloc_block(dest, dest_block);
2144         
2145         /* copies a layer at a time */
2146         dest_i = 0;
2147         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2148
2149                 /* find the first dest layer with type >= the source type
2150                  * (this should work because layers are ordered by type)
2151                  */
2152                 while(dest_i < dest->totlayer
2153                           && dest->layers[dest_i].type < source->layers[src_i].type)
2154                         ++dest_i;
2155
2156                 /* if there are no more dest layers, we're done */
2157                 if(dest_i >= dest->totlayer) return;
2158
2159                 /* if we found a matching layer, copy the data */
2160                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2161                         int offset = dest->layers[dest_i].offset;
2162                         char *src_data = source->layers[src_i].data;
2163                         char *dest_data = (char*)*dest_block + offset;
2164
2165                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2166                         src_offset = src_index * typeInfo->size;
2167
2168                         if(typeInfo->copy)
2169                                 typeInfo->copy(src_data + src_offset, dest_data, 1);
2170                         else
2171                                 memcpy(dest_data, src_data + src_offset, typeInfo->size);
2172
2173                         /* if there are multiple source & dest layers of the same type,
2174                          * we don't want to copy all source layers to the same dest, so
2175                          * increment dest_i
2176                          */
2177                         ++dest_i;
2178                 }
2179         }
2180 }
2181
2182 void CustomData_from_em_block(const CustomData *source, CustomData *dest,
2183                                                           void *src_block, int dest_index)
2184 {
2185         const LayerTypeInfo *typeInfo;
2186         int dest_i, src_i, dest_offset;
2187
2188         /* copies a layer at a time */
2189         dest_i = 0;
2190         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2191
2192                 /* find the first dest layer with type >= the source type
2193                  * (this should work because layers are ordered by type)
2194                  */
2195                 while(dest_i < dest->totlayer
2196                           && dest->layers[dest_i].type < source->layers[src_i].type)
2197                         ++dest_i;
2198
2199                 /* if there are no more dest layers, we're done */
2200                 if(dest_i >= dest->totlayer) return;
2201
2202                 /* if we found a matching layer, copy the data */
2203                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2204                         int offset = source->layers[src_i].offset;
2205                         char *src_data = (char*)src_block + offset;
2206                         char *dest_data = dest->layers[dest_i].data;
2207
2208                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2209                         dest_offset = dest_index * typeInfo->size;
2210
2211                         if(typeInfo->copy)
2212                                 typeInfo->copy(src_data, dest_data + dest_offset, 1);
2213                         else
2214                                 memcpy(dest_data + dest_offset, src_data, typeInfo->size);
2215
2216                         /* if there are multiple source & dest layers of the same type,
2217                          * we don't want to copy all source layers to the same dest, so
2218                          * increment dest_i
2219                          */
2220                         ++dest_i;
2221                 }
2222         }
2223
2224 }
2225
2226 /*Bmesh functions*/
2227 /*needed to convert to/from different face reps*/
2228 void CustomData_to_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata,
2229                              int totloop, int totpoly)
2230 {
2231         int i;
2232         for(i=0; i < fdata->totlayer; i++){
2233                 if(fdata->layers[i].type == CD_MTFACE){
2234                         CustomData_add_layer(pdata, CD_MTEXPOLY, CD_CALLOC, &(fdata->layers[i].name), totpoly);
2235                         CustomData_add_layer(ldata, CD_MLOOPUV, CD_CALLOC, &(fdata->layers[i].name), totloop);
2236                 }
2237                 else if(fdata->layers[i].type == CD_MCOL)
2238                         CustomData_add_layer(ldata, CD_MLOOPCOL, CD_CALLOC, &(fdata->layers[i].name), totloop);
2239                 else if(fdata->layers[i].type == CD_MDISPS) 
2240                         CustomData_add_layer(ldata, CD_MDISPS, CD_CALLOC, &(fdata->layers[i].name), totloop);
2241         }
2242 }
2243 void CustomData_from_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata, int total){
2244         int i;
2245         for(i=0; i < pdata->totlayer; i++){
2246                 if(pdata->layers[i].type == CD_MTEXPOLY)
2247                         CustomData_add_layer(fdata, CD_MTFACE, CD_CALLOC, &(pdata->layers[i].name), total);
2248         }
2249         for(i=0; i < ldata->totlayer; i++){
2250                 if(ldata->layers[i].type == CD_MLOOPCOL)
2251                         CustomData_add_layer(fdata, CD_MCOL, CD_CALLOC, &(ldata->layers[i].name), total);
2252                 if (ldata->layers[i].type == CD_WEIGHT_MLOOPCOL)
2253                         CustomData_add_layer(fdata, CD_WEIGHT_MCOL, CD_CALLOC, &(ldata->layers[i].name), total);
2254         }
2255 }
2256
2257
2258 void CustomData_bmesh_init_pool(CustomData *data, int allocsize){
2259         if(data->totlayer)data->pool = BLI_mempool_create(data->totsize, allocsize, allocsize, 1, 0);
2260 }
2261
2262 void CustomData_bmesh_merge(CustomData *source, CustomData *dest, 
2263                             int mask, int alloctype, BMesh *bm, int type)
2264 {
2265         BMHeader *h;
2266         BMIter iter;
2267         CustomData destold = *dest;
2268         void *tmp;
2269         int t;
2270         
2271         CustomData_merge(source, dest, mask, alloctype, 0);
2272         CustomData_bmesh_init_pool(dest, 512);
2273
2274         switch (type) {
2275                 case BM_VERT:
2276                         t = BM_VERTS_OF_MESH; break;
2277                 case BM_EDGE:
2278                         t = BM_EDGES_OF_MESH; break;
2279                 case BM_LOOP:
2280                         t = BM_LOOPS_OF_FACE; break;
2281                 case BM_FACE:
2282                         t = BM_FACES_OF_MESH; break;
2283         }
2284
2285         if (t != BM_LOOPS_OF_FACE) {
2286                 /*ensure all current elements follow new customdata layout*/
2287                 BM_ITER(h, &iter, bm, t, NULL) {
2288                         CustomData_bmesh_copy_data(&destold, dest, h->data, &tmp);
2289                         CustomData_bmesh_free_block(&destold, &h->data);
2290                         h->data = tmp;
2291                 }
2292         } else {
2293                 BMFace *f;
2294                 BMLoop *l;
2295                 BMIter liter;
2296
2297                 /*ensure all current elements follow new customdata layout*/
2298                 BM_ITER(f, &iter, bm, BM_FACES_OF_MESH, NULL) {
2299                         BM_ITER(l, &liter, bm, BM_LOOPS_OF_FACE, f) {
2300                                 CustomData_bmesh_copy_data(&destold, dest, l->head.data, &tmp);
2301                                 CustomData_bmesh_free_block(&destold, &l->head.data);
2302                                 l->head.data = tmp;
2303                         }
2304                 }
2305         }
2306
2307         if (destold.pool) BLI_mempool_destroy(destold.pool);
2308 }
2309
2310 void CustomData_bmesh_free_block(CustomData *data, void **block)
2311 {
2312         const LayerTypeInfo *typeInfo;
2313         int i;
2314
2315         if(!*block) return;
2316         for(i = 0; i < data->totlayer; ++i) {
2317                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
2318                         typeInfo = layerType_getInfo(data->layers[i].type);
2319
2320                         if(typeInfo->free) {
2321                                 int offset = data->layers[i].offset;
2322                                 typeInfo->free((char*)*block + offset, 1, typeInfo->size);
2323                         }
2324                 }
2325         }
2326
2327         if (data->totsize)
2328                 BLI_mempool_free(data->pool, *block);
2329
2330         *block = NULL;
2331 }
2332
2333 static void CustomData_bmesh_alloc_block(CustomData *data, void **block)
2334 {
2335
2336         if (*block)
2337                 CustomData_bmesh_free_block(data, block);
2338
2339         if (data->totsize > 0)
2340                 *block = BLI_mempool_alloc(data->pool);
2341         else
2342                 *block = NULL;
2343 }
2344
2345 void CustomData_bmesh_copy_data(const CustomData *source, CustomData *dest,
2346                                                         void *src_block, void **dest_block)
2347 {
2348         const LayerTypeInfo *typeInfo;
2349         int dest_i, src_i;
2350
2351         if (!*dest_block)
2352                 CustomData_bmesh_alloc_block(dest, dest_block);
2353         
2354         /* copies a layer at a time */
2355         dest_i = 0;
2356         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2357
2358                 /* find the first dest layer with type >= the source type
2359                  * (this should work because layers are ordered by type)
2360                  */
2361                 while(dest_i < dest->totlayer
2362                           && dest->layers[dest_i].type < source->layers[src_i].type)
2363                         ++dest_i;
2364
2365                 /* if there are no more dest layers, we're done */
2366                 if(dest_i >= dest->totlayer) return;
2367
2368                 /* if we found a matching layer, copy the data */
2369                 if(dest->layers[dest_i].type == source->layers[src_i].type &&
2370                         strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
2371                         char *src_data = (char*)src_block + source->layers[src_i].offset;
2372                         char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
2373
2374                         typeInfo = layerType_getInfo(source->layers[src_i].type);
2375
2376                         if(typeInfo->copy)
2377                                 typeInfo->copy(src_data, dest_data, 1);
2378                         else
2379                                 memcpy(dest_data, src_data, typeInfo->size);
2380
2381                         /* if there are multiple source & dest layers of the same type,
2382                          * we don't want to copy all source layers to the same dest, so
2383                          * increment dest_i
2384                          */
2385                         ++dest_i;
2386                 }
2387         }
2388 }
2389
2390 /*Bmesh Custom Data Functions. Should replace editmesh ones with these as well, due to more effecient memory alloc*/
2391 void *CustomData_bmesh_get(const CustomData *data, void *block, int type)
2392 {
2393         int layer_index;
2394         
2395         /* get the layer index of the first layer of type */
2396         layer_index = CustomData_get_active_layer_index(data, type);
2397         if(layer_index < 0) return NULL;
2398
2399         return (char *)block + data->layers[layer_index].offset;
2400 }
2401
2402 void *CustomData_bmesh_get_n(const CustomData *data, void *block, int type, int n)
2403 {
2404         int layer_index;
2405         
2406         /* get the layer index of the first layer of type */
2407         layer_index = CustomData_get_layer_index(data, type);
2408         if(layer_index < 0) return NULL;
2409
2410         return (char *)block + data->layers[layer_index+n].offset;
2411 }
2412
2413 /*gets from the layer at physical index n, note: doesn't check type.*/
2414 void *CustomData_bmesh_get_layer_n(const CustomData *data, void *block, int n)
2415 {
2416         if(n < 0 || n >= data->totlayer) return NULL;
2417
2418         return (char *)block + data->layers[n].offset;
2419 }
2420
2421 int CustomData_layer_has_math(struct CustomData *data, int layern)
2422 {
2423         const LayerTypeInfo *typeInfo = layerType_getInfo(data->layers[layern].type);
2424         
2425         if (typeInfo->equal && typeInfo->add && typeInfo->multiply && 
2426             typeInfo->initminmax && typeInfo->dominmax) return 1;
2427         
2428         return 0;
2429 }
2430
2431 /*copies the "value" (e.g. mloopuv uv or mloopcol colors) from one block to
2432   another, while not overwriting anything else (e.g. flags)*/
2433 void CustomData_data_copy_value(int type, void *source, void *dest)
2434 {
2435         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2436
2437         if(!dest) return;
2438
2439         if(typeInfo->copyvalue)
2440                 typeInfo->copyvalue(source, dest);
2441         else
2442                 memcpy(dest, source, typeInfo->size);
2443 }
2444
2445 int CustomData_data_equals(int type, void *data1, void *data2)
2446 {
2447         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2448
2449         if (typeInfo->equal)
2450                 return typeInfo->equal(data1, data2);
2451         else return !memcmp(data1, data2, typeInfo->size);
2452 }
2453
2454 void CustomData_data_initminmax(int type, void *min, void *max)
2455 {
2456         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2457
2458         if (typeInfo->initminmax)
2459                 typeInfo->initminmax(min, max);
2460 }
2461
2462
2463 void CustomData_data_dominmax(int type, void *data, void *min, void *max)
2464 {
2465         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2466
2467         if (typeInfo->dominmax)
2468                 typeInfo->dominmax(data, min, max);
2469 }
2470
2471
2472 void CustomData_data_multiply(int type, void *data, float fac)
2473 {
2474         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2475
2476         if (typeInfo->multiply)
2477                 typeInfo->multiply(data, fac);
2478 }
2479
2480
2481 void CustomData_data_add(int type, void *data1, void *data2)
2482 {
2483         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2484
2485         if (typeInfo->add)
2486                 typeInfo->add(data1, data2);
2487 }
2488
2489 void CustomData_bmesh_set(const CustomData *data, void *block, int type, void *source)
2490 {
2491         void *dest = CustomData_bmesh_get(data, block, type);
2492         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2493
2494         if(!dest) return;
2495
2496         if(typeInfo->copy)
2497                 typeInfo->copy(source, dest, 1);
2498         else
2499                 memcpy(dest, source, typeInfo->size);
2500 }
2501
2502 void CustomData_bmesh_set_n(CustomData *data, void *block, int type, int n, void *source)
2503 {
2504         void *dest = CustomData_bmesh_get_n(data, block, type, n);
2505         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2506
2507         if(!dest) return;
2508
2509         if(typeInfo->copy)
2510                 typeInfo->copy(source, dest, 1);
2511         else
2512                 memcpy(dest, source, typeInfo->size);
2513 }
2514
2515 void CustomData_bmesh_set_layer_n(CustomData *data, void *block, int n, void *source)
2516 {
2517         void *dest = CustomData_bmesh_get_layer_n(data, block, n);
2518         const LayerTypeInfo *typeInfo = layerType_getInfo(data->layers[n].type);
2519
2520         if(!dest) return;
2521
2522         if(typeInfo->copy)
2523                 typeInfo->copy(source, dest, 1);
2524         else
2525                 memcpy(dest, source, typeInfo->size);
2526 }
2527
2528 void CustomData_bmesh_interp(CustomData *data, void **src_blocks, float *weights,
2529                                                   float *sub_weights, int count, void *dest_block)
2530 {
2531         int i, j;
2532         void *source_buf[SOURCE_BUF_SIZE];
2533         void **sources = source_buf;
2534
2535         /* slow fallback in case we're interpolating a ridiculous number of
2536          * elements
2537          */
2538         if(count > SOURCE_BUF_SIZE)
2539                 sources = MEM_callocN(sizeof(*sources) * count,
2540                                                           "CustomData_interp sources");
2541
2542         /* interpolates a layer at a time */
2543         for(i = 0; i < data->totlayer; ++i) {
2544                 CustomDataLayer *layer = &data->layers[i];
2545                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
2546                 if(typeInfo->interp) {
2547                         for(j = 0; j < count; ++j)
2548                                 sources[j] = (char *)src_blocks[j] + layer->offset;
2549
2550                         typeInfo->interp(sources, weights, sub_weights, count,
2551                                                           (char *)dest_block + layer->offset);
2552                 }
2553         }
2554
2555         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
2556 }
2557
2558 void CustomData_bmesh_set_default(CustomData *data, void **block)
2559 {
2560         const LayerTypeInfo *typeInfo;
2561         int i;
2562
2563         if (!*block)
2564                 CustomData_bmesh_alloc_block(data, block);
2565
2566         for(i = 0; i < data->totlayer; ++i) {
2567                 int offset = data->layers[i].offset;
2568
2569                 typeInfo = layerType_getInfo(data->layers[i].type);
2570
2571                 if(typeInfo->set_default)
2572                         typeInfo->set_default((char*)*block + offset, 1);
2573                 else memset((char*)*block + offset, 0, typeInfo->size);
2574         }
2575 }
2576
2577 void CustomData_to_bmesh_block(const CustomData *source, CustomData *dest,
2578                                                         int src_index, void **dest_block)
2579 {
2580         const LayerTypeInfo *typeInfo;
2581         int dest_i, src_i, src_offset;
2582
2583         if (!*dest_block)
2584                 CustomData_bmesh_alloc_block(dest, dest_block);
2585         
2586         /* copies a layer at a time */
2587         dest_i = 0;
2588         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2589
2590                 /* find the first dest layer with type >= the source type
2591                  * (this should work because layers are ordered by type)
2592                  */
2593                 while(dest_i < dest->totlayer
2594                           && dest->layers[dest_i].type < source->layers[src_i].type)
2595                         ++dest_i;
2596
2597                 /* if there are no more dest layers, we're done */
2598                 if(dest_i >= dest->totlayer) return;
2599
2600                 /* if we found a matching layer, copy the data */
2601                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2602                         int offset = dest->layers[dest_i].offset;
2603                         char *src_data = source->layers[src_i].data;
2604                         char *dest_data = (char*)*dest_block + offset;
2605
2606                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2607                         src_offset = src_index * typeInfo->size;
2608
2609                         if(typeInfo->copy)
2610                                 typeInfo->copy(src_data + src_offset, dest_data, 1);
2611                         else
2612                                 memcpy(dest_data, src_data + src_offset, typeInfo->size);
2613
2614                         /* if there are multiple source & dest layers of the same type,
2615                          * we don't want to copy all source layers to the same dest, so
2616                          * increment dest_i
2617                          */
2618                         ++dest_i;
2619                 }
2620         }
2621 }
2622
2623 void CustomData_from_bmesh_block(const CustomData *source, CustomData *dest,
2624                                                           void *src_block, int dest_index)
2625 {
2626         const LayerTypeInfo *typeInfo;
2627         int dest_i, src_i, dest_offset;
2628
2629         /* copies a layer at a time */
2630         dest_i = 0;
2631         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2632
2633                 /* find the first dest layer with type >= the source type
2634                  * (this should work because layers are ordered by type)
2635                  */
2636                 while(dest_i < dest->totlayer
2637                           && dest->layers[dest_i].type < source->layers[src_i].type)
2638                         ++dest_i;
2639
2640                 /* if there are no more dest layers, we're done */
2641                 if(dest_i >= dest->totlayer) return;
2642
2643                 /* if we found a matching layer, copy the data */
2644                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2645                         int offset = source->layers[src_i].offset;
2646                         char *src_data = (char*)src_block + offset;
2647                         char *dest_data = dest->layers[dest_i].data;
2648
2649                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2650                         dest_offset = dest_index * typeInfo->size;
2651
2652                         if(typeInfo->copy)
2653                                 typeInfo->copy(src_data, dest_data + dest_offset, 1);
2654                         else
2655                                 memcpy(dest_data + dest_offset, src_data, typeInfo->size);
2656
2657                         /* if there are multiple source & dest layers of the same type,
2658                          * we don't want to copy all source layers to the same dest, so
2659                          * increment dest_i
2660                          */
2661                         ++dest_i;
2662                 }
2663         }
2664
2665 }
2666
2667 void CustomData_file_write_info(int type, const char **structname, int *structnum)
2668 {
2669         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2670
2671         *structname = typeInfo->structname;
2672         *structnum = typeInfo->structnum;
2673 }
2674
2675 int CustomData_sizeof(int type)
2676 {
2677         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2678
2679         return typeInfo->size;
2680 }
2681
2682 const char *CustomData_layertype_name(int type)
2683 {
2684         return layerType_getName(type);
2685 }
2686
2687 static int  CustomData_is_property_layer(int type)
2688 {
2689         if((type == CD_PROP_FLT) || (type == CD_PROP_INT) || (type == CD_PROP_STR))
2690                 return 1;
2691         return 0;
2692 }
2693
2694 static int cd_layer_find_dupe(CustomData *data, const char *name, int type, int index)
2695 {
2696         int i;
2697         /* see if there is a duplicate */
2698         for(i=0; i<data->totlayer; i++) {
2699                 if(i != index) {
2700                         CustomDataLayer *layer= &data->layers[i];
2701                         
2702                         if(CustomData_is_property_layer(type)) {
2703                                 if(CustomData_is_property_layer(layer->type) && strcmp(layer->name, name)==0) {
2704                                         return 1;
2705                                 }
2706                         }
2707                         else{
2708                                 if(i!=index && layer->type==type && strcmp(layer->name, name)==0) {
2709                                         return 1;
2710                                 }
2711                         }
2712                 }
2713         }
2714         
2715         return 0;
2716 }
2717
2718 static int customdata_unique_check(void *arg, const char *name)
2719 {
2720         struct {CustomData *data; int type; int index;} *data_arg= arg;
2721         return cd_layer_find_dupe(data_arg->data, name, data_arg->type, data_arg->index);
2722 }
2723
2724 void CustomData_set_layer_unique_name(CustomData *data, int index)
2725 {       
2726         CustomDataLayer *nlayer= &data->layers[index];
2727         const LayerTypeInfo *typeInfo= layerType_getInfo(nlayer->type);
2728
2729         struct {CustomData *data; int type; int index;} data_arg;
2730         data_arg.data= data;
2731         data_arg.type= nlayer->type;
2732         data_arg.index= index;
2733
2734         if (!typeInfo->defaultname)
2735                 return;
2736         
2737         BLI_uniquename_cb(customdata_unique_check, &data_arg, typeInfo->defaultname, '.', nlayer->name, sizeof(nlayer->name));
2738 }
2739
2740 int CustomData_verify_versions(struct CustomData *data, int index)
2741 {
2742         const LayerTypeInfo *typeInfo;
2743         CustomDataLayer *layer = &data->layers[index];
2744         int i, keeplayer = 1;
2745
2746         if (layer->type >= CD_NUMTYPES) {
2747                 keeplayer = 0; /* unknown layer type from future version */
2748         }
2749         else {
2750                 typeInfo = layerType_getInfo(layer->type);
2751
2752                 if (!typeInfo->defaultname && (index > 0) &&
2753                         data->layers[index-1].type == layer->type)
2754                         keeplayer = 0; /* multiple layers of which we only support one */
2755         }
2756
2757         if (!keeplayer) {
2758                 for (i=index+1; i < data->totlayer; ++i)
2759                         data->layers[i-1] = data->layers[i];
2760                 data->totlayer--;
2761         }
2762
2763         return keeplayer;
2764 }
2765
2766 /****************************** External Files *******************************/
2767
2768 static void customdata_external_filename(char filename[FILE_MAX], ID *id, CustomDataExternal *external)
2769 {
2770         char *path = (id->lib)? id->lib->filepath: G.main->name;
2771
2772         BLI_strncpy(filename, external->filename, FILE_MAX);
2773         BLI_path_abs(filename, path);
2774 }
2775
2776 void CustomData_external_reload(CustomData *data, ID *UNUSED(id), CustomDataMask mask, int totelem)
2777 {
2778         CustomDataLayer *layer;
2779         const LayerTypeInfo *typeInfo;
2780         int i;
2781
2782         for(i=0; i<data->totlayer; i++) {
2783                 layer = &data->layers[i];
2784                 typeInfo = layerType_getInfo(layer->type);
2785
2786                 if(!(mask & (1<<layer->type)));
2787                 else if((layer->flag & CD_FLAG_EXTERNAL) && (layer->flag & CD_FLAG_IN_MEMORY)) {
2788                         if(typeInfo->free)
2789                                 typeInfo->free(layer->data, totelem, typeInfo->size);
2790                         layer->flag &= ~CD_FLAG_IN_MEMORY;
2791                 }
2792         }
2793 }
2794
2795 void CustomData_external_read(CustomData *data, ID *id, CustomDataMask mask, int totelem)
2796 {
2797         CustomDataExternal *external= data->external;
2798         CustomDataLayer *layer;
2799         CDataFile *cdf;
2800         CDataFileLayer *blay;
2801         char filename[FILE_MAX];
2802         const LayerTypeInfo *typeInfo;
2803         int i, update = 0;
2804
2805         if(!external)
2806                 return;
2807         
2808         for(i=0; i<data->totlayer; i++) {
2809                 layer = &data->layers[i];
2810                 typeInfo = layerType_getInfo(layer->type);
2811
2812                 if(!(mask & (1<<layer->type)));
2813                 else if(layer->flag & CD_FLAG_IN_MEMORY);
2814                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read)
2815                         update= 1;
2816         }
2817
2818         if(!update)
2819                 return;
2820
2821         customdata_external_filename(filename, id, external);
2822
2823         cdf= cdf_create(CDF_TYPE_MESH);
2824         if(!cdf_read_open(cdf, filename)) {
2825                 fprintf(stderr, "Failed to read %s layer from %s.\n", layerType_getName(layer->type), filename);
2826                 return;
2827         }
2828
2829         for(i=0; i<data->totlayer; i++) {
2830                 layer = &data->layers[i];
2831                 typeInfo = layerType_getInfo(layer->type);
2832
2833                 if(!(mask & (1<<layer->type)));
2834                 else if(layer->flag & CD_FLAG_IN_MEMORY);
2835                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read) {
2836                         blay= cdf_layer_find(cdf, layer->type, layer->name);
2837
2838                         if(blay) {
2839                                 if(cdf_read_layer(cdf, blay)) {
2840                                         if(typeInfo->read(cdf, layer->data, totelem));
2841                                         else break;
2842                                         layer->flag |= CD_FLAG_IN_MEMORY;
2843                                 }
2844                                 else
2845                                         break;
2846                         }
2847                 }
2848         }
2849
2850         cdf_read_close(cdf);
2851         cdf_free(cdf);
2852 }
2853
2854 void CustomData_external_write(CustomData *data, ID *id, CustomDataMask mask, int totelem, int free)
2855 {
2856         CustomDataExternal *external= data->external;
2857         CustomDataLayer *layer;
2858         CDataFile *cdf;
2859         CDataFileLayer *blay;
2860         const LayerTypeInfo *typeInfo;
2861         int i, update = 0;
2862         char filename[FILE_MAX];
2863
2864         if(!external)
2865                 return;
2866
2867         /* test if there is anything to write */
2868         for(i=0; i<data->totlayer; i++) {
2869                 layer = &data->layers[i];
2870                 typeInfo = layerType_getInfo(layer->type);
2871
2872                 if(!(mask & (1<<layer->type)));
2873                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write)
2874                         update= 1;
2875         }
2876
2877         if(!update)
2878                 return;
2879
2880         /* make sure data is read before we try to write */
2881         CustomData_external_read(data, id, mask, totelem);
2882         customdata_external_filename(filename, id, external);
2883
2884         cdf= cdf_create(CDF_TYPE_MESH);
2885
2886         for(i=0; i<data->totlayer; i++) {
2887                 layer = &data->layers[i];
2888                 typeInfo = layerType_getInfo(layer->type);
2889
2890                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->filesize) {
2891                         if(layer->flag & CD_FLAG_IN_MEMORY) {
2892                                 cdf_layer_add(cdf, layer->type, layer->name,
2893                                         typeInfo->filesize(cdf, layer->data, totelem));
2894                         }
2895                         else {
2896                                 cdf_free(cdf);
2897                                 return; /* read failed for a layer! */
2898                         }
2899                 }
2900         }
2901
2902         if(!cdf_write_open(cdf, filename)) {
2903                 fprintf(stderr, "Failed to open %s for writing.\n", filename);
2904                 return;
2905         }
2906
2907         for(i=0; i<data->totlayer; i++) {
2908                 layer = &data->layers[i];
2909                 typeInfo = layerType_getInfo(layer->type);
2910
2911                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) {
2912                         blay= cdf_layer_find(cdf, layer->type, layer->name);
2913
2914                         if(cdf_write_layer(cdf, blay)) {
2915                                 if(typeInfo->write(cdf, layer->data, totelem));
2916                                 else break;
2917                         }
2918                         else
2919                                 break;
2920                 }
2921         }
2922
2923         if(i != data->totlayer) {
2924                 fprintf(stderr, "Failed to write data to %s.\n", filename);
2925                 cdf_free(cdf);
2926                 return;
2927         }
2928
2929         for(i=0; i<data->totlayer; i++) {
2930                 layer = &data->layers[i];
2931                 typeInfo = layerType_getInfo(layer->type);
2932
2933                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) {
2934                         if(free) {
2935                                 if(typeInfo->free)
2936                                         typeInfo->free(layer->data, totelem, typeInfo->size);
2937                                 layer->flag &= ~CD_FLAG_IN_MEMORY;
2938                         }
2939                 }
2940         }
2941
2942         cdf_write_close(cdf);
2943         cdf_free(cdf);
2944 }
2945
2946 void CustomData_external_add(CustomData *data, ID *UNUSED(id), int type, int UNUSED(totelem), const char *filename)
2947 {
2948         CustomDataExternal *external= data->external;
2949         CustomDataLayer *layer;
2950         int layer_index;
2951
2952         layer_index = CustomData_get_active_layer_index(data, type);
2953         if(layer_index < 0) return;
2954
2955         layer = &data->layers[layer_index];
2956
2957         if(layer->flag & CD_FLAG_EXTERNAL)
2958                 return;
2959
2960         if(!external) {
2961                 external= MEM_callocN(sizeof(CustomDataExternal), "CustomDataExternal");
2962                 data->external= external;
2963         }
2964         BLI_strncpy(external->filename, filename, sizeof(external->filename));
2965
2966         layer->flag |= CD_FLAG_EXTERNAL|CD_FLAG_IN_MEMORY;
2967 }
2968
2969 void CustomData_external_remove(CustomData *data, ID *id, int type, int totelem)
2970 {
2971         CustomDataExternal *external= data->external;
2972         CustomDataLayer *layer;
2973         //char filename[FILE_MAX];
2974         int layer_index; // i, remove_file;
2975
2976         layer_index = CustomData_get_active_layer_index(data, type);
2977         if(layer_index < 0) return;
2978
2979         layer = &data->layers[layer_index];
2980
2981         if(!external)
2982                 return;
2983
2984         if(layer->flag & CD_FLAG_EXTERNAL) {
2985                 if(!(layer->flag & CD_FLAG_IN_MEMORY))
2986                         CustomData_external_read(data, id, (1<<layer->type), totelem);
2987
2988                 layer->flag &= ~CD_FLAG_EXTERNAL;
2989
2990 #if 0
2991                 remove_file= 1;
2992                 for(i=0; i<data->totlayer; i++)
2993                         if(data->layers[i].flag & CD_FLAG_EXTERNAL)
2994                                 remove_file= 0;
2995
2996                 if(remove_file) {
2997                         customdata_external_filename(filename, id, external);
2998                         cdf_remove(filename);
2999                         CustomData_external_free(data);
3000                 }
3001 #endif
3002         }
3003 }
3004
3005 int CustomData_external_test(CustomData *data, int type)
3006 {
3007         CustomDataLayer *layer;
3008         int layer_index;
3009
3010         layer_index = CustomData_get_active_layer_index(data, type);
3011         if(layer_index < 0) return 0;
3012
3013         layer = &data->layers[layer_index];
3014         return (layer->flag & CD_FLAG_EXTERNAL);
3015 }
3016
3017 #if 0
3018 void CustomData_external_remove_object(CustomData *data, ID *id)
3019 {
3020         CustomDataExternal *external= data->external;
3021         char filename[FILE_MAX];
3022
3023         if(!external)
3024                 return;
3025
3026         customdata_external_filename(filename, id, external);
3027         cdf_remove(filename);
3028         CustomData_external_free(data);
3029 }
3030 #endif
3031