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