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