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