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