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