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