minor warning fixes for clang-static-checker
[blender-staging.git] / source / blender / blenkernel / intern / customdata.c
1 /*
2 * $Id$
3 *
4 * ***** BEGIN GPL LICENSE BLOCK *****
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software  Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 *
20 * The Original Code is Copyright (C) 2006 Blender Foundation.
21 * All rights reserved.
22 *
23 * The Original Code is: all of this file.
24 *
25 * Contributor(s): Ben Batt <benbatt@gmail.com>
26 *
27 * ***** END GPL LICENSE BLOCK *****
28 *
29 * Implementation of CustomData.
30 *
31 * BKE_customdata.h contains the function prototypes for this file.
32 *
33 */
34
35 /** \file blender/blenkernel/intern/customdata.c
36  *  \ingroup bke
37  */
38  
39
40 #include <math.h>
41 #include <string.h>
42 #include <assert.h>
43
44 #include "MEM_guardedalloc.h"
45
46 #include "DNA_meshdata_types.h"
47 #include "DNA_ID.h"
48
49 #include "BLI_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                         for(i = 0; i < 2; i++)
470                                 for(y = 0; y < 4; y++)
471                                         for(x = 0; x < 4; x++)
472                                                 if(sw[x+i*4][y])
473                                                         vindex[x] = y;
474
475                         for(i = 0; i < 2; i++) {
476                                 float sw_m4[4][4] = {{0}};
477                                 int a = 7 & ~(1 << vindex[i*2] | 1 << vindex[i*2+1]);
478
479                                 sw_m4[0][vindex[i*2+1]] = 1;
480                                 sw_m4[1][vindex[i*2]] = 1;
481
482                                 for(x = 0; x < 3; x++)
483                                         if(a & (1 << x))
484                                                 sw_m4[2][x] = 1;
485
486                                 tris[i] = *((MDisps*)sources[i]);
487                                 tris[i].disps = MEM_dupallocN(tris[i].disps);
488                                 layerInterp_mdisps(&sources[i], NULL, (float*)sw_m4, 1, &tris[i]);
489                         }
490
491                         mdisp_join_tris(d, &tris[0], &tris[1]);
492
493                         for(i = 0; i < 2; i++)
494                                 MEM_freeN(tris[i].disps);
495
496                         return;
497                 }
498         }
499
500         /* For now, some restrictions on the input */
501         if(count != 1 || !sub_weights) {
502                 for(i = 0; i < d->totdisp; ++i)
503                         zero_v3(d->disps[i]);
504
505                 return;
506         }
507
508         /* Initialize the destination */
509         disps = MEM_callocN(3*d->totdisp*sizeof(float), "iterp disps");
510
511         side = sqrt(d->totdisp / dst_corners);
512         st = (side<<1)-1;
513         stl = st - 1;
514
515         sw= (void*)sub_weights;
516         for(i = 0; i < 4; ++i) {
517                 crn_weight[i][0] = 0 * sw[i][0] + stl * sw[i][1] + stl * sw[i][2] + 0 * sw[i][3];
518                 crn_weight[i][1] = 0 * sw[i][0] + 0 * sw[i][1] + stl * sw[i][2] + stl * sw[i][3];
519         }
520
521         multires_mdisp_smooth_bounds(s);
522
523         out = disps;
524         for(S = 0; S < dst_corners; S++) {
525                 float base[2], axis_x[2], axis_y[2];
526
527                 mdisp_apply_weight(S, dst_corners, 0, 0, st, crn_weight, &base[0], &base[1]);
528                 mdisp_apply_weight(S, dst_corners, side-1, 0, st, crn_weight, &axis_x[0], &axis_x[1]);
529                 mdisp_apply_weight(S, dst_corners, 0, side-1, st, crn_weight, &axis_y[0], &axis_y[1]);
530
531                 sub_v2_v2(axis_x, base);
532                 sub_v2_v2(axis_y, base);
533                 normalize_v2(axis_x);
534                 normalize_v2(axis_y);
535
536                 for(y = 0; y < side; ++y) {
537                         for(x = 0; x < side; ++x, ++out) {
538                                 int crn;
539                                 float face_u, face_v, crn_u, crn_v;
540
541                                 mdisp_apply_weight(S, dst_corners, x, y, st, crn_weight, &face_u, &face_v);
542                                 crn = mdisp_rot_face_to_quad_crn(src_corners, st, face_u, face_v, &crn_u, &crn_v);
543
544                                 old_mdisps_bilinear((*out), &s->disps[crn*side*side], side, crn_u, crn_v);
545                                 mdisp_flip_disp(crn, dst_corners, axis_x, axis_y, *out);
546                         }
547                 }
548         }
549
550         MEM_freeN(d->disps);
551         d->disps = disps;
552 }
553
554 static void layerCopy_mdisps(const void *source, void *dest, int count)
555 {
556         int i;
557         const MDisps *s = source;
558         MDisps *d = dest;
559
560         for(i = 0; i < count; ++i) {
561                 if(s[i].disps) {
562                         d[i].disps = MEM_dupallocN(s[i].disps);
563                         d[i].totdisp = s[i].totdisp;
564                 }
565                 else {
566                         d[i].disps = NULL;
567                         d[i].totdisp = 0;
568                 }
569                 
570         }
571 }
572
573 static void layerValidate_mdisps(void *data, int sub_elements)
574 {
575         MDisps *disps = data;
576         if(disps->disps) {
577                 int corners = multires_mdisp_corners(disps);
578
579                 if(corners != sub_elements) {
580                         MEM_freeN(disps->disps);
581                         disps->totdisp = disps->totdisp / corners * sub_elements;
582                         disps->disps = MEM_callocN(3*disps->totdisp*sizeof(float), "layerValidate_mdisps");
583                 }
584         }
585 }
586
587 static void layerFree_mdisps(void *data, int count, int UNUSED(size))
588 {
589         int i;
590         MDisps *d = data;
591
592         for(i = 0; i < count; ++i) {
593                 if(d[i].disps)
594                         MEM_freeN(d[i].disps);
595                 d[i].disps = NULL;
596                 d[i].totdisp = 0;
597         }
598 }
599
600 static int layerRead_mdisps(CDataFile *cdf, void *data, int count)
601 {
602         MDisps *d = data;
603         int i;
604
605         for(i = 0; i < count; ++i) {
606                 if(!d[i].disps)
607                         d[i].disps = MEM_callocN(sizeof(float)*3*d[i].totdisp, "mdisps read");
608
609                 if(!cdf_read_data(cdf, d[i].totdisp*3*sizeof(float), d[i].disps)) {
610                         printf("failed to read multires displacement %d/%d %d\n", i, count, d[i].totdisp);
611                         return 0;
612                 }
613         }
614
615         return 1;
616 }
617
618 static int layerWrite_mdisps(CDataFile *cdf, void *data, int count)
619 {
620         MDisps *d = data;
621         int i;
622
623         for(i = 0; i < count; ++i) {
624                 if(!cdf_write_data(cdf, d[i].totdisp*3*sizeof(float), d[i].disps)) {
625                         printf("failed to write multires displacement %d/%d %d\n", i, count, d[i].totdisp);
626                         return 0;
627                 }
628         }
629
630         return 1;
631 }
632
633 static size_t layerFilesize_mdisps(CDataFile *UNUSED(cdf), void *data, int count)
634 {
635         MDisps *d = data;
636         size_t size = 0;
637         int i;
638
639         for(i = 0; i < count; ++i)
640                 size += d[i].totdisp*3*sizeof(float);
641
642         return size;
643 }
644
645 /* --------- */
646
647 static void layerDefault_mloopcol(void *data, int count)
648 {
649         static MLoopCol default_mloopcol = {255,255,255,255};
650         MLoopCol *mlcol = (MLoopCol*)data;
651         int i;
652         for(i = 0; i < count; i++)
653                 mlcol[i] = default_mloopcol;
654
655 }
656
657 static void layerInterp_mloopcol(void **sources, float *weights,
658                                 float *sub_weights, int count, void *dest)
659 {
660         MLoopCol *mc = dest;
661         int i;
662         float *sub_weight;
663         struct {
664                 float a;
665                 float r;
666                 float g;
667                 float b;
668         } col;
669         col.a = col.r = col.g = col.b = 0;
670
671         sub_weight = sub_weights;
672         for(i = 0; i < count; ++i){
673                 float weight = weights ? weights[i] : 1;
674                 MLoopCol *src = sources[i];
675                 if(sub_weights){
676                         col.a += src->a * (*sub_weight) * weight;
677                         col.r += src->r * (*sub_weight) * weight;
678                         col.g += src->g * (*sub_weight) * weight;
679                         col.b += src->b * (*sub_weight) * weight;
680                         sub_weight++;           
681                 } else {
682                         col.a += src->a * weight;
683                         col.r += src->r * weight;
684                         col.g += src->g * weight;
685                         col.b += src->b * weight;
686                 }
687         }
688         
689         /* Subdivide smooth or fractal can cause problems without clamping
690          * although weights should also not cause this situation */
691         CLAMP(col.a, 0.0f, 255.0f);
692         CLAMP(col.r, 0.0f, 255.0f);
693         CLAMP(col.g, 0.0f, 255.0f);
694         CLAMP(col.b, 0.0f, 255.0f);
695         
696         mc->a = (int)col.a;
697         mc->r = (int)col.r;
698         mc->g = (int)col.g;
699         mc->b = (int)col.b;
700 }
701 static void layerInterp_mloopuv(void **sources, float *weights,
702                                 float *sub_weights, int count, void *dest)
703 {
704         MLoopUV *mluv = dest;
705         int i;
706         float *sub_weight;
707         struct {
708                 float u;
709                 float v;
710         }uv;
711         uv.u = uv.v = 0.0;
712
713         sub_weight = sub_weights;
714         for(i = 0; i < count; ++i){
715                 float weight = weights ? weights[i] : 1;
716                 MLoopUV *src = sources[i];
717                 if(sub_weights){
718                         uv.u += src->uv[0] * (*sub_weight) * weight;
719                         uv.v += src->uv[1] * (*sub_weight) * weight;
720                         sub_weight++;           
721                 } else {
722                         uv.u += src->uv[0] * weight;
723                         uv.v += src->uv[1] * weight;
724                 }
725         }
726         mluv->uv[0] = uv.u;
727         mluv->uv[1] = uv.v;
728 }
729
730 static void layerInterp_mcol(void **sources, float *weights,
731                                                          float *sub_weights, int count, void *dest)
732 {
733         MCol *mc = dest;
734         int i, j, k;
735         struct {
736                 float a;
737                 float r;
738                 float g;
739                 float b;
740         } col[4];
741         float *sub_weight;
742
743         if(count <= 0) return;
744
745         memset(col, 0, sizeof(col));
746         
747         sub_weight = sub_weights;
748         for(i = 0; i < count; ++i) {
749                 float weight = weights ? weights[i] : 1;
750
751                 for(j = 0; j < 4; ++j) {
752                         if(sub_weights) {
753                                 MCol *src = sources[i];
754                                 for(k = 0; k < 4; ++k, ++sub_weight, ++src) {
755                                         col[j].a += src->a * (*sub_weight) * weight;
756                                         col[j].r += src->r * (*sub_weight) * weight;
757                                         col[j].g += src->g * (*sub_weight) * weight;
758                                         col[j].b += src->b * (*sub_weight) * weight;
759                                 }
760                         } else {
761                                 MCol *src = sources[i];
762                                 col[j].a += src[j].a * weight;
763                                 col[j].r += src[j].r * weight;
764                                 col[j].g += src[j].g * weight;
765                                 col[j].b += src[j].b * weight;
766                         }
767                 }
768         }
769
770         for(j = 0; j < 4; ++j) {
771                 
772                 /* Subdivide smooth or fractal can cause problems without clamping
773                  * although weights should also not cause this situation */
774                 CLAMP(col[j].a, 0.0f, 255.0f);
775                 CLAMP(col[j].r, 0.0f, 255.0f);
776                 CLAMP(col[j].g, 0.0f, 255.0f);
777                 CLAMP(col[j].b, 0.0f, 255.0f);
778                 
779                 mc[j].a = (int)col[j].a;
780                 mc[j].r = (int)col[j].r;
781                 mc[j].g = (int)col[j].g;
782                 mc[j].b = (int)col[j].b;
783         }
784 }
785
786 static void layerSwap_mcol(void *data, const int *corner_indices)
787 {
788         MCol *mcol = data;
789         MCol col[4];
790         int j;
791
792         for(j = 0; j < 4; ++j)
793                 col[j] = mcol[corner_indices[j]];
794
795         memcpy(mcol, col, sizeof(col));
796 }
797
798 static void layerDefault_mcol(void *data, int count)
799 {
800         static MCol default_mcol = {255, 255, 255, 255};
801         MCol *mcol = (MCol*)data;
802         int i;
803
804         for(i = 0; i < 4*count; i++)
805                 mcol[i] = default_mcol;
806 }
807
808
809
810 static const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = {
811         {sizeof(MVert), "MVert", 1, NULL, NULL, NULL, NULL, NULL, NULL},
812         {sizeof(MSticky), "MSticky", 1, NULL, NULL, NULL, layerInterp_msticky, NULL,
813          NULL},
814         {sizeof(MDeformVert), "MDeformVert", 1, NULL, layerCopy_mdeformvert,
815          layerFree_mdeformvert, layerInterp_mdeformvert, NULL, NULL},
816         {sizeof(MEdge), "MEdge", 1, NULL, NULL, NULL, NULL, NULL, NULL},
817         {sizeof(MFace), "MFace", 1, NULL, NULL, NULL, NULL, NULL, NULL},
818         {sizeof(MTFace), "MTFace", 1, "UVTex", layerCopy_tface, NULL,
819          layerInterp_tface, layerSwap_tface, layerDefault_tface},
820         /* 4 MCol structs per face */
821         {sizeof(MCol)*4, "MCol", 4, "Col", NULL, NULL, layerInterp_mcol,
822          layerSwap_mcol, layerDefault_mcol},
823         {sizeof(int), "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
824         /* 3 floats per normal vector */
825         {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
826         {sizeof(int), "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
827         {sizeof(MFloatProperty), "MFloatProperty",1,"Float",NULL,NULL,NULL,NULL},
828         {sizeof(MIntProperty), "MIntProperty",1,"Int",NULL,NULL,NULL,NULL},
829         {sizeof(MStringProperty), "MStringProperty",1,"String",NULL,NULL,NULL,NULL},
830         {sizeof(OrigSpaceFace), "OrigSpaceFace", 1, "UVTex", layerCopy_origspace_face, NULL,
831          layerInterp_origspace_face, layerSwap_origspace_face, layerDefault_origspace_face},
832         {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
833         {sizeof(MTexPoly), "MTexPoly", 1, "Face Texture", NULL, NULL, NULL, NULL, NULL},
834         {sizeof(MLoopUV), "MLoopUV", 1, "UV coord", NULL, NULL, layerInterp_mloopuv, NULL, NULL},
835         {sizeof(MLoopCol), "MLoopCol", 1, "Col", NULL, NULL, layerInterp_mloopcol, NULL, layerDefault_mloopcol},
836         {sizeof(float)*4*4, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
837         {sizeof(MDisps), "MDisps", 1, NULL, layerCopy_mdisps,
838          layerFree_mdisps, layerInterp_mdisps, layerSwap_mdisps, NULL, layerRead_mdisps, layerWrite_mdisps,
839          layerFilesize_mdisps, layerValidate_mdisps},
840         {sizeof(MCol)*4, "MCol", 4, "WeightCol", NULL, NULL, layerInterp_mcol,
841          layerSwap_mcol, layerDefault_mcol},
842          {sizeof(MCol)*4, "MCol", 4, "IDCol", NULL, NULL, layerInterp_mcol,
843          layerSwap_mcol, layerDefault_mcol},
844          {sizeof(MCol)*4, "MCol", 4, "TexturedCol", NULL, NULL, layerInterp_mcol,
845          layerSwap_mcol, layerDefault_mcol},
846         {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL}
847 };
848
849 static const char *LAYERTYPENAMES[CD_NUMTYPES] = {
850         /*   0-4 */ "CDMVert", "CDMSticky", "CDMDeformVert", "CDMEdge", "CDMFace",
851         /*   5-9 */ "CDMTFace", "CDMCol", "CDOrigIndex", "CDNormal", "CDFlags",
852         /* 10-14 */ "CDMFloatProperty", "CDMIntProperty","CDMStringProperty", "CDOrigSpace", "CDOrco",
853         /* 15-19 */ "CDMTexPoly", "CDMLoopUV", "CDMloopCol", "CDTangent", "CDMDisps",
854         /* 20-23 */"CDWeightMCol", "CDIDMCol", "CDTextureMCol", "CDClothOrco"
855 };
856
857 const CustomDataMask CD_MASK_BAREMESH =
858         CD_MASK_MVERT | CD_MASK_MEDGE | CD_MASK_MFACE;
859 const CustomDataMask CD_MASK_MESH =
860         CD_MASK_MVERT | CD_MASK_MEDGE | CD_MASK_MFACE |
861         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE | CD_MASK_MCOL |
862         CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR | CD_MASK_MDISPS;
863 const CustomDataMask CD_MASK_EDITMESH =
864         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE |
865         CD_MASK_MCOL|CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR | CD_MASK_MDISPS;
866 const CustomDataMask CD_MASK_DERIVEDMESH =
867         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE |
868         CD_MASK_MCOL | CD_MASK_ORIGINDEX | CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_CLOTH_ORCO |
869         CD_MASK_PROP_STR | CD_MASK_ORIGSPACE | CD_MASK_ORCO | CD_MASK_TANGENT | CD_MASK_WEIGHT_MCOL;
870 const CustomDataMask CD_MASK_BMESH = 
871         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR;
872 const CustomDataMask CD_MASK_FACECORNERS =
873         CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_MTEXPOLY | CD_MASK_MLOOPUV |
874         CD_MASK_MLOOPCOL;
875
876
877 static const LayerTypeInfo *layerType_getInfo(int type)
878 {
879         if(type < 0 || type >= CD_NUMTYPES) return NULL;
880
881         return &LAYERTYPEINFO[type];
882 }
883
884 static const char *layerType_getName(int type)
885 {
886         if(type < 0 || type >= CD_NUMTYPES) return NULL;
887
888         return LAYERTYPENAMES[type];
889 }
890
891 /********************* CustomData functions *********************/
892 static void customData_update_offsets(CustomData *data);
893
894 static CustomDataLayer *customData_add_layer__internal(CustomData *data,
895         int type, int alloctype, void *layerdata, int totelem, const char *name);
896
897 void CustomData_merge(const struct CustomData *source, struct CustomData *dest,
898                                           CustomDataMask mask, int alloctype, int totelem)
899 {
900         /*const LayerTypeInfo *typeInfo;*/
901         CustomDataLayer *layer, *newlayer;
902         int i, type, number = 0, lasttype = -1, lastactive = 0, lastrender = 0, lastclone = 0, lastmask = 0, lastflag = 0;
903
904         for(i = 0; i < source->totlayer; ++i) {
905                 layer = &source->layers[i];
906                 /*typeInfo = layerType_getInfo(layer->type);*/ /*UNUSED*/
907
908                 type = layer->type;
909
910                 if (type != lasttype) {
911                         number = 0;
912                         lastactive = layer->active;
913                         lastrender = layer->active_rnd;
914                         lastclone = layer->active_clone;
915                         lastmask = layer->active_mask;
916                         lasttype = type;
917                         lastflag = layer->flag;
918                 }
919                 else
920                         number++;
921
922                 if(lastflag & CD_FLAG_NOCOPY) continue;
923                 else if(!((int)mask & (int)(1 << (int)type))) continue;
924                 else if(number < CustomData_number_of_layers(dest, type)) continue;
925
926                 if((alloctype == CD_ASSIGN) && (lastflag & CD_FLAG_NOFREE))
927                         newlayer = customData_add_layer__internal(dest, type, CD_REFERENCE,
928                                 layer->data, totelem, layer->name);
929                 else
930                         newlayer = customData_add_layer__internal(dest, type, alloctype,
931                                 layer->data, totelem, layer->name);
932                 
933                 if(newlayer) {
934                         newlayer->active = lastactive;
935                         newlayer->active_rnd = lastrender;
936                         newlayer->active_clone = lastclone;
937                         newlayer->active_mask = lastmask;
938                         newlayer->flag |= lastflag & (CD_FLAG_EXTERNAL|CD_FLAG_IN_MEMORY);
939                 }
940         }
941 }
942
943 void CustomData_copy(const struct CustomData *source, struct CustomData *dest,
944                                          CustomDataMask mask, int alloctype, int totelem)
945 {
946         memset(dest, 0, sizeof(*dest));
947
948         if(source->external)
949                 dest->external= MEM_dupallocN(source->external);
950
951         CustomData_merge(source, dest, mask, alloctype, totelem);
952 }
953
954 static void customData_free_layer__internal(CustomDataLayer *layer, int totelem)
955 {
956         const LayerTypeInfo *typeInfo;
957
958         if(!(layer->flag & CD_FLAG_NOFREE) && layer->data) {
959                 typeInfo = layerType_getInfo(layer->type);
960
961                 if(typeInfo->free)
962                         typeInfo->free(layer->data, totelem, typeInfo->size);
963
964                 if(layer->data)
965                         MEM_freeN(layer->data);
966         }
967 }
968
969 static void CustomData_external_free(CustomData *data)
970 {
971         if(data->external) {
972                 MEM_freeN(data->external);
973                 data->external= NULL;
974         }
975 }
976
977 void CustomData_free(CustomData *data, int totelem)
978 {
979         int i;
980
981         for(i = 0; i < data->totlayer; ++i)
982                 customData_free_layer__internal(&data->layers[i], totelem);
983
984         if(data->layers)
985                 MEM_freeN(data->layers);
986         
987         CustomData_external_free(data);
988         
989         memset(data, 0, sizeof(*data));
990 }
991
992 static void customData_update_offsets(CustomData *data)
993 {
994         const LayerTypeInfo *typeInfo;
995         int i, offset = 0;
996
997         for(i = 0; i < data->totlayer; ++i) {
998                 typeInfo = layerType_getInfo(data->layers[i].type);
999
1000                 data->layers[i].offset = offset;
1001                 offset += typeInfo->size;
1002         }
1003
1004         data->totsize = offset;
1005 }
1006
1007 int CustomData_get_layer_index(const CustomData *data, int type)
1008 {
1009         int i; 
1010
1011         for(i=0; i < data->totlayer; ++i)
1012                 if(data->layers[i].type == type)
1013                         return i;
1014
1015         return -1;
1016 }
1017
1018 int CustomData_get_named_layer_index(const CustomData *data, int type, const char *name)
1019 {
1020         int i;
1021
1022         for(i=0; i < data->totlayer; ++i)
1023                 if(data->layers[i].type == type && strcmp(data->layers[i].name, name)==0)
1024                         return i;
1025
1026         return -1;
1027 }
1028
1029 int CustomData_get_active_layer_index(const CustomData *data, int type)
1030 {
1031         int i;
1032
1033         for(i=0; i < data->totlayer; ++i)
1034                 if(data->layers[i].type == type)
1035                         return i + data->layers[i].active;
1036
1037         return -1;
1038 }
1039
1040 int CustomData_get_render_layer_index(const CustomData *data, int type)
1041 {
1042         int i;
1043
1044         for(i=0; i < data->totlayer; ++i)
1045                 if(data->layers[i].type == type)
1046                         return i + data->layers[i].active_rnd;
1047
1048         return -1;
1049 }
1050
1051 int CustomData_get_clone_layer_index(const CustomData *data, int type)
1052 {
1053         int i;
1054
1055         for(i=0; i < data->totlayer; ++i)
1056                 if(data->layers[i].type == type)
1057                         return i + data->layers[i].active_clone;
1058
1059         return -1;
1060 }
1061
1062 int CustomData_get_stencil_layer_index(const CustomData *data, int type)
1063 {
1064         int i;
1065
1066         for(i=0; i < data->totlayer; ++i)
1067                 if(data->layers[i].type == type)
1068                         return i + data->layers[i].active_mask;
1069
1070         return -1;
1071 }
1072
1073 int CustomData_get_active_layer(const CustomData *data, int type)
1074 {
1075         int i;
1076
1077         for(i=0; i < data->totlayer; ++i)
1078                 if(data->layers[i].type == type)
1079                         return data->layers[i].active;
1080
1081         return -1;
1082 }
1083
1084 int CustomData_get_render_layer(const CustomData *data, int type)
1085 {
1086         int i;
1087
1088         for(i=0; i < data->totlayer; ++i)
1089                 if(data->layers[i].type == type)
1090                         return data->layers[i].active_rnd;
1091
1092         return -1;
1093 }
1094
1095 int CustomData_get_clone_layer(const CustomData *data, int type)
1096 {
1097         int i;
1098
1099         for(i=0; i < data->totlayer; ++i)
1100                 if(data->layers[i].type == type)
1101                         return data->layers[i].active_clone;
1102
1103         return -1;
1104 }
1105
1106 int CustomData_get_stencil_layer(const CustomData *data, int type)
1107 {
1108         int i;
1109
1110         for(i=0; i < data->totlayer; ++i)
1111                 if(data->layers[i].type == type)
1112                         return data->layers[i].active_mask;
1113
1114         return -1;
1115 }
1116
1117 void CustomData_set_layer_active(CustomData *data, int type, int n)
1118 {
1119         int i;
1120
1121         for(i=0; i < data->totlayer; ++i)
1122                 if(data->layers[i].type == type)
1123                         data->layers[i].active = n;
1124 }
1125
1126 void CustomData_set_layer_render(CustomData *data, int type, int n)
1127 {
1128         int i;
1129
1130         for(i=0; i < data->totlayer; ++i)
1131                 if(data->layers[i].type == type)
1132                         data->layers[i].active_rnd = n;
1133 }
1134
1135 void CustomData_set_layer_clone(CustomData *data, int type, int n)
1136 {
1137         int i;
1138
1139         for(i=0; i < data->totlayer; ++i)
1140                 if(data->layers[i].type == type)
1141                         data->layers[i].active_clone = n;
1142 }
1143
1144 void CustomData_set_layer_stencil(CustomData *data, int type, int n)
1145 {
1146         int i;
1147
1148         for(i=0; i < data->totlayer; ++i)
1149                 if(data->layers[i].type == type)
1150                         data->layers[i].active_mask = n;
1151 }
1152
1153 /* for using with an index from CustomData_get_active_layer_index and CustomData_get_render_layer_index */
1154 void CustomData_set_layer_active_index(CustomData *data, int type, int n)
1155 {
1156         int i;
1157
1158         for(i=0; i < data->totlayer; ++i)
1159                 if(data->layers[i].type == type)
1160                         data->layers[i].active = n-i;
1161 }
1162
1163 void CustomData_set_layer_render_index(CustomData *data, int type, int n)
1164 {
1165         int i;
1166
1167         for(i=0; i < data->totlayer; ++i)
1168                 if(data->layers[i].type == type)
1169                         data->layers[i].active_rnd = n-i;
1170 }
1171
1172 void CustomData_set_layer_clone_index(CustomData *data, int type, int n)
1173 {
1174         int i;
1175
1176         for(i=0; i < data->totlayer; ++i)
1177                 if(data->layers[i].type == type)
1178                         data->layers[i].active_clone = n-i;
1179 }
1180
1181 void CustomData_set_layer_stencil_index(CustomData *data, int type, int n)
1182 {
1183         int i;
1184
1185         for(i=0; i < data->totlayer; ++i)
1186                 if(data->layers[i].type == type)
1187                         data->layers[i].active_mask = n-i;
1188 }
1189
1190 void CustomData_set_layer_flag(struct CustomData *data, int type, int flag)
1191 {
1192         int i;
1193
1194         for(i=0; i < data->totlayer; ++i)
1195                 if(data->layers[i].type == type)
1196                         data->layers[i].flag |= flag;
1197 }
1198
1199 static int customData_resize(CustomData *data, int amount)
1200 {
1201         CustomDataLayer *tmp = MEM_callocN(sizeof(*tmp)*(data->maxlayer + amount),
1202                                                                            "CustomData->layers");
1203         if(!tmp) return 0;
1204
1205         data->maxlayer += amount;
1206         if (data->layers) {
1207                 memcpy(tmp, data->layers, sizeof(*tmp) * data->totlayer);
1208                 MEM_freeN(data->layers);
1209         }
1210         data->layers = tmp;
1211
1212         return 1;
1213 }
1214
1215 static CustomDataLayer *customData_add_layer__internal(CustomData *data,
1216         int type, int alloctype, void *layerdata, int totelem, const char *name)
1217 {
1218         const LayerTypeInfo *typeInfo= layerType_getInfo(type);
1219         int size = typeInfo->size * totelem, flag = 0, index = data->totlayer;
1220         void *newlayerdata;
1221
1222         if (!typeInfo->defaultname && CustomData_has_layer(data, type))
1223                 return &data->layers[CustomData_get_layer_index(data, type)];
1224
1225         if((alloctype == CD_ASSIGN) || (alloctype == CD_REFERENCE)) {
1226                 newlayerdata = layerdata;
1227         }
1228         else {
1229                 newlayerdata = MEM_callocN(size, layerType_getName(type));
1230                 if(!newlayerdata)
1231                         return NULL;
1232         }
1233
1234         if (alloctype == CD_DUPLICATE) {
1235                 if(typeInfo->copy)
1236                         typeInfo->copy(layerdata, newlayerdata, totelem);
1237                 else
1238                         memcpy(newlayerdata, layerdata, size);
1239         }
1240         else if (alloctype == CD_DEFAULT) {
1241                 if(typeInfo->set_default)
1242                         typeInfo->set_default((char*)newlayerdata, totelem);
1243         }
1244         else if (alloctype == CD_REFERENCE)
1245                 flag |= CD_FLAG_NOFREE;
1246
1247         if(index >= data->maxlayer) {
1248                 if(!customData_resize(data, CUSTOMDATA_GROW)) {
1249                         if(newlayerdata != layerdata)
1250                                 MEM_freeN(newlayerdata);
1251                         return NULL;
1252                 }
1253         }
1254         
1255         data->totlayer++;
1256
1257         /* keep layers ordered by type */
1258         for( ; index > 0 && data->layers[index - 1].type > type; --index)
1259                 data->layers[index] = data->layers[index - 1];
1260
1261         data->layers[index].type = type;
1262         data->layers[index].flag = flag;
1263         data->layers[index].data = newlayerdata;
1264         if(name || (name=typeInfo->defaultname)) {
1265                 BLI_strncpy(data->layers[index].name, name, 32);
1266                 CustomData_set_layer_unique_name(data, index);
1267         }
1268         else
1269                 data->layers[index].name[0] = '\0';
1270
1271         if(index > 0 && data->layers[index-1].type == type) {
1272                 data->layers[index].active = data->layers[index-1].active;
1273                 data->layers[index].active_rnd = data->layers[index-1].active_rnd;
1274                 data->layers[index].active_clone = data->layers[index-1].active_clone;
1275                 data->layers[index].active_mask = data->layers[index-1].active_mask;
1276         } else {
1277                 data->layers[index].active = 0;
1278                 data->layers[index].active_rnd = 0;
1279                 data->layers[index].active_clone = 0;
1280                 data->layers[index].active_mask = 0;
1281         }
1282         
1283         customData_update_offsets(data);
1284
1285         return &data->layers[index];
1286 }
1287
1288 void *CustomData_add_layer(CustomData *data, int type, int alloctype,
1289                                                    void *layerdata, int totelem)
1290 {
1291         CustomDataLayer *layer;
1292         const LayerTypeInfo *typeInfo= layerType_getInfo(type);
1293         
1294         layer = customData_add_layer__internal(data, type, alloctype, layerdata,
1295                                                                                    totelem, typeInfo->defaultname);
1296
1297         if(layer)
1298                 return layer->data;
1299
1300         return NULL;
1301 }
1302
1303 /*same as above but accepts a name*/
1304 void *CustomData_add_layer_named(CustomData *data, int type, int alloctype,
1305                                                    void *layerdata, int totelem, const char *name)
1306 {
1307         CustomDataLayer *layer;
1308         
1309         layer = customData_add_layer__internal(data, type, alloctype, layerdata,
1310                                                                                    totelem, name);
1311
1312         if(layer)
1313                 return layer->data;
1314
1315         return NULL;
1316 }
1317
1318
1319 int CustomData_free_layer(CustomData *data, int type, int totelem, int index)
1320 {
1321         int i;
1322         
1323         if (index < 0) return 0;
1324
1325         customData_free_layer__internal(&data->layers[index], totelem);
1326
1327         for (i=index+1; i < data->totlayer; ++i)
1328                 data->layers[i-1] = data->layers[i];
1329
1330         data->totlayer--;
1331
1332         /* if layer was last of type in array, set new active layer */
1333         if ((index >= data->totlayer) || (data->layers[index].type != type)) {
1334                 i = CustomData_get_layer_index(data, type);
1335                 
1336                 if (i >= 0)
1337                         for (; i < data->totlayer && data->layers[i].type == type; i++) {
1338                                 data->layers[i].active--;
1339                                 data->layers[i].active_rnd--;
1340                                 data->layers[i].active_clone--;
1341                                 data->layers[i].active_mask--;
1342                         }
1343         }
1344
1345         if (data->totlayer <= data->maxlayer-CUSTOMDATA_GROW)
1346                 customData_resize(data, -CUSTOMDATA_GROW);
1347
1348         customData_update_offsets(data);
1349
1350         return 1;
1351 }
1352
1353 int CustomData_free_layer_active(CustomData *data, int type, int totelem)
1354 {
1355         int index = 0;
1356         index = CustomData_get_active_layer_index(data, type);
1357         if (index < 0) return 0;
1358         return CustomData_free_layer(data, type, totelem, index);
1359 }
1360
1361
1362 void CustomData_free_layers(CustomData *data, int type, int totelem)
1363 {
1364         while (CustomData_has_layer(data, type))
1365                 CustomData_free_layer_active(data, type, totelem);
1366 }
1367
1368 int CustomData_has_layer(const CustomData *data, int type)
1369 {
1370         return (CustomData_get_layer_index(data, type) != -1);
1371 }
1372
1373 int CustomData_number_of_layers(const CustomData *data, int type)
1374 {
1375         int i, number = 0;
1376
1377         for(i = 0; i < data->totlayer; i++)
1378                 if(data->layers[i].type == type)
1379                         number++;
1380         
1381         return number;
1382 }
1383
1384 void *CustomData_duplicate_referenced_layer(struct CustomData *data, int type)
1385 {
1386         CustomDataLayer *layer;
1387         int layer_index;
1388
1389         /* get the layer index of the first layer of type */
1390         layer_index = CustomData_get_active_layer_index(data, type);
1391         if(layer_index < 0) return NULL;
1392
1393         layer = &data->layers[layer_index];
1394
1395         if (layer->flag & CD_FLAG_NOFREE) {
1396                 layer->data = MEM_dupallocN(layer->data);
1397                 layer->flag &= ~CD_FLAG_NOFREE;
1398         }
1399
1400         return layer->data;
1401 }
1402
1403 void *CustomData_duplicate_referenced_layer_named(struct CustomData *data,
1404                                                                                                   int type, const char *name)
1405 {
1406         CustomDataLayer *layer;
1407         int layer_index;
1408
1409         /* get the layer index of the desired layer */
1410         layer_index = CustomData_get_named_layer_index(data, type, name);
1411         if(layer_index < 0) return NULL;
1412
1413         layer = &data->layers[layer_index];
1414
1415         if (layer->flag & CD_FLAG_NOFREE) {
1416                 layer->data = MEM_dupallocN(layer->data);
1417                 layer->flag &= ~CD_FLAG_NOFREE;
1418         }
1419
1420         return layer->data;
1421 }
1422
1423 void CustomData_free_temporary(CustomData *data, int totelem)
1424 {
1425         CustomDataLayer *layer;
1426         int i, j;
1427
1428         for(i = 0, j = 0; i < data->totlayer; ++i) {
1429                 layer = &data->layers[i];
1430
1431                 if (i != j)
1432                         data->layers[j] = data->layers[i];
1433
1434                 if ((layer->flag & CD_FLAG_TEMPORARY) == CD_FLAG_TEMPORARY)
1435                         customData_free_layer__internal(layer, totelem);
1436                 else
1437                         j++;
1438         }
1439
1440         data->totlayer = j;
1441
1442         if(data->totlayer <= data->maxlayer-CUSTOMDATA_GROW)
1443                 customData_resize(data, -CUSTOMDATA_GROW);
1444
1445         customData_update_offsets(data);
1446 }
1447
1448 void CustomData_set_only_copy(const struct CustomData *data,
1449                                                           CustomDataMask mask)
1450 {
1451         int i;
1452
1453         for(i = 0; i < data->totlayer; ++i)
1454                 if(!((int)mask & (int)(1 << (int)data->layers[i].type)))
1455                         data->layers[i].flag |= CD_FLAG_NOCOPY;
1456 }
1457
1458 void CustomData_copy_data(const CustomData *source, CustomData *dest,
1459                                                   int source_index, int dest_index, int count)
1460 {
1461         const LayerTypeInfo *typeInfo;
1462         int src_i, dest_i;
1463         int src_offset;
1464         int dest_offset;
1465
1466         /* copies a layer at a time */
1467         dest_i = 0;
1468         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1469
1470                 /* find the first dest layer with type >= the source type
1471                  * (this should work because layers are ordered by type)
1472                  */
1473                 while(dest_i < dest->totlayer
1474                           && dest->layers[dest_i].type < source->layers[src_i].type)
1475                         ++dest_i;
1476
1477                 /* if there are no more dest layers, we're done */
1478                 if(dest_i >= dest->totlayer) return;
1479
1480                 /* if we found a matching layer, copy the data */
1481                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1482                         char *src_data = source->layers[src_i].data;
1483                         char *dest_data = dest->layers[dest_i].data;
1484
1485                         typeInfo = layerType_getInfo(source->layers[src_i].type);
1486
1487                         src_offset = source_index * typeInfo->size;
1488                         dest_offset = dest_index * typeInfo->size;
1489
1490                         if(typeInfo->copy)
1491                                 typeInfo->copy(src_data + src_offset,
1492                                                                 dest_data + dest_offset,
1493                                                                 count);
1494                         else
1495                                 memcpy(dest_data + dest_offset,
1496                                            src_data + src_offset,
1497                                            count * typeInfo->size);
1498
1499                         /* if there are multiple source & dest layers of the same type,
1500                          * we don't want to copy all source layers to the same dest, so
1501                          * increment dest_i
1502                          */
1503                         ++dest_i;
1504                 }
1505         }
1506 }
1507
1508 void CustomData_free_elem(CustomData *data, int index, int count)
1509 {
1510         int i;
1511         const LayerTypeInfo *typeInfo;
1512
1513         for(i = 0; i < data->totlayer; ++i) {
1514                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
1515                         typeInfo = layerType_getInfo(data->layers[i].type);
1516
1517                         if(typeInfo->free) {
1518                                 int offset = typeInfo->size * index;
1519
1520                                 typeInfo->free((char *)data->layers[i].data + offset,
1521                                                            count, typeInfo->size);
1522                         }
1523                 }
1524         }
1525 }
1526
1527 #define SOURCE_BUF_SIZE 100
1528
1529 void CustomData_interp(const CustomData *source, CustomData *dest,
1530                                            int *src_indices, float *weights, float *sub_weights,
1531                                            int count, int dest_index)
1532 {
1533         int src_i, dest_i;
1534         int dest_offset;
1535         int j;
1536         void *source_buf[SOURCE_BUF_SIZE];
1537         void **sources = source_buf;
1538
1539         /* slow fallback in case we're interpolating a ridiculous number of
1540          * elements
1541          */
1542         if(count > SOURCE_BUF_SIZE)
1543                 sources = MEM_callocN(sizeof(*sources) * count,
1544                                                           "CustomData_interp sources");
1545
1546         /* interpolates a layer at a time */
1547         dest_i = 0;
1548         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1549                 const LayerTypeInfo *typeInfo= layerType_getInfo(source->layers[src_i].type);
1550                 if(!typeInfo->interp) continue;
1551
1552                 /* find the first dest layer with type >= the source type
1553                  * (this should work because layers are ordered by type)
1554                  */
1555                 while(dest_i < dest->totlayer
1556                           && dest->layers[dest_i].type < source->layers[src_i].type)
1557                         ++dest_i;
1558
1559                 /* if there are no more dest layers, we're done */
1560                 if(dest_i >= dest->totlayer) return;
1561
1562                 /* if we found a matching layer, copy the data */
1563                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1564                         void *src_data = source->layers[src_i].data;
1565
1566                         for(j = 0; j < count; ++j)
1567                                 sources[j] = (char *)src_data
1568                                                          + typeInfo->size * src_indices[j];
1569
1570                         dest_offset = dest_index * typeInfo->size;
1571
1572                         typeInfo->interp(sources, weights, sub_weights, count,
1573                                                    (char *)dest->layers[dest_i].data + dest_offset);
1574
1575                         /* if there are multiple source & dest layers of the same type,
1576                          * we don't want to copy all source layers to the same dest, so
1577                          * increment dest_i
1578                          */
1579                         ++dest_i;
1580                 }
1581         }
1582
1583         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
1584 }
1585
1586 void CustomData_swap(struct CustomData *data, int index, const int *corner_indices)
1587 {
1588         const LayerTypeInfo *typeInfo;
1589         int i;
1590
1591         for(i = 0; i < data->totlayer; ++i) {
1592                 typeInfo = layerType_getInfo(data->layers[i].type);
1593
1594                 if(typeInfo->swap) {
1595                         int offset = typeInfo->size * index;
1596
1597                         typeInfo->swap((char *)data->layers[i].data + offset, corner_indices);
1598                 }
1599         }
1600 }
1601
1602 void *CustomData_get(const CustomData *data, int index, int type)
1603 {
1604         int offset;
1605         int layer_index;
1606         
1607         /* get the layer index of the active layer of type */
1608         layer_index = CustomData_get_active_layer_index(data, type);
1609         if(layer_index < 0) return NULL;
1610
1611         /* get the offset of the desired element */
1612         offset = layerType_getInfo(type)->size * index;
1613
1614         return (char *)data->layers[layer_index].data + offset;
1615 }
1616
1617 void *CustomData_get_layer(const CustomData *data, int type)
1618 {
1619         /* get the layer index of the active layer of type */
1620         int layer_index = CustomData_get_active_layer_index(data, type);
1621         if(layer_index < 0) return NULL;
1622
1623         return data->layers[layer_index].data;
1624 }
1625
1626 void *CustomData_get_layer_n(const CustomData *data, int type, int n)
1627 {
1628         /* get the layer index of the active layer of type */
1629         int layer_index = CustomData_get_layer_index(data, type);
1630         if(layer_index < 0) return NULL;
1631
1632         return data->layers[layer_index+n].data;
1633 }
1634
1635 void *CustomData_get_layer_named(const struct CustomData *data, int type,
1636                                                                  const char *name)
1637 {
1638         int layer_index = CustomData_get_named_layer_index(data, type, name);
1639         if(layer_index < 0) return NULL;
1640
1641         return data->layers[layer_index].data;
1642 }
1643
1644 void *CustomData_set_layer(const CustomData *data, int type, void *ptr)
1645 {
1646         /* get the layer index of the first layer of type */
1647         int layer_index = CustomData_get_active_layer_index(data, type);
1648
1649         if(layer_index < 0) return NULL;
1650
1651         data->layers[layer_index].data = ptr;
1652
1653         return ptr;
1654 }
1655
1656 void *CustomData_set_layer_n(const struct CustomData *data, int type, int n, void *ptr)
1657 {
1658         /* get the layer index of the first layer of type */
1659         int layer_index = CustomData_get_layer_index(data, type);
1660         if(layer_index < 0) return NULL;
1661
1662         data->layers[layer_index+n].data = ptr;
1663
1664         return ptr;
1665 }
1666
1667 void CustomData_set(const CustomData *data, int index, int type, void *source)
1668 {
1669         void *dest = CustomData_get(data, index, type);
1670         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1671
1672         if(!dest) return;
1673
1674         if(typeInfo->copy)
1675                 typeInfo->copy(source, dest, 1);
1676         else
1677                 memcpy(dest, source, typeInfo->size);
1678 }
1679
1680 /* EditMesh functions */
1681
1682 void CustomData_em_free_block(CustomData *data, void **block)
1683 {
1684         const LayerTypeInfo *typeInfo;
1685         int i;
1686
1687         if(!*block) return;
1688
1689         for(i = 0; i < data->totlayer; ++i) {
1690                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
1691                         typeInfo = layerType_getInfo(data->layers[i].type);
1692
1693                         if(typeInfo->free) {
1694                                 int offset = data->layers[i].offset;
1695                                 typeInfo->free((char*)*block + offset, 1, typeInfo->size);
1696                         }
1697                 }
1698         }
1699
1700         MEM_freeN(*block);
1701         *block = NULL;
1702 }
1703
1704 static void CustomData_em_alloc_block(CustomData *data, void **block)
1705 {
1706         /* TODO: optimize free/alloc */
1707
1708         if (*block)
1709                 CustomData_em_free_block(data, block);
1710
1711         if (data->totsize > 0)
1712                 *block = MEM_callocN(data->totsize, "CustomData EM block");
1713         else
1714                 *block = NULL;
1715 }
1716
1717 void CustomData_em_copy_data(const CustomData *source, CustomData *dest,
1718                                                         void *src_block, void **dest_block)
1719 {
1720         const LayerTypeInfo *typeInfo;
1721         int dest_i, src_i;
1722
1723         if (!*dest_block)
1724                 CustomData_em_alloc_block(dest, dest_block);
1725         
1726         /* copies a layer at a time */
1727         dest_i = 0;
1728         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1729
1730                 /* find the first dest layer with type >= the source type
1731                  * (this should work because layers are ordered by type)
1732                  */
1733                 while(dest_i < dest->totlayer
1734                           && dest->layers[dest_i].type < source->layers[src_i].type)
1735                         ++dest_i;
1736
1737                 /* if there are no more dest layers, we're done */
1738                 if(dest_i >= dest->totlayer) return;
1739
1740                 /* if we found a matching layer, copy the data */
1741                 if(dest->layers[dest_i].type == source->layers[src_i].type &&
1742                         strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
1743                         char *src_data = (char*)src_block + source->layers[src_i].offset;
1744                         char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
1745
1746                         typeInfo = layerType_getInfo(source->layers[src_i].type);
1747
1748                         if(typeInfo->copy)
1749                                 typeInfo->copy(src_data, dest_data, 1);
1750                         else
1751                                 memcpy(dest_data, src_data, typeInfo->size);
1752
1753                         /* if there are multiple source & dest layers of the same type,
1754                          * we don't want to copy all source layers to the same dest, so
1755                          * increment dest_i
1756                          */
1757                         ++dest_i;
1758                 }
1759         }
1760 }
1761
1762 void CustomData_em_validate_data(CustomData *data, void *block, int sub_elements)
1763 {
1764         int i;
1765         for(i = 0; i < data->totlayer; i++) {
1766                 const LayerTypeInfo *typeInfo = layerType_getInfo(data->layers[i].type);
1767                 char *leayer_data = (char*)block + data->layers[i].offset;
1768
1769                 if(typeInfo->validate)
1770                         typeInfo->validate(leayer_data, sub_elements);
1771         }
1772 }
1773
1774 void *CustomData_em_get(const CustomData *data, void *block, int type)
1775 {
1776         int layer_index;
1777         
1778         /* get the layer index of the first layer of type */
1779         layer_index = CustomData_get_active_layer_index(data, type);
1780         if(layer_index < 0) return NULL;
1781
1782         return (char *)block + data->layers[layer_index].offset;
1783 }
1784
1785 void *CustomData_em_get_n(const CustomData *data, void *block, int type, int n)
1786 {
1787         int layer_index;
1788         
1789         /* get the layer index of the first layer of type */
1790         layer_index = CustomData_get_layer_index(data, type);
1791         if(layer_index < 0) return NULL;
1792
1793         return (char *)block + data->layers[layer_index+n].offset;
1794 }
1795
1796 void CustomData_em_set(CustomData *data, void *block, int type, void *source)
1797 {
1798         void *dest = CustomData_em_get(data, block, type);
1799         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1800
1801         if(!dest) return;
1802
1803         if(typeInfo->copy)
1804                 typeInfo->copy(source, dest, 1);
1805         else
1806                 memcpy(dest, source, typeInfo->size);
1807 }
1808
1809 void CustomData_em_set_n(CustomData *data, void *block, int type, int n, void *source)
1810 {
1811         void *dest = CustomData_em_get_n(data, block, type, n);
1812         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1813
1814         if(!dest) return;
1815
1816         if(typeInfo->copy)
1817                 typeInfo->copy(source, dest, 1);
1818         else
1819                 memcpy(dest, source, typeInfo->size);
1820 }
1821
1822 void CustomData_em_interp(CustomData *data, void **src_blocks, float *weights,
1823                                                   float *sub_weights, int count, void *dest_block)
1824 {
1825         int i, j;
1826         void *source_buf[SOURCE_BUF_SIZE];
1827         void **sources = source_buf;
1828
1829         /* slow fallback in case we're interpolating a ridiculous number of
1830          * elements
1831          */
1832         if(count > SOURCE_BUF_SIZE)
1833                 sources = MEM_callocN(sizeof(*sources) * count,
1834                                                           "CustomData_interp sources");
1835
1836         /* interpolates a layer at a time */
1837         for(i = 0; i < data->totlayer; ++i) {
1838                 CustomDataLayer *layer = &data->layers[i];
1839                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
1840
1841                 if(typeInfo->interp) {
1842                         for(j = 0; j < count; ++j)
1843                                 sources[j] = (char *)src_blocks[j] + layer->offset;
1844
1845                         typeInfo->interp(sources, weights, sub_weights, count,
1846                                                           (char *)dest_block + layer->offset);
1847                 }
1848         }
1849
1850         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
1851 }
1852
1853 void CustomData_em_set_default(CustomData *data, void **block)
1854 {
1855         const LayerTypeInfo *typeInfo;
1856         int i;
1857
1858         if (!*block)
1859                 CustomData_em_alloc_block(data, block);
1860
1861         for(i = 0; i < data->totlayer; ++i) {
1862                 int offset = data->layers[i].offset;
1863
1864                 typeInfo = layerType_getInfo(data->layers[i].type);
1865
1866                 if(typeInfo->set_default)
1867                         typeInfo->set_default((char*)*block + offset, 1);
1868         }
1869 }
1870
1871 void CustomData_to_em_block(const CustomData *source, CustomData *dest,
1872                                                         int src_index, void **dest_block)
1873 {
1874         const LayerTypeInfo *typeInfo;
1875         int dest_i, src_i, src_offset;
1876
1877         if (!*dest_block)
1878                 CustomData_em_alloc_block(dest, dest_block);
1879         
1880         /* copies a layer at a time */
1881         dest_i = 0;
1882         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1883
1884                 /* find the first dest layer with type >= the source type
1885                  * (this should work because layers are ordered by type)
1886                  */
1887                 while(dest_i < dest->totlayer
1888                           && dest->layers[dest_i].type < source->layers[src_i].type)
1889                         ++dest_i;
1890
1891                 /* if there are no more dest layers, we're done */
1892                 if(dest_i >= dest->totlayer) return;
1893
1894                 /* if we found a matching layer, copy the data */
1895                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1896                         int offset = dest->layers[dest_i].offset;
1897                         char *src_data = source->layers[src_i].data;
1898                         char *dest_data = (char*)*dest_block + offset;
1899
1900                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
1901                         src_offset = src_index * typeInfo->size;
1902
1903                         if(typeInfo->copy)
1904                                 typeInfo->copy(src_data + src_offset, dest_data, 1);
1905                         else
1906                                 memcpy(dest_data, src_data + src_offset, typeInfo->size);
1907
1908                         /* if there are multiple source & dest layers of the same type,
1909                          * we don't want to copy all source layers to the same dest, so
1910                          * increment dest_i
1911                          */
1912                         ++dest_i;
1913                 }
1914         }
1915 }
1916
1917 void CustomData_from_em_block(const CustomData *source, CustomData *dest,
1918                                                           void *src_block, int dest_index)
1919 {
1920         const LayerTypeInfo *typeInfo;
1921         int dest_i, src_i, dest_offset;
1922
1923         /* copies a layer at a time */
1924         dest_i = 0;
1925         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1926
1927                 /* find the first dest layer with type >= the source type
1928                  * (this should work because layers are ordered by type)
1929                  */
1930                 while(dest_i < dest->totlayer
1931                           && dest->layers[dest_i].type < source->layers[src_i].type)
1932                         ++dest_i;
1933
1934                 /* if there are no more dest layers, we're done */
1935                 if(dest_i >= dest->totlayer) return;
1936
1937                 /* if we found a matching layer, copy the data */
1938                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1939                         int offset = source->layers[src_i].offset;
1940                         char *src_data = (char*)src_block + offset;
1941                         char *dest_data = dest->layers[dest_i].data;
1942
1943                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
1944                         dest_offset = dest_index * typeInfo->size;
1945
1946                         if(typeInfo->copy)
1947                                 typeInfo->copy(src_data, dest_data + dest_offset, 1);
1948                         else
1949                                 memcpy(dest_data + dest_offset, src_data, typeInfo->size);
1950
1951                         /* if there are multiple source & dest layers of the same type,
1952                          * we don't want to copy all source layers to the same dest, so
1953                          * increment dest_i
1954                          */
1955                         ++dest_i;
1956                 }
1957         }
1958
1959 }
1960
1961 /*Bmesh functions*/
1962 /*needed to convert to/from different face reps*/
1963 void CustomData_to_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata)
1964 {
1965         int i;
1966         for(i=0; i < fdata->totlayer; i++){
1967                 if(fdata->layers[i].type == CD_MTFACE){
1968                         CustomData_add_layer(pdata, CD_MTEXPOLY, CD_CALLOC, &(fdata->layers[i].name), 0);
1969                         CustomData_add_layer(ldata, CD_MLOOPUV, CD_CALLOC, &(fdata->layers[i].name), 0);
1970                 }
1971                 else if(fdata->layers[i].type == CD_MCOL)
1972                         CustomData_add_layer(ldata, CD_MLOOPCOL, CD_CALLOC, &(fdata->layers[i].name), 0);
1973         }               
1974 }
1975 void CustomData_from_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata, int total){
1976         int i;
1977         for(i=0; i < pdata->totlayer; i++){
1978                 if(pdata->layers[i].type == CD_MTEXPOLY)
1979                         CustomData_add_layer(fdata, CD_MTFACE, CD_CALLOC, &(pdata->layers[i].name), total);
1980         }
1981         for(i=0; i < ldata->totlayer; i++){
1982                 if(ldata->layers[i].type == CD_MLOOPCOL)
1983                         CustomData_add_layer(fdata, CD_MCOL, CD_CALLOC, &(ldata->layers[i].name), total);
1984         }
1985 }
1986
1987
1988 void CustomData_bmesh_init_pool(CustomData *data, int allocsize){
1989         if(data->totlayer)data->pool = BLI_mempool_create(data->totsize, allocsize, allocsize, 0);
1990 }
1991
1992 void CustomData_bmesh_free_block(CustomData *data, void **block)
1993 {
1994         const LayerTypeInfo *typeInfo;
1995         int i;
1996
1997         if(!*block) return;
1998         for(i = 0; i < data->totlayer; ++i) {
1999                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
2000                         typeInfo = layerType_getInfo(data->layers[i].type);
2001
2002                         if(typeInfo->free) {
2003                                 int offset = data->layers[i].offset;
2004                                 typeInfo->free((char*)*block + offset, 1, typeInfo->size);
2005                         }
2006                 }
2007         }
2008
2009         BLI_mempool_free(data->pool, *block);
2010         *block = NULL;
2011 }
2012
2013 static void CustomData_bmesh_alloc_block(CustomData *data, void **block)
2014 {
2015
2016         if (*block)
2017                 CustomData_bmesh_free_block(data, block);
2018
2019         if (data->totsize > 0)
2020                 *block = BLI_mempool_calloc(data->pool);
2021         else
2022                 *block = NULL;
2023 }
2024
2025 void CustomData_bmesh_copy_data(const CustomData *source, CustomData *dest,
2026                                                         void *src_block, void **dest_block)
2027 {
2028         const LayerTypeInfo *typeInfo;
2029         int dest_i, src_i;
2030
2031         if (!*dest_block)
2032                 CustomData_bmesh_alloc_block(dest, dest_block);
2033         
2034         /* copies a layer at a time */
2035         dest_i = 0;
2036         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2037
2038                 /* find the first dest layer with type >= the source type
2039                  * (this should work because layers are ordered by type)
2040                  */
2041                 while(dest_i < dest->totlayer
2042                           && dest->layers[dest_i].type < source->layers[src_i].type)
2043                         ++dest_i;
2044
2045                 /* if there are no more dest layers, we're done */
2046                 if(dest_i >= dest->totlayer) return;
2047
2048                 /* if we found a matching layer, copy the data */
2049                 if(dest->layers[dest_i].type == source->layers[src_i].type &&
2050                         strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
2051                         char *src_data = (char*)src_block + source->layers[src_i].offset;
2052                         char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
2053
2054                         typeInfo = layerType_getInfo(source->layers[src_i].type);
2055
2056                         if(typeInfo->copy)
2057                                 typeInfo->copy(src_data, dest_data, 1);
2058                         else
2059                                 memcpy(dest_data, src_data, typeInfo->size);
2060
2061                         /* if there are multiple source & dest layers of the same type,
2062                          * we don't want to copy all source layers to the same dest, so
2063                          * increment dest_i
2064                          */
2065                         ++dest_i;
2066                 }
2067         }
2068 }
2069
2070 /*Bmesh Custom Data Functions. Should replace editmesh ones with these as well, due to more effecient memory alloc*/
2071 void *CustomData_bmesh_get(const CustomData *data, void *block, int type)
2072 {
2073         int layer_index;
2074         
2075         /* get the layer index of the first layer of type */
2076         layer_index = CustomData_get_active_layer_index(data, type);
2077         if(layer_index < 0) return NULL;
2078
2079         return (char *)block + data->layers[layer_index].offset;
2080 }
2081
2082 void *CustomData_bmesh_get_n(const CustomData *data, void *block, int type, int n)
2083 {
2084         int layer_index;
2085         
2086         /* get the layer index of the first layer of type */
2087         layer_index = CustomData_get_layer_index(data, type);
2088         if(layer_index < 0) return NULL;
2089
2090         return (char *)block + data->layers[layer_index+n].offset;
2091 }
2092
2093 void CustomData_bmesh_set(const CustomData *data, void *block, int type, void *source)
2094 {
2095         void *dest = CustomData_bmesh_get(data, block, type);
2096         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2097
2098         if(!dest) return;
2099
2100         if(typeInfo->copy)
2101                 typeInfo->copy(source, dest, 1);
2102         else
2103                 memcpy(dest, source, typeInfo->size);
2104 }
2105
2106 void CustomData_bmesh_set_n(CustomData *data, void *block, int type, int n, void *source)
2107 {
2108         void *dest = CustomData_bmesh_get_n(data, block, type, n);
2109         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2110
2111         if(!dest) return;
2112
2113         if(typeInfo->copy)
2114                 typeInfo->copy(source, dest, 1);
2115         else
2116                 memcpy(dest, source, typeInfo->size);
2117 }
2118
2119 void CustomData_bmesh_interp(CustomData *data, void **src_blocks, float *weights,
2120                                                   float *sub_weights, int count, void *dest_block)
2121 {
2122         int i, j;
2123         void *source_buf[SOURCE_BUF_SIZE];
2124         void **sources = source_buf;
2125
2126         /* slow fallback in case we're interpolating a ridiculous number of
2127          * elements
2128          */
2129         if(count > SOURCE_BUF_SIZE)
2130                 sources = MEM_callocN(sizeof(*sources) * count,
2131                                                           "CustomData_interp sources");
2132
2133         /* interpolates a layer at a time */
2134         for(i = 0; i < data->totlayer; ++i) {
2135                 CustomDataLayer *layer = &data->layers[i];
2136                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
2137                 if(typeInfo->interp) {
2138                         for(j = 0; j < count; ++j)
2139                                 sources[j] = (char *)src_blocks[j] + layer->offset;
2140
2141                         typeInfo->interp(sources, weights, sub_weights, count,
2142                                                           (char *)dest_block + layer->offset);
2143                 }
2144         }
2145
2146         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
2147 }
2148
2149 void CustomData_bmesh_set_default(CustomData *data, void **block)
2150 {
2151         const LayerTypeInfo *typeInfo;
2152         int i;
2153
2154         if (!*block)
2155                 CustomData_bmesh_alloc_block(data, block);
2156
2157         for(i = 0; i < data->totlayer; ++i) {
2158                 int offset = data->layers[i].offset;
2159
2160                 typeInfo = layerType_getInfo(data->layers[i].type);
2161
2162                 if(typeInfo->set_default)
2163                         typeInfo->set_default((char*)*block + offset, 1);
2164         }
2165 }
2166
2167 void CustomData_to_bmesh_block(const CustomData *source, CustomData *dest,
2168                                                         int src_index, void **dest_block)
2169 {
2170         const LayerTypeInfo *typeInfo;
2171         int dest_i, src_i, src_offset;
2172
2173         if (!*dest_block)
2174                 CustomData_bmesh_alloc_block(dest, dest_block);
2175         
2176         /* copies a layer at a time */
2177         dest_i = 0;
2178         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2179
2180                 /* find the first dest layer with type >= the source type
2181                  * (this should work because layers are ordered by type)
2182                  */
2183                 while(dest_i < dest->totlayer
2184                           && dest->layers[dest_i].type < source->layers[src_i].type)
2185                         ++dest_i;
2186
2187                 /* if there are no more dest layers, we're done */
2188                 if(dest_i >= dest->totlayer) return;
2189
2190                 /* if we found a matching layer, copy the data */
2191                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2192                         int offset = dest->layers[dest_i].offset;
2193                         char *src_data = source->layers[src_i].data;
2194                         char *dest_data = (char*)*dest_block + offset;
2195
2196                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2197                         src_offset = src_index * typeInfo->size;
2198
2199                         if(typeInfo->copy)
2200                                 typeInfo->copy(src_data + src_offset, dest_data, 1);
2201                         else
2202                                 memcpy(dest_data, src_data + src_offset, typeInfo->size);
2203
2204                         /* if there are multiple source & dest layers of the same type,
2205                          * we don't want to copy all source layers to the same dest, so
2206                          * increment dest_i
2207                          */
2208                         ++dest_i;
2209                 }
2210         }
2211 }
2212
2213 void CustomData_from_bmesh_block(const CustomData *source, CustomData *dest,
2214                                                           void *src_block, int dest_index)
2215 {
2216         const LayerTypeInfo *typeInfo;
2217         int dest_i, src_i, dest_offset;
2218
2219         /* copies a layer at a time */
2220         dest_i = 0;
2221         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2222
2223                 /* find the first dest layer with type >= the source type
2224                  * (this should work because layers are ordered by type)
2225                  */
2226                 while(dest_i < dest->totlayer
2227                           && dest->layers[dest_i].type < source->layers[src_i].type)
2228                         ++dest_i;
2229
2230                 /* if there are no more dest layers, we're done */
2231                 if(dest_i >= dest->totlayer) return;
2232
2233                 /* if we found a matching layer, copy the data */
2234                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2235                         int offset = source->layers[src_i].offset;
2236                         char *src_data = (char*)src_block + offset;
2237                         char *dest_data = dest->layers[dest_i].data;
2238
2239                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2240                         dest_offset = dest_index * typeInfo->size;
2241
2242                         if(typeInfo->copy)
2243                                 typeInfo->copy(src_data, dest_data + dest_offset, 1);
2244                         else
2245                                 memcpy(dest_data + dest_offset, src_data, typeInfo->size);
2246
2247                         /* if there are multiple source & dest layers of the same type,
2248                          * we don't want to copy all source layers to the same dest, so
2249                          * increment dest_i
2250                          */
2251                         ++dest_i;
2252                 }
2253         }
2254
2255 }
2256
2257 void CustomData_file_write_info(int type, const char **structname, int *structnum)
2258 {
2259         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2260
2261         *structname = typeInfo->structname;
2262         *structnum = typeInfo->structnum;
2263 }
2264
2265 int CustomData_sizeof(int type)
2266 {
2267         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2268
2269         return typeInfo->size;
2270 }
2271
2272 const char *CustomData_layertype_name(int type)
2273 {
2274         return layerType_getName(type);
2275 }
2276
2277 static int  CustomData_is_property_layer(int type)
2278 {
2279         if((type == CD_PROP_FLT) || (type == CD_PROP_INT) || (type == CD_PROP_STR))
2280                 return 1;
2281         return 0;
2282 }
2283
2284 static int cd_layer_find_dupe(CustomData *data, const char *name, int type, int index)
2285 {
2286         int i;
2287         /* see if there is a duplicate */
2288         for(i=0; i<data->totlayer; i++) {
2289                 if(i != index) {
2290                         CustomDataLayer *layer= &data->layers[i];
2291                         
2292                         if(CustomData_is_property_layer(type)) {
2293                                 if(CustomData_is_property_layer(layer->type) && strcmp(layer->name, name)==0) {
2294                                         return 1;
2295                                 }
2296                         }
2297                         else{
2298                                 if(i!=index && layer->type==type && strcmp(layer->name, name)==0) {
2299                                         return 1;
2300                                 }
2301                         }
2302                 }
2303         }
2304         
2305         return 0;
2306 }
2307
2308 static int customdata_unique_check(void *arg, const char *name)
2309 {
2310         struct {CustomData *data; int type; int index;} *data_arg= arg;
2311         return cd_layer_find_dupe(data_arg->data, name, data_arg->type, data_arg->index);
2312 }
2313
2314 void CustomData_set_layer_unique_name(CustomData *data, int index)
2315 {       
2316         CustomDataLayer *nlayer= &data->layers[index];
2317         const LayerTypeInfo *typeInfo= layerType_getInfo(nlayer->type);
2318
2319         struct {CustomData *data; int type; int index;} data_arg;
2320         data_arg.data= data;
2321         data_arg.type= nlayer->type;
2322         data_arg.index= index;
2323
2324         if (!typeInfo->defaultname)
2325                 return;
2326         
2327         BLI_uniquename_cb(customdata_unique_check, &data_arg, typeInfo->defaultname, '.', nlayer->name, sizeof(nlayer->name));
2328 }
2329
2330 int CustomData_verify_versions(struct CustomData *data, int index)
2331 {
2332         const LayerTypeInfo *typeInfo;
2333         CustomDataLayer *layer = &data->layers[index];
2334         int i, keeplayer = 1;
2335
2336         if (layer->type >= CD_NUMTYPES) {
2337                 keeplayer = 0; /* unknown layer type from future version */
2338         }
2339         else {
2340                 typeInfo = layerType_getInfo(layer->type);
2341
2342                 if (!typeInfo->defaultname && (index > 0) &&
2343                         data->layers[index-1].type == layer->type)
2344                         keeplayer = 0; /* multiple layers of which we only support one */
2345         }
2346
2347         if (!keeplayer) {
2348                 for (i=index+1; i < data->totlayer; ++i)
2349                         data->layers[i-1] = data->layers[i];
2350                 data->totlayer--;
2351         }
2352
2353         return keeplayer;
2354 }
2355
2356 /****************************** External Files *******************************/
2357
2358 static void customdata_external_filename(char filename[FILE_MAX], ID *id, CustomDataExternal *external)
2359 {
2360         char *path = (id->lib)? id->lib->filepath: G.main->name;
2361
2362         BLI_strncpy(filename, external->filename, FILE_MAX);
2363         BLI_path_abs(filename, path);
2364 }
2365
2366 void CustomData_external_reload(CustomData *data, ID *UNUSED(id), CustomDataMask mask, int totelem)
2367 {
2368         CustomDataLayer *layer;
2369         const LayerTypeInfo *typeInfo;
2370         int i;
2371
2372         for(i=0; i<data->totlayer; i++) {
2373                 layer = &data->layers[i];
2374                 typeInfo = layerType_getInfo(layer->type);
2375
2376                 if(!(mask & (1<<layer->type)));
2377                 else if((layer->flag & CD_FLAG_EXTERNAL) && (layer->flag & CD_FLAG_IN_MEMORY)) {
2378                         if(typeInfo->free)
2379                                 typeInfo->free(layer->data, totelem, typeInfo->size);
2380                         layer->flag &= ~CD_FLAG_IN_MEMORY;
2381                 }
2382         }
2383 }
2384
2385 void CustomData_external_read(CustomData *data, ID *id, CustomDataMask mask, int totelem)
2386 {
2387         CustomDataExternal *external= data->external;
2388         CustomDataLayer *layer;
2389         CDataFile *cdf;
2390         CDataFileLayer *blay;
2391         char filename[FILE_MAX];
2392         const LayerTypeInfo *typeInfo;
2393         int i, update = 0;
2394
2395         if(!external)
2396                 return;
2397         
2398         for(i=0; i<data->totlayer; i++) {
2399                 layer = &data->layers[i];
2400                 typeInfo = layerType_getInfo(layer->type);
2401
2402                 if(!(mask & (1<<layer->type)));
2403                 else if(layer->flag & CD_FLAG_IN_MEMORY);
2404                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read)
2405                         update= 1;
2406         }
2407
2408         if(!update)
2409                 return;
2410
2411         customdata_external_filename(filename, id, external);
2412
2413         cdf= cdf_create(CDF_TYPE_MESH);
2414         if(!cdf_read_open(cdf, filename)) {
2415                 fprintf(stderr, "Failed to read %s layer from %s.\n", layerType_getName(layer->type), filename);
2416                 return;
2417         }
2418
2419         for(i=0; i<data->totlayer; i++) {
2420                 layer = &data->layers[i];
2421                 typeInfo = layerType_getInfo(layer->type);
2422
2423                 if(!(mask & (1<<layer->type)));
2424                 else if(layer->flag & CD_FLAG_IN_MEMORY);
2425                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read) {
2426                         blay= cdf_layer_find(cdf, layer->type, layer->name);
2427
2428                         if(blay) {
2429                                 if(cdf_read_layer(cdf, blay)) {
2430                                         if(typeInfo->read(cdf, layer->data, totelem));
2431                                         else break;
2432                                         layer->flag |= CD_FLAG_IN_MEMORY;
2433                                 }
2434                                 else
2435                                         break;
2436                         }
2437                 }
2438         }
2439
2440         cdf_read_close(cdf);
2441         cdf_free(cdf);
2442 }
2443
2444 void CustomData_external_write(CustomData *data, ID *id, CustomDataMask mask, int totelem, int free)
2445 {
2446         CustomDataExternal *external= data->external;
2447         CustomDataLayer *layer;
2448         CDataFile *cdf;
2449         CDataFileLayer *blay;
2450         const LayerTypeInfo *typeInfo;
2451         int i, update = 0;
2452         char filename[FILE_MAX];
2453
2454         if(!external)
2455                 return;
2456
2457         /* test if there is anything to write */
2458         for(i=0; i<data->totlayer; i++) {
2459                 layer = &data->layers[i];
2460                 typeInfo = layerType_getInfo(layer->type);
2461
2462                 if(!(mask & (1<<layer->type)));
2463                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write)
2464                         update= 1;
2465         }
2466
2467         if(!update)
2468                 return;
2469
2470         /* make sure data is read before we try to write */
2471         CustomData_external_read(data, id, mask, totelem);
2472         customdata_external_filename(filename, id, external);
2473
2474         cdf= cdf_create(CDF_TYPE_MESH);
2475
2476         for(i=0; i<data->totlayer; i++) {
2477                 layer = &data->layers[i];
2478                 typeInfo = layerType_getInfo(layer->type);
2479
2480                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->filesize) {
2481                         if(layer->flag & CD_FLAG_IN_MEMORY) {
2482                                 cdf_layer_add(cdf, layer->type, layer->name,
2483                                         typeInfo->filesize(cdf, layer->data, totelem));
2484                         }
2485                         else {
2486                                 cdf_free(cdf);
2487                                 return; /* read failed for a layer! */
2488                         }
2489                 }
2490         }
2491
2492         if(!cdf_write_open(cdf, filename)) {
2493                 fprintf(stderr, "Failed to open %s for writing.\n", filename);
2494                 return;
2495         }
2496
2497         for(i=0; i<data->totlayer; i++) {
2498                 layer = &data->layers[i];
2499                 typeInfo = layerType_getInfo(layer->type);
2500
2501                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) {
2502                         blay= cdf_layer_find(cdf, layer->type, layer->name);
2503
2504                         if(cdf_write_layer(cdf, blay)) {
2505                                 if(typeInfo->write(cdf, layer->data, totelem));
2506                                 else break;
2507                         }
2508                         else
2509                                 break;
2510                 }
2511         }
2512
2513         if(i != data->totlayer) {
2514                 fprintf(stderr, "Failed to write data to %s.\n", filename);
2515                 cdf_free(cdf);
2516                 return;
2517         }
2518
2519         for(i=0; i<data->totlayer; i++) {
2520                 layer = &data->layers[i];
2521                 typeInfo = layerType_getInfo(layer->type);
2522
2523                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) {
2524                         if(free) {
2525                                 if(typeInfo->free)
2526                                         typeInfo->free(layer->data, totelem, typeInfo->size);
2527                                 layer->flag &= ~CD_FLAG_IN_MEMORY;
2528                         }
2529                 }
2530         }
2531
2532         cdf_write_close(cdf);
2533         cdf_free(cdf);
2534 }
2535
2536 void CustomData_external_add(CustomData *data, ID *UNUSED(id), int type, int UNUSED(totelem), const char *filename)
2537 {
2538         CustomDataExternal *external= data->external;
2539         CustomDataLayer *layer;
2540         int layer_index;
2541
2542         layer_index = CustomData_get_active_layer_index(data, type);
2543         if(layer_index < 0) return;
2544
2545         layer = &data->layers[layer_index];
2546
2547         if(layer->flag & CD_FLAG_EXTERNAL)
2548                 return;
2549
2550         if(!external) {
2551                 external= MEM_callocN(sizeof(CustomDataExternal), "CustomDataExternal");
2552                 data->external= external;
2553         }
2554         BLI_strncpy(external->filename, filename, sizeof(external->filename));
2555
2556         layer->flag |= CD_FLAG_EXTERNAL|CD_FLAG_IN_MEMORY;
2557 }
2558
2559 void CustomData_external_remove(CustomData *data, ID *id, int type, int totelem)
2560 {
2561         CustomDataExternal *external= data->external;
2562         CustomDataLayer *layer;
2563         //char filename[FILE_MAX];
2564         int layer_index; // i, remove_file;
2565
2566         layer_index = CustomData_get_active_layer_index(data, type);
2567         if(layer_index < 0) return;
2568
2569         layer = &data->layers[layer_index];
2570
2571         if(!external)
2572                 return;
2573
2574         if(layer->flag & CD_FLAG_EXTERNAL) {
2575                 if(!(layer->flag & CD_FLAG_IN_MEMORY))
2576                         CustomData_external_read(data, id, (1<<layer->type), totelem);
2577
2578                 layer->flag &= ~CD_FLAG_EXTERNAL;
2579
2580 #if 0
2581                 remove_file= 1;
2582                 for(i=0; i<data->totlayer; i++)
2583                         if(data->layers[i].flag & CD_FLAG_EXTERNAL)
2584                                 remove_file= 0;
2585
2586                 if(remove_file) {
2587                         customdata_external_filename(filename, id, external);
2588                         cdf_remove(filename);
2589                         CustomData_external_free(data);
2590                 }
2591 #endif
2592         }
2593 }
2594
2595 int CustomData_external_test(CustomData *data, int type)
2596 {
2597         CustomDataLayer *layer;
2598         int layer_index;
2599
2600         layer_index = CustomData_get_active_layer_index(data, type);
2601         if(layer_index < 0) return 0;
2602
2603         layer = &data->layers[layer_index];
2604         return (layer->flag & CD_FLAG_EXTERNAL);
2605 }
2606
2607 #if 0
2608 void CustomData_external_remove_object(CustomData *data, ID *id)
2609 {
2610         CustomDataExternal *external= data->external;
2611         char filename[FILE_MAX];
2612
2613         if(!external)
2614                 return;
2615
2616         customdata_external_filename(filename, id, external);
2617         cdf_remove(filename);
2618         CustomData_external_free(data);
2619 }
2620 #endif
2621