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