svn merge ^/trunk/blender -r40720:40872
[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|TF_CONVERTED, 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 /* note, these numbered comments below are copied from trunk,
1027  * while _most_ match, some at the end need adding and are out of sync */
1028
1029 static const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = {
1030         /* 0: CD_MVERT */
1031         {sizeof(MVert), "MVert", 1, NULL, NULL, NULL, NULL, NULL, NULL},
1032         /* 1: CD_MSTICKY */
1033         {sizeof(MSticky), "MSticky", 1, NULL, NULL, NULL, layerInterp_msticky, NULL,
1034          NULL},
1035         /* 2: CD_MDEFORMVERT */
1036         {sizeof(MDeformVert), "MDeformVert", 1, NULL, layerCopy_mdeformvert,
1037          layerFree_mdeformvert, layerInterp_mdeformvert, NULL, NULL},
1038         /* 3: CD_MEDGE */
1039         {sizeof(MEdge), "MEdge", 1, NULL, NULL, NULL, NULL, NULL, NULL},
1040         /* 4: CD_MFACE */
1041         {sizeof(MFace), "MFace", 1, NULL, NULL, NULL, NULL, NULL, NULL},
1042         /* 5: CD_MTFACE */
1043         {sizeof(MTFace), "MTFace", 1, "UVTex", layerCopy_tface, NULL,
1044          layerInterp_tface, layerSwap_tface, layerDefault_tface},
1045         /* 6: CD_MCOL */
1046         /* 4 MCol structs per face */
1047         {sizeof(MCol)*4, "MCol", 4, "Col", NULL, NULL, layerInterp_mcol,
1048          layerSwap_mcol, layerDefault_mcol},
1049         /* 7: CD_ORIGINDEX */
1050         {sizeof(int), "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
1051         /* 8: CD_NORMAL */
1052         /* 3 floats per normal vector */
1053         {sizeof(float)*3, "vec3f", 1, NULL, NULL, NULL, NULL, NULL, NULL},
1054         /* 9: CD_FLAGS */
1055         {sizeof(int), "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
1056         /* 10: CD_PROP_FLT */
1057         {sizeof(MFloatProperty), "MFloatProperty",1,"Float", layerCopy_propFloat,NULL,NULL,NULL},
1058         /* 11: CD_PROP_INT */
1059         {sizeof(MIntProperty), "MIntProperty",1,"Int",layerCopy_propInt,NULL,NULL,NULL},
1060         /* 12: CD_PROP_STR */
1061         {sizeof(MStringProperty), "MStringProperty",1,"String",layerCopy_propString,NULL,NULL,NULL},
1062         /* 13: CD_ORIGSPACE */
1063         {sizeof(OrigSpaceFace), "OrigSpaceFace", 1, "UVTex", layerCopy_origspace_face, NULL,
1064          layerInterp_origspace_face, layerSwap_origspace_face, layerDefault_origspace_face},
1065         /* 14: CD_ORCO */
1066         {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
1067         /* 15: CD_MTEXPOLY */
1068         {sizeof(MTexPoly), "MTexPoly", 1, "Face Texture", NULL, NULL, NULL, NULL, NULL},
1069         /* 16: CD_MLOOPUV */
1070         {sizeof(MLoopUV), "MLoopUV", 1, "UV coord", NULL, NULL, layerInterp_mloopuv, NULL, NULL,
1071          layerEqual_mloopuv, layerMultiply_mloopuv, layerInitMinMax_mloopuv, 
1072          layerAdd_mloopuv, layerDoMinMax_mloopuv, layerCopyValue_mloopuv},
1073         /* 17: CD_MLOOPCOL */
1074         {sizeof(MLoopCol), "MLoopCol", 1, "Col", NULL, NULL, layerInterp_mloopcol, NULL, 
1075          layerDefault_mloopcol, layerEqual_mloopcol, layerMultiply_mloopcol, layerInitMinMax_mloopcol, 
1076          layerAdd_mloopcol, layerDoMinMax_mloopcol, layerCopyValue_mloopcol},
1077         {sizeof(float)*4*4, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
1078         /* 19: CD_MDISPS */
1079         {sizeof(MDisps), "MDisps", 1, NULL, layerCopy_mdisps,
1080          layerFree_mdisps, layerInterp_mdisps, layerSwap_mdisps, NULL, 
1081          NULL, NULL, NULL, NULL, NULL, NULL, 
1082          layerRead_mdisps, layerWrite_mdisps, layerFilesize_mdisps, layerValidate_mdisps},
1083         /* 20: CD_WEIGHT_MCOL */
1084         {sizeof(MCol)*4, "MCol", 4, "WeightCol", NULL, NULL, layerInterp_mcol,
1085          layerSwap_mcol, layerDefault_mcol},
1086         {sizeof(MPoly), "MPoly", 1, "NGon Face", NULL, NULL, NULL, NULL, NULL},
1087         {sizeof(MLoop), "MLoop", 1, "NGon Face-Vertex", NULL, NULL, NULL, NULL, NULL},
1088         {sizeof(float)*3, "", 0, "ClothOrco", NULL, NULL, layerInterp_shapekey},
1089         /* 21: CD_ID_MCOL */
1090         {sizeof(MCol)*4, "MCol", 4, "IDCol", NULL, NULL, layerInterp_mcol,
1091          layerSwap_mcol, layerDefault_mcol},
1092         {sizeof(MCol)*4, "MCol", 4, "TextureCol", NULL, NULL, layerInterp_mcol,
1093          layerSwap_mcol, layerDefault_mcol},
1094         {sizeof(int), "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
1095         {sizeof(float)*3, "", 0, "ShapeKey", NULL, NULL, layerInterp_shapekey},
1096         {sizeof(float), "", 0, "BevelWeight", NULL, NULL, layerInterp_bweight},
1097         {sizeof(float), "", 0, "SubSurfCrease", NULL, NULL, layerInterp_bweight},
1098         {sizeof(MLoopCol), "MLoopCol", 1, "WeightLoopCol", NULL, NULL, layerInterp_mloopcol, NULL,
1099          layerDefault_mloopcol, layerEqual_mloopcol, layerMultiply_mloopcol, layerInitMinMax_mloopcol,
1100          layerAdd_mloopcol, layerDoMinMax_mloopcol, layerCopyValue_mloopcol},
1101         /* 24: CD_RECAST */
1102         {sizeof(MRecast), "MRecast", 1,"Recast",NULL,NULL,NULL,NULL}
1103 };
1104
1105 /* note, numbers are from trunk and need updating for bmesh */
1106
1107 static const char *LAYERTYPENAMES[CD_NUMTYPES] = {
1108         /*   0-4 */ "CDMVert", "CDMSticky", "CDMDeformVert", "CDMEdge", "CDMFace", "CDMTFace",
1109         /*   5-9 */ "CDMCol", "CDOrigIndex", "CDNormal", "CDFlags","CDMFloatProperty",
1110         /* 10-14 */ "CDMIntProperty","CDMStringProperty", "CDOrigSpace", "CDOrco", "CDMTexPoly", "CDMLoopUV",
1111         /* 15-19 */ "CDMloopCol", "CDTangent", "CDMDisps", "CDWeightMCol", "CDMPoly", 
1112         /* 20-24 */ "CDMLoop", "CDMClothOrco", "CDMLoopCol", "CDIDCol", "CDTextureCol",
1113         /* ?-? */ "CDShapeKeyIndex", "CDShapeKey", "CDBevelWeight", "CDSubSurfCrease", "CDMRecast"
1114 };
1115
1116
1117 const CustomDataMask CD_MASK_BAREMESH =
1118         CD_MASK_MVERT | CD_MASK_MEDGE | CD_MASK_MFACE | CD_MASK_MLOOP | CD_MASK_MPOLY | CD_MASK_BWEIGHT;
1119 const CustomDataMask CD_MASK_MESH =
1120         CD_MASK_MVERT | CD_MASK_MEDGE | CD_MASK_MFACE |
1121         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE | CD_MASK_MCOL |
1122         CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR | CD_MASK_MDISPS |
1123         CD_MASK_MLOOPUV | CD_MASK_MLOOPCOL | CD_MASK_MPOLY | CD_MASK_MLOOP |
1124         CD_MASK_MTEXPOLY | CD_MASK_NORMAL | CD_MASK_MDISPS | CD_MASK_RECAST;
1125 const CustomDataMask CD_MASK_EDITMESH =
1126         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE | CD_MASK_MLOOPUV |
1127         CD_MASK_MLOOPCOL | CD_MASK_MTEXPOLY | CD_MASK_SHAPE_KEYINDEX |
1128         CD_MASK_MCOL|CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR |
1129         CD_MASK_MDISPS | CD_MASK_SHAPEKEY | CD_MASK_RECAST;
1130 const CustomDataMask CD_MASK_DERIVEDMESH =
1131         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE |
1132         CD_MASK_MCOL | CD_MASK_ORIGINDEX | CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_CLOTH_ORCO |
1133         CD_MASK_MLOOPUV | CD_MASK_MLOOPCOL | CD_MASK_MTEXPOLY | CD_MASK_WEIGHT_MLOOPCOL |
1134         CD_MASK_PROP_STR | CD_MASK_ORIGSPACE | CD_MASK_ORCO | CD_MASK_TANGENT | 
1135         CD_MASK_WEIGHT_MCOL | CD_MASK_NORMAL | CD_MASK_SHAPEKEY | CD_MASK_RECAST;
1136 const CustomDataMask CD_MASK_BMESH = CD_MASK_MLOOPUV | CD_MASK_MLOOPCOL | CD_MASK_MTEXPOLY |
1137         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_PROP_FLT | CD_MASK_PROP_INT | 
1138         CD_MASK_PROP_STR | CD_MASK_SHAPEKEY | CD_MASK_SHAPE_KEYINDEX | CD_MASK_MDISPS;
1139 const CustomDataMask CD_MASK_FACECORNERS =
1140         CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_MTEXPOLY | CD_MASK_MLOOPUV |
1141         CD_MASK_MLOOPCOL;
1142
1143 static const LayerTypeInfo *layerType_getInfo(int type)
1144 {
1145         if(type < 0 || type >= CD_NUMTYPES) return NULL;
1146
1147         return &LAYERTYPEINFO[type];
1148 }
1149
1150 static const char *layerType_getName(int type)
1151 {
1152         if(type < 0 || type >= CD_NUMTYPES) return NULL;
1153
1154         return LAYERTYPENAMES[type];
1155 }
1156
1157 /********************* CustomData functions *********************/
1158 static void customData_update_offsets(CustomData *data);
1159
1160 static CustomDataLayer *customData_add_layer__internal(CustomData *data,
1161         int type, int alloctype, void *layerdata, int totelem, const char *name);
1162
1163 void CustomData_update_typemap(CustomData *data)
1164 {
1165         int i, lasttype = -1;
1166
1167         for (i=0; i<CD_NUMTYPES; i++) {
1168                 data->typemap[i] = -1;
1169         }
1170
1171         for (i=0; i<data->totlayer; i++) {
1172                 if (data->layers[i].type != lasttype) {
1173                         data->typemap[data->layers[i].type] = i;
1174                 }
1175                 lasttype = data->layers[i].type;
1176         }
1177 }
1178
1179 void CustomData_merge(const struct CustomData *source, struct CustomData *dest,
1180                                           CustomDataMask mask, int alloctype, int totelem)
1181 {
1182         /*const LayerTypeInfo *typeInfo;*/
1183         CustomDataLayer *layer, *newlayer;
1184         int i, type, number = 0, lasttype = -1, lastactive = 0, lastrender = 0, lastclone = 0, lastmask = 0, lastflag = 0;
1185
1186         for(i = 0; i < source->totlayer; ++i) {
1187                 layer = &source->layers[i];
1188                 /*typeInfo = layerType_getInfo(layer->type);*/ /*UNUSED*/
1189
1190                 type = layer->type;
1191
1192                 if (type != lasttype) {
1193                         number = 0;
1194                         lastactive = layer->active;
1195                         lastrender = layer->active_rnd;
1196                         lastclone = layer->active_clone;
1197                         lastmask = layer->active_mask;
1198                         lasttype = type;
1199                         lastflag = layer->flag;
1200                 }
1201                 else
1202                         number++;
1203
1204                 if(lastflag & CD_FLAG_NOCOPY) continue;
1205                 else if(!((int)mask & (int)(1 << (int)type))) continue;
1206                 else if(number < CustomData_number_of_layers(dest, type)) continue;
1207
1208                 if((alloctype == CD_ASSIGN) && (lastflag & CD_FLAG_NOFREE))
1209                         newlayer = customData_add_layer__internal(dest, type, CD_REFERENCE,
1210                                 layer->data, totelem, layer->name);
1211                 else
1212                         newlayer = customData_add_layer__internal(dest, type, alloctype,
1213                                 layer->data, totelem, layer->name);
1214                 
1215                 if(newlayer) {
1216                         newlayer->uid = layer->uid;
1217                         
1218                         newlayer->active = lastactive;
1219                         newlayer->active_rnd = lastrender;
1220                         newlayer->active_clone = lastclone;
1221                         newlayer->active_mask = lastmask;
1222                         newlayer->flag |= lastflag & (CD_FLAG_EXTERNAL|CD_FLAG_IN_MEMORY);
1223                 }
1224         }
1225
1226         CustomData_update_typemap(dest);
1227 }
1228
1229 void CustomData_copy(const struct CustomData *source, struct CustomData *dest,
1230                                          CustomDataMask mask, int alloctype, int totelem)
1231 {
1232         memset(dest, 0, sizeof(*dest));
1233
1234         if(source->external)
1235                 dest->external= MEM_dupallocN(source->external);
1236
1237         CustomData_merge(source, dest, mask, alloctype, totelem);
1238 }
1239
1240 static void customData_free_layer__internal(CustomDataLayer *layer, int totelem)
1241 {
1242         const LayerTypeInfo *typeInfo;
1243
1244         if(!(layer->flag & CD_FLAG_NOFREE) && layer->data) {
1245                 typeInfo = layerType_getInfo(layer->type);
1246
1247                 if(typeInfo->free)
1248                         typeInfo->free(layer->data, totelem, typeInfo->size);
1249
1250                 if(layer->data)
1251                         MEM_freeN(layer->data);
1252         }
1253 }
1254
1255 static void CustomData_external_free(CustomData *data)
1256 {
1257         if(data->external) {
1258                 MEM_freeN(data->external);
1259                 data->external= NULL;
1260         }
1261 }
1262
1263 void CustomData_free(CustomData *data, int totelem)
1264 {
1265         int i;
1266
1267         for(i = 0; i < data->totlayer; ++i)
1268                 customData_free_layer__internal(&data->layers[i], totelem);
1269
1270         if(data->layers)
1271                 MEM_freeN(data->layers);
1272         
1273         CustomData_external_free(data);
1274         
1275         memset(data, 0, sizeof(*data));
1276 }
1277
1278 static void customData_update_offsets(CustomData *data)
1279 {
1280         const LayerTypeInfo *typeInfo;
1281         int i, offset = 0;
1282
1283         for(i = 0; i < data->totlayer; ++i) {
1284                 typeInfo = layerType_getInfo(data->layers[i].type);
1285
1286                 data->layers[i].offset = offset;
1287                 offset += typeInfo->size;
1288         }
1289
1290         data->totsize = offset;
1291         CustomData_update_typemap(data);
1292 }
1293
1294 int CustomData_get_layer_index(const CustomData *data, int type)
1295 {
1296         int i; 
1297
1298         for(i=0; i < data->totlayer; ++i)
1299                 if(data->layers[i].type == type)
1300                         return i;
1301
1302         return -1;
1303 }
1304
1305 int CustomData_get_layer_index_n(const struct CustomData *data, int type, int n)
1306 {
1307         int i; 
1308
1309         for(i=0; i < data->totlayer; ++i)
1310                 if(data->layers[i].type == type)
1311                         return i + n;
1312
1313         return -1;      
1314 }
1315
1316 int CustomData_get_named_layer_index(const CustomData *data, int type, const char *name)
1317 {
1318         int i;
1319
1320         for(i=0; i < data->totlayer; ++i)
1321                 if(data->layers[i].type == type && strcmp(data->layers[i].name, name)==0)
1322                         return i;
1323
1324         return -1;
1325 }
1326
1327 int CustomData_get_active_layer_index(const CustomData *data, int type)
1328 {
1329         if (!data->totlayer)
1330                 return -1;
1331
1332         if (data->typemap[type] != -1) {
1333                 return data->typemap[type] + data->layers[data->typemap[type]].active;
1334         }
1335
1336         return -1;
1337 }
1338
1339 int CustomData_get_render_layer_index(const CustomData *data, int type)
1340 {
1341         int i;
1342
1343         for(i=0; i < data->totlayer; ++i)
1344                 if(data->layers[i].type == type)
1345                         return i + data->layers[i].active_rnd;
1346
1347         return -1;
1348 }
1349
1350 int CustomData_get_clone_layer_index(const CustomData *data, int type)
1351 {
1352         int i;
1353
1354         for(i=0; i < data->totlayer; ++i)
1355                 if(data->layers[i].type == type)
1356                         return i + data->layers[i].active_clone;
1357
1358         return -1;
1359 }
1360
1361 int CustomData_get_stencil_layer_index(const CustomData *data, int type)
1362 {
1363         int i;
1364
1365         for(i=0; i < data->totlayer; ++i)
1366                 if(data->layers[i].type == type)
1367                         return i + data->layers[i].active_mask;
1368
1369         return -1;
1370 }
1371
1372 int CustomData_get_active_layer(const CustomData *data, int type)
1373 {
1374         int i;
1375
1376         for(i=0; i < data->totlayer; ++i)
1377                 if(data->layers[i].type == type)
1378                         return data->layers[i].active;
1379
1380         return -1;
1381 }
1382
1383 int CustomData_get_render_layer(const CustomData *data, int type)
1384 {
1385         int i;
1386
1387         for(i=0; i < data->totlayer; ++i)
1388                 if(data->layers[i].type == type)
1389                         return data->layers[i].active_rnd;
1390
1391         return -1;
1392 }
1393
1394 int CustomData_get_clone_layer(const CustomData *data, int type)
1395 {
1396         int i;
1397
1398         for(i=0; i < data->totlayer; ++i)
1399                 if(data->layers[i].type == type)
1400                         return data->layers[i].active_clone;
1401
1402         return -1;
1403 }
1404
1405 int CustomData_get_stencil_layer(const CustomData *data, int type)
1406 {
1407         int i;
1408
1409         for(i=0; i < data->totlayer; ++i)
1410                 if(data->layers[i].type == type)
1411                         return data->layers[i].active_mask;
1412
1413         return -1;
1414 }
1415
1416 void CustomData_set_layer_active(CustomData *data, int type, int n)
1417 {
1418         int i;
1419
1420         for(i=0; i < data->totlayer; ++i)
1421                 if(data->layers[i].type == type)
1422                         data->layers[i].active = n;
1423 }
1424
1425 void CustomData_set_layer_render(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_rnd = n;
1432 }
1433
1434 void CustomData_set_layer_clone(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_clone = n;
1441 }
1442
1443 void CustomData_set_layer_stencil(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_mask = n;
1450 }
1451
1452 /* for using with an index from CustomData_get_active_layer_index and CustomData_get_render_layer_index */
1453 void CustomData_set_layer_active_index(CustomData *data, int type, int n)
1454 {
1455         int i;
1456
1457         for(i=0; i < data->totlayer; ++i)
1458                 if(data->layers[i].type == type)
1459                         data->layers[i].active = n-i;
1460 }
1461
1462 void CustomData_set_layer_render_index(CustomData *data, int type, int n)
1463 {
1464         int i;
1465
1466         for(i=0; i < data->totlayer; ++i)
1467                 if(data->layers[i].type == type)
1468                         data->layers[i].active_rnd = n-i;
1469 }
1470
1471 void CustomData_set_layer_clone_index(CustomData *data, int type, int n)
1472 {
1473         int i;
1474
1475         for(i=0; i < data->totlayer; ++i)
1476                 if(data->layers[i].type == type)
1477                         data->layers[i].active_clone = n-i;
1478 }
1479
1480 void CustomData_set_layer_stencil_index(CustomData *data, int type, int n)
1481 {
1482         int i;
1483
1484         for(i=0; i < data->totlayer; ++i)
1485                 if(data->layers[i].type == type)
1486                         data->layers[i].active_mask = n-i;
1487 }
1488
1489 void CustomData_set_layer_flag(struct CustomData *data, int type, int flag)
1490 {
1491         int i;
1492
1493         for(i=0; i < data->totlayer; ++i)
1494                 if(data->layers[i].type == type)
1495                         data->layers[i].flag |= flag;
1496 }
1497
1498 static int customData_resize(CustomData *data, int amount)
1499 {
1500         CustomDataLayer *tmp = MEM_callocN(sizeof(*tmp)*(data->maxlayer + amount),
1501                                                                            "CustomData->layers");
1502         if(!tmp) return 0;
1503
1504         data->maxlayer += amount;
1505         if (data->layers) {
1506                 memcpy(tmp, data->layers, sizeof(*tmp) * data->totlayer);
1507                 MEM_freeN(data->layers);
1508         }
1509         data->layers = tmp;
1510
1511         return 1;
1512 }
1513
1514 static CustomDataLayer *customData_add_layer__internal(CustomData *data,
1515         int type, int alloctype, void *layerdata, int totelem, const char *name)
1516 {
1517         const LayerTypeInfo *typeInfo= layerType_getInfo(type);
1518         int size = typeInfo->size * totelem, flag = 0, index = data->totlayer;
1519         void *newlayerdata;
1520
1521         if (!typeInfo->defaultname && CustomData_has_layer(data, type))
1522                 return &data->layers[CustomData_get_layer_index(data, type)];
1523
1524         if((alloctype == CD_ASSIGN) || (alloctype == CD_REFERENCE)) {
1525                 newlayerdata = layerdata;
1526         }
1527         else {
1528                 newlayerdata = MEM_callocN(size, layerType_getName(type));
1529                 if(!newlayerdata)
1530                         return NULL;
1531         }
1532
1533         if (alloctype == CD_DUPLICATE && layerdata) {
1534                 if(typeInfo->copy)
1535                         typeInfo->copy(layerdata, newlayerdata, totelem);
1536                 else
1537                         memcpy(newlayerdata, layerdata, size);
1538         }
1539         else if (alloctype == CD_DEFAULT) {
1540                 if(typeInfo->set_default)
1541                         typeInfo->set_default((char*)newlayerdata, totelem);
1542         }
1543         else if (alloctype == CD_REFERENCE)
1544                 flag |= CD_FLAG_NOFREE;
1545
1546         if(index >= data->maxlayer) {
1547                 if(!customData_resize(data, CUSTOMDATA_GROW)) {
1548                         if(newlayerdata != layerdata)
1549                                 MEM_freeN(newlayerdata);
1550                         return NULL;
1551                 }
1552         }
1553         
1554         data->totlayer++;
1555
1556         /* keep layers ordered by type */
1557         for( ; index > 0 && data->layers[index - 1].type > type; --index)
1558                 data->layers[index] = data->layers[index - 1];
1559
1560         data->layers[index].type = type;
1561         data->layers[index].flag = flag;
1562         data->layers[index].data = newlayerdata;
1563
1564         if(name || (name=typeInfo->defaultname)) {
1565                 BLI_strncpy(data->layers[index].name, name, 32);
1566                 CustomData_set_layer_unique_name(data, index);
1567         }
1568         else
1569                 data->layers[index].name[0] = '\0';
1570
1571         if(index > 0 && data->layers[index-1].type == type) {
1572                 data->layers[index].active = data->layers[index-1].active;
1573                 data->layers[index].active_rnd = data->layers[index-1].active_rnd;
1574                 data->layers[index].active_clone = data->layers[index-1].active_clone;
1575                 data->layers[index].active_mask = data->layers[index-1].active_mask;
1576         } else {
1577                 data->layers[index].active = 0;
1578                 data->layers[index].active_rnd = 0;
1579                 data->layers[index].active_clone = 0;
1580                 data->layers[index].active_mask = 0;
1581         }
1582         
1583         customData_update_offsets(data);
1584
1585         return &data->layers[index];
1586 }
1587
1588 void *CustomData_add_layer(CustomData *data, int type, int alloctype,
1589                                                    void *layerdata, int totelem)
1590 {
1591         CustomDataLayer *layer;
1592         const LayerTypeInfo *typeInfo= layerType_getInfo(type);
1593         
1594         layer = customData_add_layer__internal(data, type, alloctype, layerdata,
1595                                                                                    totelem, typeInfo->defaultname);
1596         CustomData_update_typemap(data);
1597
1598         if(layer)
1599                 return layer->data;
1600
1601         return NULL;
1602 }
1603
1604 /*same as above but accepts a name*/
1605 void *CustomData_add_layer_named(CustomData *data, int type, int alloctype,
1606                                                    void *layerdata, int totelem, const char *name)
1607 {
1608         CustomDataLayer *layer;
1609         
1610         layer = customData_add_layer__internal(data, type, alloctype, layerdata,
1611                                                                                    totelem, name);
1612         CustomData_update_typemap(data);
1613
1614         if(layer)
1615                 return layer->data;
1616
1617         return NULL;
1618 }
1619
1620
1621 int CustomData_free_layer(CustomData *data, int type, int totelem, int index)
1622 {
1623         int i;
1624         
1625         if (index < 0) return 0;
1626
1627         customData_free_layer__internal(&data->layers[index], totelem);
1628
1629         for (i=index+1; i < data->totlayer; ++i)
1630                 data->layers[i-1] = data->layers[i];
1631
1632         data->totlayer--;
1633
1634         /* if layer was last of type in array, set new active layer */
1635         if ((index >= data->totlayer) || (data->layers[index].type != type)) {
1636                 i = CustomData_get_layer_index(data, type);
1637                 
1638                 if (i >= 0)
1639                         for (; i < data->totlayer && data->layers[i].type == type; i++) {
1640                                 data->layers[i].active--;
1641                                 data->layers[i].active_rnd--;
1642                                 data->layers[i].active_clone--;
1643                                 data->layers[i].active_mask--;
1644                         }
1645         }
1646
1647         if (data->totlayer <= data->maxlayer-CUSTOMDATA_GROW)
1648                 customData_resize(data, -CUSTOMDATA_GROW);
1649
1650         customData_update_offsets(data);
1651         CustomData_update_typemap(data);
1652
1653         return 1;
1654 }
1655
1656 int CustomData_free_layer_active(CustomData *data, int type, int totelem)
1657 {
1658         int index = 0;
1659         index = CustomData_get_active_layer_index(data, type);
1660         if (index < 0) return 0;
1661         return CustomData_free_layer(data, type, totelem, index);
1662 }
1663
1664
1665 void CustomData_free_layers(CustomData *data, int type, int totelem)
1666 {
1667         while (CustomData_has_layer(data, type))
1668                 CustomData_free_layer_active(data, type, totelem);
1669 }
1670
1671 int CustomData_has_layer(const CustomData *data, int type)
1672 {
1673         return (CustomData_get_layer_index(data, type) != -1);
1674 }
1675
1676 int CustomData_number_of_layers(const CustomData *data, int type)
1677 {
1678         int i, number = 0;
1679
1680         for(i = 0; i < data->totlayer; i++)
1681                 if(data->layers[i].type == type)
1682                         number++;
1683         
1684         return number;
1685 }
1686
1687 void *CustomData_duplicate_referenced_layer(struct CustomData *data, int type)
1688 {
1689         CustomDataLayer *layer;
1690         int layer_index;
1691
1692         /* get the layer index of the first layer of type */
1693         layer_index = CustomData_get_active_layer_index(data, type);
1694         if(layer_index < 0) return NULL;
1695
1696         layer = &data->layers[layer_index];
1697
1698         if (layer->flag & CD_FLAG_NOFREE) {
1699                 layer->data = MEM_dupallocN(layer->data);
1700                 layer->flag &= ~CD_FLAG_NOFREE;
1701         }
1702
1703         return layer->data;
1704 }
1705
1706 void *CustomData_duplicate_referenced_layer_named(struct CustomData *data,
1707                                                                                                   int type, const char *name)
1708 {
1709         CustomDataLayer *layer;
1710         int layer_index;
1711
1712         /* get the layer index of the desired layer */
1713         layer_index = CustomData_get_named_layer_index(data, type, name);
1714         if(layer_index < 0) return NULL;
1715
1716         layer = &data->layers[layer_index];
1717
1718         if (layer->flag & CD_FLAG_NOFREE) {
1719                 layer->data = MEM_dupallocN(layer->data);
1720                 layer->flag &= ~CD_FLAG_NOFREE;
1721         }
1722
1723         return layer->data;
1724 }
1725
1726 void CustomData_free_temporary(CustomData *data, int totelem)
1727 {
1728         CustomDataLayer *layer;
1729         int i, j;
1730
1731         for(i = 0, j = 0; i < data->totlayer; ++i) {
1732                 layer = &data->layers[i];
1733
1734                 if (i != j)
1735                         data->layers[j] = data->layers[i];
1736
1737                 if ((layer->flag & CD_FLAG_TEMPORARY) == CD_FLAG_TEMPORARY)
1738                         customData_free_layer__internal(layer, totelem);
1739                 else
1740                         j++;
1741         }
1742
1743         data->totlayer = j;
1744
1745         if(data->totlayer <= data->maxlayer-CUSTOMDATA_GROW)
1746                 customData_resize(data, -CUSTOMDATA_GROW);
1747
1748         customData_update_offsets(data);
1749 }
1750
1751 void CustomData_set_only_copy(const struct CustomData *data,
1752                                                           CustomDataMask mask)
1753 {
1754         int i;
1755
1756         for(i = 0; i < data->totlayer; ++i)
1757                 if(!((int)mask & (int)(1 << (int)data->layers[i].type)))
1758                         data->layers[i].flag |= CD_FLAG_NOCOPY;
1759 }
1760
1761 void CustomData_copy_elements(int type, void *source, void *dest, int count)
1762 {
1763         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1764
1765         if (typeInfo->copy)
1766                 typeInfo->copy(source, dest, count);
1767         else
1768                 memcpy(dest, source, typeInfo->size*count);
1769 }
1770
1771 void CustomData_copy_data(const CustomData *source, CustomData *dest,
1772                                                   int source_index, int dest_index, int count)
1773 {
1774         const LayerTypeInfo *typeInfo;
1775         int src_i, dest_i;
1776         int src_offset;
1777         int dest_offset;
1778
1779         /* copies a layer at a time */
1780         dest_i = 0;
1781         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1782
1783                 /* find the first dest layer with type >= the source type
1784                  * (this should work because layers are ordered by type)
1785                  */
1786                 while(dest_i < dest->totlayer
1787                           && dest->layers[dest_i].type < source->layers[src_i].type)
1788                         ++dest_i;
1789
1790                 /* if there are no more dest layers, we're done */
1791                 if(dest_i >= dest->totlayer) return;
1792
1793                 /* if we found a matching layer, copy the data */
1794                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1795                         char *src_data = source->layers[src_i].data;
1796                         char *dest_data = dest->layers[dest_i].data;
1797
1798                         typeInfo = layerType_getInfo(source->layers[src_i].type);
1799
1800                         src_offset = source_index * typeInfo->size;
1801                         dest_offset = dest_index * typeInfo->size;
1802                         
1803                         if (!src_data || !dest_data) {
1804                                 printf("eek! null data in CustomData_copy_data!\n");
1805                                 continue;
1806                         }
1807                         
1808                         if(typeInfo->copy)
1809                                 typeInfo->copy(src_data + src_offset,
1810                                                                 dest_data + dest_offset,
1811                                                                 count);
1812                         else
1813                                 memcpy(dest_data + dest_offset,
1814                                            src_data + src_offset,
1815                                            count * typeInfo->size);
1816
1817                         /* if there are multiple source & dest layers of the same type,
1818                          * we don't want to copy all source layers to the same dest, so
1819                          * increment dest_i
1820                          */
1821                         ++dest_i;
1822                 }
1823         }
1824 }
1825
1826 void CustomData_free_elem(CustomData *data, int index, int count)
1827 {
1828         int i;
1829         const LayerTypeInfo *typeInfo;
1830
1831         for(i = 0; i < data->totlayer; ++i) {
1832                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
1833                         typeInfo = layerType_getInfo(data->layers[i].type);
1834
1835                         if(typeInfo->free) {
1836                                 int offset = typeInfo->size * index;
1837
1838                                 typeInfo->free((char *)data->layers[i].data + offset,
1839                                                            count, typeInfo->size);
1840                         }
1841                 }
1842         }
1843 }
1844
1845 #define SOURCE_BUF_SIZE 100
1846
1847 void CustomData_interp(const CustomData *source, CustomData *dest,
1848                                            int *src_indices, float *weights, float *sub_weights,
1849                                            int count, int dest_index)
1850 {
1851         int src_i, dest_i;
1852         int dest_offset;
1853         int j;
1854         void *source_buf[SOURCE_BUF_SIZE];
1855         void **sources = source_buf;
1856
1857         /* slow fallback in case we're interpolating a ridiculous number of
1858          * elements
1859          */
1860         if(count > SOURCE_BUF_SIZE)
1861                 sources = MEM_callocN(sizeof(*sources) * count,
1862                                                           "CustomData_interp sources");
1863
1864         /* interpolates a layer at a time */
1865         dest_i = 0;
1866         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1867                 const LayerTypeInfo *typeInfo= layerType_getInfo(source->layers[src_i].type);
1868                 if(!typeInfo->interp) continue;
1869
1870                 /* find the first dest layer with type >= the source type
1871                  * (this should work because layers are ordered by type)
1872                  */
1873                 while(dest_i < dest->totlayer
1874                           && dest->layers[dest_i].type < source->layers[src_i].type)
1875                         ++dest_i;
1876
1877                 /* if there are no more dest layers, we're done */
1878                 if(dest_i >= dest->totlayer) return;
1879
1880                 /* if we found a matching layer, copy the data */
1881                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1882                         void *src_data = source->layers[src_i].data;
1883
1884                         for(j = 0; j < count; ++j)
1885                                 sources[j] = (char *)src_data
1886                                                          + typeInfo->size * src_indices[j];
1887
1888                         dest_offset = dest_index * typeInfo->size;
1889
1890                         typeInfo->interp(sources, weights, sub_weights, count,
1891                                                    (char *)dest->layers[dest_i].data + dest_offset);
1892
1893                         /* if there are multiple source & dest layers of the same type,
1894                          * we don't want to copy all source layers to the same dest, so
1895                          * increment dest_i
1896                          */
1897                         ++dest_i;
1898                 }
1899         }
1900
1901         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
1902 }
1903
1904 void CustomData_swap(struct CustomData *data, int index, const int *corner_indices)
1905 {
1906         const LayerTypeInfo *typeInfo;
1907         int i;
1908
1909         for(i = 0; i < data->totlayer; ++i) {
1910                 typeInfo = layerType_getInfo(data->layers[i].type);
1911
1912                 if(typeInfo->swap) {
1913                         int offset = typeInfo->size * index;
1914
1915                         typeInfo->swap((char *)data->layers[i].data + offset, corner_indices);
1916                 }
1917         }
1918 }
1919
1920 void *CustomData_get(const CustomData *data, int index, int type)
1921 {
1922         int offset;
1923         int layer_index;
1924         
1925         /* get the layer index of the active layer of type */
1926         layer_index = CustomData_get_active_layer_index(data, type);
1927         if(layer_index < 0) return NULL;
1928
1929         /* get the offset of the desired element */
1930         offset = layerType_getInfo(type)->size * index;
1931
1932         return (char *)data->layers[layer_index].data + offset;
1933 }
1934
1935 void *CustomData_get_n(const CustomData *data, int type, int index, int n)
1936 {
1937         int layer_index;
1938         int offset;
1939
1940         /* get the layer index of the first layer of type */
1941         layer_index = data->typemap[type];
1942         if(layer_index < 0) return NULL;
1943         
1944         offset = layerType_getInfo(type)->size * index;
1945         return (char *)data->layers[layer_index+n].data + offset;
1946 }
1947
1948 void *CustomData_get_layer(const CustomData *data, int type)
1949 {
1950         /* get the layer index of the active layer of type */
1951         int layer_index = CustomData_get_active_layer_index(data, type);
1952         if(layer_index < 0) return NULL;
1953
1954         return data->layers[layer_index].data;
1955 }
1956
1957 void *CustomData_get_layer_n(const CustomData *data, int type, int n)
1958 {
1959         /* get the layer index of the active layer of type */
1960         int layer_index = CustomData_get_layer_index(data, type);
1961         if(layer_index < 0) return NULL;
1962
1963         return data->layers[layer_index+n].data;
1964 }
1965
1966 void *CustomData_get_layer_named(const struct CustomData *data, int type,
1967                                                                  const char *name)
1968 {
1969         int layer_index = CustomData_get_named_layer_index(data, type, name);
1970         if(layer_index < 0) return NULL;
1971
1972         return data->layers[layer_index].data;
1973 }
1974
1975
1976 int CustomData_set_layer_name(const CustomData *data, int type, int n, const char *name)
1977 {
1978         /* get the layer index of the first layer of type */
1979         int layer_index = CustomData_get_layer_index_n(data, type, n);
1980
1981         if(layer_index < 0) return 0;
1982         if (!name) return 0;
1983         
1984         strcpy(data->layers[layer_index].name, name);
1985         
1986         return 1;
1987 }
1988
1989 void *CustomData_set_layer(const CustomData *data, int type, void *ptr)
1990 {
1991         /* get the layer index of the first layer of type */
1992         int layer_index = CustomData_get_active_layer_index(data, type);
1993
1994         if(layer_index < 0) return NULL;
1995
1996         data->layers[layer_index].data = ptr;
1997
1998         return ptr;
1999 }
2000
2001 void *CustomData_set_layer_n(const struct CustomData *data, int type, int n, void *ptr)
2002 {
2003         /* get the layer index of the first layer of type */
2004         int layer_index = CustomData_get_layer_index(data, type);
2005         if(layer_index < 0) return NULL;
2006
2007         data->layers[layer_index+n].data = ptr;
2008
2009         return ptr;
2010 }
2011
2012 void CustomData_set(const CustomData *data, int index, int type, void *source)
2013 {
2014         void *dest = CustomData_get(data, index, type);
2015         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2016
2017         if(!dest) return;
2018
2019         if(typeInfo->copy)
2020                 typeInfo->copy(source, dest, 1);
2021         else
2022                 memcpy(dest, source, typeInfo->size);
2023 }
2024
2025 /* EditMesh functions */
2026
2027 void CustomData_em_free_block(CustomData *data, void **block)
2028 {
2029         const LayerTypeInfo *typeInfo;
2030         int i;
2031
2032         if(!*block) return;
2033
2034         for(i = 0; i < data->totlayer; ++i) {
2035                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
2036                         typeInfo = layerType_getInfo(data->layers[i].type);
2037
2038                         if(typeInfo->free) {
2039                                 int offset = data->layers[i].offset;
2040                                 typeInfo->free((char*)*block + offset, 1, typeInfo->size);
2041                         }
2042                 }
2043         }
2044
2045         MEM_freeN(*block);
2046         *block = NULL;
2047 }
2048
2049 static void CustomData_em_alloc_block(CustomData *data, void **block)
2050 {
2051         /* TODO: optimize free/alloc */
2052
2053         if (*block)
2054                 CustomData_em_free_block(data, block);
2055
2056         if (data->totsize > 0)
2057                 *block = MEM_callocN(data->totsize, "CustomData EM block");
2058         else
2059                 *block = NULL;
2060 }
2061
2062 void CustomData_em_copy_data(const CustomData *source, CustomData *dest,
2063                                                         void *src_block, void **dest_block)
2064 {
2065         const LayerTypeInfo *typeInfo;
2066         int dest_i, src_i;
2067
2068         if (!*dest_block)
2069                 CustomData_em_alloc_block(dest, dest_block);
2070         
2071         /* copies a layer at a time */
2072         dest_i = 0;
2073         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2074
2075                 /* find the first dest layer with type >= the source type
2076                  * (this should work because layers are ordered by type)
2077                  */
2078                 while(dest_i < dest->totlayer
2079                           && dest->layers[dest_i].type < source->layers[src_i].type)
2080                         ++dest_i;
2081
2082                 /* if there are no more dest layers, we're done */
2083                 if(dest_i >= dest->totlayer) return;
2084
2085                 /* if we found a matching layer, copy the data */
2086                 if(dest->layers[dest_i].type == source->layers[src_i].type &&
2087                         strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
2088                         char *src_data = (char*)src_block + source->layers[src_i].offset;
2089                         char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
2090
2091                         typeInfo = layerType_getInfo(source->layers[src_i].type);
2092
2093                         if(typeInfo->copy)
2094                                 typeInfo->copy(src_data, dest_data, 1);
2095                         else
2096                                 memcpy(dest_data, src_data, typeInfo->size);
2097
2098                         /* if there are multiple source & dest layers of the same type,
2099                          * we don't want to copy all source layers to the same dest, so
2100                          * increment dest_i
2101                          */
2102                         ++dest_i;
2103                 }
2104         }
2105 }
2106
2107 void CustomData_em_validate_data(CustomData *data, void *block, int sub_elements)
2108 {
2109         int i;
2110         for(i = 0; i < data->totlayer; i++) {
2111                 const LayerTypeInfo *typeInfo = layerType_getInfo(data->layers[i].type);
2112                 char *leayer_data = (char*)block + data->layers[i].offset;
2113
2114                 if(typeInfo->validate)
2115                         typeInfo->validate(leayer_data, sub_elements);
2116         }
2117 }
2118
2119 void *CustomData_em_get(const CustomData *data, void *block, int type)
2120 {
2121         int layer_index;
2122         
2123         /* get the layer index of the first layer of type */
2124         layer_index = CustomData_get_active_layer_index(data, type);
2125         if(layer_index < 0) return NULL;
2126
2127         return (char *)block + data->layers[layer_index].offset;
2128 }
2129
2130 void *CustomData_em_get_n(const CustomData *data, void *block, int type, int n)
2131 {
2132         int layer_index;
2133         
2134         /* get the layer index of the first layer of type */
2135         layer_index = CustomData_get_layer_index(data, type);
2136         if(layer_index < 0) return NULL;
2137
2138         return (char *)block + data->layers[layer_index+n].offset;
2139 }
2140
2141 void CustomData_em_set(CustomData *data, void *block, int type, void *source)
2142 {
2143         void *dest = CustomData_em_get(data, block, type);
2144         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2145
2146         if(!dest) return;
2147
2148         if(typeInfo->copy)
2149                 typeInfo->copy(source, dest, 1);
2150         else
2151                 memcpy(dest, source, typeInfo->size);
2152 }
2153
2154 void CustomData_em_set_n(CustomData *data, void *block, int type, int n, void *source)
2155 {
2156         void *dest = CustomData_em_get_n(data, block, type, n);
2157         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2158
2159         if(!dest) return;
2160
2161         if(typeInfo->copy)
2162                 typeInfo->copy(source, dest, 1);
2163         else
2164                 memcpy(dest, source, typeInfo->size);
2165 }
2166
2167 void CustomData_em_interp(CustomData *data, void **src_blocks, float *weights,
2168                                                   float *sub_weights, int count, void *dest_block)
2169 {
2170         int i, j;
2171         void *source_buf[SOURCE_BUF_SIZE];
2172         void **sources = source_buf;
2173
2174         /* slow fallback in case we're interpolating a ridiculous number of
2175          * elements
2176          */
2177         if(count > SOURCE_BUF_SIZE)
2178                 sources = MEM_callocN(sizeof(*sources) * count,
2179                                                           "CustomData_interp sources");
2180
2181         /* interpolates a layer at a time */
2182         for(i = 0; i < data->totlayer; ++i) {
2183                 CustomDataLayer *layer = &data->layers[i];
2184                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
2185
2186                 if(typeInfo->interp) {
2187                         for(j = 0; j < count; ++j)
2188                                 sources[j] = (char *)src_blocks[j] + layer->offset;
2189
2190                         typeInfo->interp(sources, weights, sub_weights, count,
2191                                                           (char *)dest_block + layer->offset);
2192                 }
2193         }
2194
2195         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
2196 }
2197
2198 void CustomData_em_set_default(CustomData *data, void **block)
2199 {
2200         const LayerTypeInfo *typeInfo;
2201         int i;
2202
2203         if (!*block)
2204                 CustomData_em_alloc_block(data, block);
2205
2206         for(i = 0; i < data->totlayer; ++i) {
2207                 int offset = data->layers[i].offset;
2208
2209                 typeInfo = layerType_getInfo(data->layers[i].type);
2210
2211                 if(typeInfo->set_default)
2212                         typeInfo->set_default((char*)*block + offset, 1);
2213         }
2214 }
2215
2216 void CustomData_to_em_block(const CustomData *source, CustomData *dest,
2217                                                         int src_index, void **dest_block)
2218 {
2219         const LayerTypeInfo *typeInfo;
2220         int dest_i, src_i, src_offset;
2221
2222         if (!*dest_block)
2223                 CustomData_em_alloc_block(dest, dest_block);
2224         
2225         /* copies a layer at a time */
2226         dest_i = 0;
2227         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2228
2229                 /* find the first dest layer with type >= the source type
2230                  * (this should work because layers are ordered by type)
2231                  */
2232                 while(dest_i < dest->totlayer
2233                           && dest->layers[dest_i].type < source->layers[src_i].type)
2234                         ++dest_i;
2235
2236                 /* if there are no more dest layers, we're done */
2237                 if(dest_i >= dest->totlayer) return;
2238
2239                 /* if we found a matching layer, copy the data */
2240                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2241                         int offset = dest->layers[dest_i].offset;
2242                         char *src_data = source->layers[src_i].data;
2243                         char *dest_data = (char*)*dest_block + offset;
2244
2245                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2246                         src_offset = src_index * typeInfo->size;
2247
2248                         if(typeInfo->copy)
2249                                 typeInfo->copy(src_data + src_offset, dest_data, 1);
2250                         else
2251                                 memcpy(dest_data, src_data + src_offset, typeInfo->size);
2252
2253                         /* if there are multiple source & dest layers of the same type,
2254                          * we don't want to copy all source layers to the same dest, so
2255                          * increment dest_i
2256                          */
2257                         ++dest_i;
2258                 }
2259         }
2260 }
2261
2262 void CustomData_from_em_block(const CustomData *source, CustomData *dest,
2263                                                           void *src_block, int dest_index)
2264 {
2265         const LayerTypeInfo *typeInfo;
2266         int dest_i, src_i, dest_offset;
2267
2268         /* copies a layer at a time */
2269         dest_i = 0;
2270         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2271
2272                 /* find the first dest layer with type >= the source type
2273                  * (this should work because layers are ordered by type)
2274                  */
2275                 while(dest_i < dest->totlayer
2276                           && dest->layers[dest_i].type < source->layers[src_i].type)
2277                         ++dest_i;
2278
2279                 /* if there are no more dest layers, we're done */
2280                 if(dest_i >= dest->totlayer) return;
2281
2282                 /* if we found a matching layer, copy the data */
2283                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2284                         int offset = source->layers[src_i].offset;
2285                         char *src_data = (char*)src_block + offset;
2286                         char *dest_data = dest->layers[dest_i].data;
2287
2288                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2289                         dest_offset = dest_index * typeInfo->size;
2290
2291                         if(typeInfo->copy)
2292                                 typeInfo->copy(src_data, dest_data + dest_offset, 1);
2293                         else
2294                                 memcpy(dest_data + dest_offset, src_data, typeInfo->size);
2295
2296                         /* if there are multiple source & dest layers of the same type,
2297                          * we don't want to copy all source layers to the same dest, so
2298                          * increment dest_i
2299                          */
2300                         ++dest_i;
2301                 }
2302         }
2303
2304 }
2305
2306 /*Bmesh functions*/
2307 /*needed to convert to/from different face reps*/
2308 void CustomData_to_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata,
2309                              int totloop, int totpoly)
2310 {
2311         int i;
2312         for(i=0; i < fdata->totlayer; i++){
2313                 if(fdata->layers[i].type == CD_MTFACE){
2314                         CustomData_add_layer(pdata, CD_MTEXPOLY, CD_CALLOC, &(fdata->layers[i].name), totpoly);
2315                         CustomData_add_layer(ldata, CD_MLOOPUV, CD_CALLOC, &(fdata->layers[i].name), totloop);
2316                 }
2317                 else if(fdata->layers[i].type == CD_MCOL)
2318                         CustomData_add_layer(ldata, CD_MLOOPCOL, CD_CALLOC, &(fdata->layers[i].name), totloop);
2319                 else if(fdata->layers[i].type == CD_MDISPS) 
2320                         CustomData_add_layer(ldata, CD_MDISPS, CD_CALLOC, &(fdata->layers[i].name), totloop);
2321         }
2322 }
2323 void CustomData_from_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata, int total){
2324         int i;
2325         for(i=0; i < pdata->totlayer; i++){
2326                 if(pdata->layers[i].type == CD_MTEXPOLY)
2327                         CustomData_add_layer_named(fdata, CD_MTFACE, CD_CALLOC, NULL, total, pdata->layers[i].name);
2328         }
2329         for(i=0; i < ldata->totlayer; i++){
2330                 if(ldata->layers[i].type == CD_MLOOPCOL)
2331                         CustomData_add_layer_named(fdata, CD_MCOL, CD_CALLOC, NULL, total, ldata->layers[i].name);
2332                 if (ldata->layers[i].type == CD_WEIGHT_MLOOPCOL)
2333                         CustomData_add_layer_named(fdata, CD_WEIGHT_MCOL, CD_CALLOC, NULL, total, ldata->layers[i].name);
2334         }
2335 }
2336
2337
2338 void CustomData_bmesh_init_pool(CustomData *data, int allocsize){
2339         if(data->totlayer)data->pool = BLI_mempool_create(data->totsize, allocsize, allocsize, 1, 0);
2340 }
2341
2342 void CustomData_bmesh_merge(CustomData *source, CustomData *dest, 
2343                             int mask, int alloctype, BMesh *bm, int type)
2344 {
2345         BMHeader *h;
2346         BMIter iter;
2347         CustomData destold = *dest;
2348         void *tmp;
2349         int t;
2350         
2351         CustomData_merge(source, dest, mask, alloctype, 0);
2352         CustomData_bmesh_init_pool(dest, 512);
2353
2354         switch (type) {
2355                 case BM_VERT:
2356                         t = BM_VERTS_OF_MESH; break;
2357                 case BM_EDGE:
2358                         t = BM_EDGES_OF_MESH; break;
2359                 case BM_LOOP:
2360                         t = BM_LOOPS_OF_FACE; break;
2361                 case BM_FACE:
2362                         t = BM_FACES_OF_MESH; break;
2363                 default: /* should never happen */
2364                         BLI_assert(!"invalid type given");
2365                         t = BM_VERTS_OF_MESH;
2366         }
2367
2368         if (t != BM_LOOPS_OF_FACE) {
2369                 /*ensure all current elements follow new customdata layout*/
2370                 BM_ITER(h, &iter, bm, t, NULL) {
2371                         CustomData_bmesh_copy_data(&destold, dest, h->data, &tmp);
2372                         CustomData_bmesh_free_block(&destold, &h->data);
2373                         h->data = tmp;
2374                 }
2375         } else {
2376                 BMFace *f;
2377                 BMLoop *l;
2378                 BMIter liter;
2379
2380                 /*ensure all current elements follow new customdata layout*/
2381                 BM_ITER(f, &iter, bm, BM_FACES_OF_MESH, NULL) {
2382                         BM_ITER(l, &liter, bm, BM_LOOPS_OF_FACE, f) {
2383                                 CustomData_bmesh_copy_data(&destold, dest, l->head.data, &tmp);
2384                                 CustomData_bmesh_free_block(&destold, &l->head.data);
2385                                 l->head.data = tmp;
2386                         }
2387                 }
2388         }
2389
2390         if (destold.pool) BLI_mempool_destroy(destold.pool);
2391 }
2392
2393 void CustomData_bmesh_free_block(CustomData *data, void **block)
2394 {
2395         const LayerTypeInfo *typeInfo;
2396         int i;
2397
2398         if(!*block) return;
2399         for(i = 0; i < data->totlayer; ++i) {
2400                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
2401                         typeInfo = layerType_getInfo(data->layers[i].type);
2402
2403                         if(typeInfo->free) {
2404                                 int offset = data->layers[i].offset;
2405                                 typeInfo->free((char*)*block + offset, 1, typeInfo->size);
2406                         }
2407                 }
2408         }
2409
2410         if (data->totsize)
2411                 BLI_mempool_free(data->pool, *block);
2412
2413         *block = NULL;
2414 }
2415
2416 static void CustomData_bmesh_alloc_block(CustomData *data, void **block)
2417 {
2418
2419         if (*block)
2420                 CustomData_bmesh_free_block(data, block);
2421
2422         if (data->totsize > 0)
2423                 *block = BLI_mempool_alloc(data->pool);
2424         else
2425                 *block = NULL;
2426 }
2427
2428 void CustomData_bmesh_copy_data(const CustomData *source, CustomData *dest,
2429                                                         void *src_block, void **dest_block)
2430 {
2431         const LayerTypeInfo *typeInfo;
2432         int dest_i, src_i;
2433
2434         if (!*dest_block)
2435                 CustomData_bmesh_alloc_block(dest, dest_block);
2436         
2437         /* copies a layer at a time */
2438         dest_i = 0;
2439         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2440
2441                 /* find the first dest layer with type >= the source type
2442                  * (this should work because layers are ordered by type)
2443                  */
2444                 while(dest_i < dest->totlayer
2445                           && dest->layers[dest_i].type < source->layers[src_i].type)
2446                         ++dest_i;
2447
2448                 /* if there are no more dest layers, we're done */
2449                 if(dest_i >= dest->totlayer) return;
2450
2451                 /* if we found a matching layer, copy the data */
2452                 if(dest->layers[dest_i].type == source->layers[src_i].type &&
2453                         strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
2454                         char *src_data = (char*)src_block + source->layers[src_i].offset;
2455                         char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
2456
2457                         typeInfo = layerType_getInfo(source->layers[src_i].type);
2458
2459                         if(typeInfo->copy)
2460                                 typeInfo->copy(src_data, dest_data, 1);
2461                         else
2462                                 memcpy(dest_data, src_data, typeInfo->size);
2463
2464                         /* if there are multiple source & dest layers of the same type,
2465                          * we don't want to copy all source layers to the same dest, so
2466                          * increment dest_i
2467                          */
2468                         ++dest_i;
2469                 }
2470         }
2471 }
2472
2473 /*Bmesh Custom Data Functions. Should replace editmesh ones with these as well, due to more effecient memory alloc*/
2474 void *CustomData_bmesh_get(const CustomData *data, void *block, int type)
2475 {
2476         int layer_index;
2477         
2478         /* get the layer index of the first layer of type */
2479         layer_index = CustomData_get_active_layer_index(data, type);
2480         if(layer_index < 0) return NULL;
2481
2482         return (char *)block + data->layers[layer_index].offset;
2483 }
2484
2485 void *CustomData_bmesh_get_n(const CustomData *data, void *block, int type, int n)
2486 {
2487         int layer_index;
2488         
2489         /* get the layer index of the first layer of type */
2490         layer_index = CustomData_get_layer_index(data, type);
2491         if(layer_index < 0) return NULL;
2492
2493         return (char *)block + data->layers[layer_index+n].offset;
2494 }
2495
2496 /*gets from the layer at physical index n, note: doesn't check type.*/
2497 void *CustomData_bmesh_get_layer_n(const CustomData *data, void *block, int n)
2498 {
2499         if(n < 0 || n >= data->totlayer) return NULL;
2500
2501         return (char *)block + data->layers[n].offset;
2502 }
2503
2504 int CustomData_layer_has_math(struct CustomData *data, int layern)
2505 {
2506         const LayerTypeInfo *typeInfo = layerType_getInfo(data->layers[layern].type);
2507         
2508         if (typeInfo->equal && typeInfo->add && typeInfo->multiply && 
2509             typeInfo->initminmax && typeInfo->dominmax) return 1;
2510         
2511         return 0;
2512 }
2513
2514 /*copies the "value" (e.g. mloopuv uv or mloopcol colors) from one block to
2515   another, while not overwriting anything else (e.g. flags)*/
2516 void CustomData_data_copy_value(int type, void *source, void *dest)
2517 {
2518         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2519
2520         if(!dest) return;
2521
2522         if(typeInfo->copyvalue)
2523                 typeInfo->copyvalue(source, dest);
2524         else
2525                 memcpy(dest, source, typeInfo->size);
2526 }
2527
2528 int CustomData_data_equals(int type, void *data1, void *data2)
2529 {
2530         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2531
2532         if (typeInfo->equal)
2533                 return typeInfo->equal(data1, data2);
2534         else return !memcmp(data1, data2, typeInfo->size);
2535 }
2536
2537 void CustomData_data_initminmax(int type, void *min, void *max)
2538 {
2539         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2540
2541         if (typeInfo->initminmax)
2542                 typeInfo->initminmax(min, max);
2543 }
2544
2545
2546 void CustomData_data_dominmax(int type, void *data, void *min, void *max)
2547 {
2548         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2549
2550         if (typeInfo->dominmax)
2551                 typeInfo->dominmax(data, min, max);
2552 }
2553
2554
2555 void CustomData_data_multiply(int type, void *data, float fac)
2556 {
2557         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2558
2559         if (typeInfo->multiply)
2560                 typeInfo->multiply(data, fac);
2561 }
2562
2563
2564 void CustomData_data_add(int type, void *data1, void *data2)
2565 {
2566         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2567
2568         if (typeInfo->add)
2569                 typeInfo->add(data1, data2);
2570 }
2571
2572 void CustomData_bmesh_set(const CustomData *data, void *block, int type, void *source)
2573 {
2574         void *dest = CustomData_bmesh_get(data, block, type);
2575         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2576
2577         if(!dest) return;
2578
2579         if(typeInfo->copy)
2580                 typeInfo->copy(source, dest, 1);
2581         else
2582                 memcpy(dest, source, typeInfo->size);
2583 }
2584
2585 void CustomData_bmesh_set_n(CustomData *data, void *block, int type, int n, void *source)
2586 {
2587         void *dest = CustomData_bmesh_get_n(data, block, type, n);
2588         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2589
2590         if(!dest) return;
2591
2592         if(typeInfo->copy)
2593                 typeInfo->copy(source, dest, 1);
2594         else
2595                 memcpy(dest, source, typeInfo->size);
2596 }
2597
2598 void CustomData_bmesh_set_layer_n(CustomData *data, void *block, int n, void *source)
2599 {
2600         void *dest = CustomData_bmesh_get_layer_n(data, block, n);
2601         const LayerTypeInfo *typeInfo = layerType_getInfo(data->layers[n].type);
2602
2603         if(!dest) return;
2604
2605         if(typeInfo->copy)
2606                 typeInfo->copy(source, dest, 1);
2607         else
2608                 memcpy(dest, source, typeInfo->size);
2609 }
2610
2611 void CustomData_bmesh_interp(CustomData *data, void **src_blocks, float *weights,
2612                                                   float *sub_weights, int count, void *dest_block)
2613 {
2614         int i, j;
2615         void *source_buf[SOURCE_BUF_SIZE];
2616         void **sources = source_buf;
2617
2618         /* slow fallback in case we're interpolating a ridiculous number of
2619          * elements
2620          */
2621         if(count > SOURCE_BUF_SIZE)
2622                 sources = MEM_callocN(sizeof(*sources) * count,
2623                                                           "CustomData_interp sources");
2624
2625         /* interpolates a layer at a time */
2626         for(i = 0; i < data->totlayer; ++i) {
2627                 CustomDataLayer *layer = &data->layers[i];
2628                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
2629                 if(typeInfo->interp) {
2630                         for(j = 0; j < count; ++j)
2631                                 sources[j] = (char *)src_blocks[j] + layer->offset;
2632
2633                         typeInfo->interp(sources, weights, sub_weights, count,
2634                                                           (char *)dest_block + layer->offset);
2635                 }
2636         }
2637
2638         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
2639 }
2640
2641 void CustomData_bmesh_set_default(CustomData *data, void **block)
2642 {
2643         const LayerTypeInfo *typeInfo;
2644         int i;
2645
2646         if (!*block)
2647                 CustomData_bmesh_alloc_block(data, block);
2648
2649         for(i = 0; i < data->totlayer; ++i) {
2650                 int offset = data->layers[i].offset;
2651
2652                 typeInfo = layerType_getInfo(data->layers[i].type);
2653
2654                 if(typeInfo->set_default)
2655                         typeInfo->set_default((char*)*block + offset, 1);
2656                 else memset((char*)*block + offset, 0, typeInfo->size);
2657         }
2658 }
2659
2660 void CustomData_to_bmesh_block(const CustomData *source, CustomData *dest,
2661                                                         int src_index, void **dest_block)
2662 {
2663         const LayerTypeInfo *typeInfo;
2664         int dest_i, src_i, src_offset;
2665
2666         if (!*dest_block)
2667                 CustomData_bmesh_alloc_block(dest, dest_block);
2668         
2669         /* copies a layer at a time */
2670         dest_i = 0;
2671         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2672
2673                 /* find the first dest layer with type >= the source type
2674                  * (this should work because layers are ordered by type)
2675                  */
2676                 while(dest_i < dest->totlayer
2677                           && dest->layers[dest_i].type < source->layers[src_i].type)
2678                         ++dest_i;
2679
2680                 /* if there are no more dest layers, we're done */
2681                 if(dest_i >= dest->totlayer) return;
2682
2683                 /* if we found a matching layer, copy the data */
2684                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2685                         int offset = dest->layers[dest_i].offset;
2686                         char *src_data = source->layers[src_i].data;
2687                         char *dest_data = (char*)*dest_block + offset;
2688
2689                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2690                         src_offset = src_index * typeInfo->size;
2691
2692                         if(typeInfo->copy)
2693                                 typeInfo->copy(src_data + src_offset, dest_data, 1);
2694                         else
2695                                 memcpy(dest_data, src_data + src_offset, typeInfo->size);
2696
2697                         /* if there are multiple source & dest layers of the same type,
2698                          * we don't want to copy all source layers to the same dest, so
2699                          * increment dest_i
2700                          */
2701                         ++dest_i;
2702                 }
2703         }
2704 }
2705
2706 void CustomData_from_bmesh_block(const CustomData *source, CustomData *dest,
2707                                                           void *src_block, int dest_index)
2708 {
2709         const LayerTypeInfo *typeInfo;
2710         int dest_i, src_i, dest_offset;
2711
2712         /* copies a layer at a time */
2713         dest_i = 0;
2714         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2715
2716                 /* find the first dest layer with type >= the source type
2717                  * (this should work because layers are ordered by type)
2718                  */
2719                 while(dest_i < dest->totlayer
2720                           && dest->layers[dest_i].type < source->layers[src_i].type)
2721                         ++dest_i;
2722
2723                 /* if there are no more dest layers, we're done */
2724                 if(dest_i >= dest->totlayer) return;
2725
2726                 /* if we found a matching layer, copy the data */
2727                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2728                         int offset = source->layers[src_i].offset;
2729                         char *src_data = (char*)src_block + offset;
2730                         char *dest_data = dest->layers[dest_i].data;
2731
2732                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2733                         dest_offset = dest_index * typeInfo->size;
2734
2735                         if(typeInfo->copy)
2736                                 typeInfo->copy(src_data, dest_data + dest_offset, 1);
2737                         else
2738                                 memcpy(dest_data + dest_offset, src_data, typeInfo->size);
2739
2740                         /* if there are multiple source & dest layers of the same type,
2741                          * we don't want to copy all source layers to the same dest, so
2742                          * increment dest_i
2743                          */
2744                         ++dest_i;
2745                 }
2746         }
2747
2748 }
2749
2750 void CustomData_file_write_info(int type, const char **structname, int *structnum)
2751 {
2752         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2753
2754         *structname = typeInfo->structname;
2755         *structnum = typeInfo->structnum;
2756 }
2757
2758 int CustomData_sizeof(int type)
2759 {
2760         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2761
2762         return typeInfo->size;
2763 }
2764
2765 const char *CustomData_layertype_name(int type)
2766 {
2767         return layerType_getName(type);
2768 }
2769
2770 static int  CustomData_is_property_layer(int type)
2771 {
2772         if((type == CD_PROP_FLT) || (type == CD_PROP_INT) || (type == CD_PROP_STR))
2773                 return 1;
2774         return 0;
2775 }
2776
2777 static int cd_layer_find_dupe(CustomData *data, const char *name, int type, int index)
2778 {
2779         int i;
2780         /* see if there is a duplicate */
2781         for(i=0; i<data->totlayer; i++) {
2782                 if(i != index) {
2783                         CustomDataLayer *layer= &data->layers[i];
2784                         
2785                         if(CustomData_is_property_layer(type)) {
2786                                 if(CustomData_is_property_layer(layer->type) && strcmp(layer->name, name)==0) {
2787                                         return 1;
2788                                 }
2789                         }
2790                         else{
2791                                 if(i!=index && layer->type==type && strcmp(layer->name, name)==0) {
2792                                         return 1;
2793                                 }
2794                         }
2795                 }
2796         }
2797         
2798         return 0;
2799 }
2800
2801 static int customdata_unique_check(void *arg, const char *name)
2802 {
2803         struct {CustomData *data; int type; int index;} *data_arg= arg;
2804         return cd_layer_find_dupe(data_arg->data, name, data_arg->type, data_arg->index);
2805 }
2806
2807 void CustomData_set_layer_unique_name(CustomData *data, int index)
2808 {       
2809         CustomDataLayer *nlayer= &data->layers[index];
2810         const LayerTypeInfo *typeInfo= layerType_getInfo(nlayer->type);
2811
2812         struct {CustomData *data; int type; int index;} data_arg;
2813         data_arg.data= data;
2814         data_arg.type= nlayer->type;
2815         data_arg.index= index;
2816
2817         if (!typeInfo->defaultname)
2818                 return;
2819         
2820         BLI_uniquename_cb(customdata_unique_check, &data_arg, typeInfo->defaultname, '.', nlayer->name, sizeof(nlayer->name));
2821 }
2822
2823 int CustomData_verify_versions(struct CustomData *data, int index)
2824 {
2825         const LayerTypeInfo *typeInfo;
2826         CustomDataLayer *layer = &data->layers[index];
2827         int i, keeplayer = 1;
2828
2829         if (layer->type >= CD_NUMTYPES) {
2830                 keeplayer = 0; /* unknown layer type from future version */
2831         }
2832         else {
2833                 typeInfo = layerType_getInfo(layer->type);
2834
2835                 if (!typeInfo->defaultname && (index > 0) &&
2836                         data->layers[index-1].type == layer->type)
2837                         keeplayer = 0; /* multiple layers of which we only support one */
2838         }
2839
2840         if (!keeplayer) {
2841                 for (i=index+1; i < data->totlayer; ++i)
2842                         data->layers[i-1] = data->layers[i];
2843                 data->totlayer--;
2844         }
2845
2846         return keeplayer;
2847 }
2848
2849 /****************************** External Files *******************************/
2850
2851 static void customdata_external_filename(char filename[FILE_MAX], ID *id, CustomDataExternal *external)
2852 {
2853         BLI_strncpy(filename, external->filename, FILE_MAX);
2854         BLI_path_abs(filename, ID_BLEND_PATH(G.main, id));
2855 }
2856
2857 void CustomData_external_reload(CustomData *data, ID *UNUSED(id), CustomDataMask mask, int totelem)
2858 {
2859         CustomDataLayer *layer;
2860         const LayerTypeInfo *typeInfo;
2861         int i;
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_EXTERNAL) && (layer->flag & CD_FLAG_IN_MEMORY)) {
2869                         if(typeInfo->free)
2870                                 typeInfo->free(layer->data, totelem, typeInfo->size);
2871                         layer->flag &= ~CD_FLAG_IN_MEMORY;
2872                 }
2873         }
2874 }
2875
2876 void CustomData_external_read(CustomData *data, ID *id, CustomDataMask mask, int totelem)
2877 {
2878         CustomDataExternal *external= data->external;
2879         CustomDataLayer *layer;
2880         CDataFile *cdf;
2881         CDataFileLayer *blay;
2882         char filename[FILE_MAX];
2883         const LayerTypeInfo *typeInfo;
2884         int i, update = 0;
2885
2886         if(!external)
2887                 return;
2888         
2889         for(i=0; i<data->totlayer; i++) {
2890                 layer = &data->layers[i];
2891                 typeInfo = layerType_getInfo(layer->type);
2892
2893                 if(!(mask & (1<<layer->type)));
2894                 else if(layer->flag & CD_FLAG_IN_MEMORY);
2895                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read)
2896                         update= 1;
2897         }
2898
2899         if(!update)
2900                 return;
2901
2902         customdata_external_filename(filename, id, external);
2903
2904         cdf= cdf_create(CDF_TYPE_MESH);
2905         if(!cdf_read_open(cdf, filename)) {
2906                 fprintf(stderr, "Failed to read %s layer from %s.\n", layerType_getName(layer->type), filename);
2907                 return;
2908         }
2909
2910         for(i=0; i<data->totlayer; i++) {
2911                 layer = &data->layers[i];
2912                 typeInfo = layerType_getInfo(layer->type);
2913
2914                 if(!(mask & (1<<layer->type)));
2915                 else if(layer->flag & CD_FLAG_IN_MEMORY);
2916                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read) {
2917                         blay= cdf_layer_find(cdf, layer->type, layer->name);
2918
2919                         if(blay) {
2920                                 if(cdf_read_layer(cdf, blay)) {
2921                                         if(typeInfo->read(cdf, layer->data, totelem));
2922                                         else break;
2923                                         layer->flag |= CD_FLAG_IN_MEMORY;
2924                                 }
2925                                 else
2926                                         break;
2927                         }
2928                 }
2929         }
2930
2931         cdf_read_close(cdf);
2932         cdf_free(cdf);
2933 }
2934
2935 void CustomData_external_write(CustomData *data, ID *id, CustomDataMask mask, int totelem, int free)
2936 {
2937         CustomDataExternal *external= data->external;
2938         CustomDataLayer *layer;
2939         CDataFile *cdf;
2940         CDataFileLayer *blay;
2941         const LayerTypeInfo *typeInfo;
2942         int i, update = 0;
2943         char filename[FILE_MAX];
2944
2945         if(!external)
2946                 return;
2947
2948         /* test if there is anything to write */
2949         for(i=0; i<data->totlayer; i++) {
2950                 layer = &data->layers[i];
2951                 typeInfo = layerType_getInfo(layer->type);
2952
2953                 if(!(mask & (1<<layer->type)));
2954                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write)
2955                         update= 1;
2956         }
2957
2958         if(!update)
2959                 return;
2960
2961         /* make sure data is read before we try to write */
2962         CustomData_external_read(data, id, mask, totelem);
2963         customdata_external_filename(filename, id, external);
2964
2965         cdf= cdf_create(CDF_TYPE_MESH);
2966
2967         for(i=0; i<data->totlayer; i++) {
2968                 layer = &data->layers[i];
2969                 typeInfo = layerType_getInfo(layer->type);
2970
2971                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->filesize) {
2972                         if(layer->flag & CD_FLAG_IN_MEMORY) {
2973                                 cdf_layer_add(cdf, layer->type, layer->name,
2974                                         typeInfo->filesize(cdf, layer->data, totelem));
2975                         }
2976                         else {
2977                                 cdf_free(cdf);
2978                                 return; /* read failed for a layer! */
2979                         }
2980                 }
2981         }
2982
2983         if(!cdf_write_open(cdf, filename)) {
2984                 fprintf(stderr, "Failed to open %s for writing.\n", filename);
2985                 return;
2986         }
2987
2988         for(i=0; i<data->totlayer; i++) {
2989                 layer = &data->layers[i];
2990                 typeInfo = layerType_getInfo(layer->type);
2991
2992                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) {
2993                         blay= cdf_layer_find(cdf, layer->type, layer->name);
2994
2995                         if(cdf_write_layer(cdf, blay)) {
2996                                 if(typeInfo->write(cdf, layer->data, totelem));
2997                                 else break;
2998                         }
2999                         else
3000                                 break;
3001                 }
3002         }
3003
3004         if(i != data->totlayer) {
3005                 fprintf(stderr, "Failed to write data to %s.\n", filename);
3006                 cdf_free(cdf);
3007                 return;
3008         }
3009
3010         for(i=0; i<data->totlayer; i++) {
3011                 layer = &data->layers[i];
3012                 typeInfo = layerType_getInfo(layer->type);
3013
3014                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) {
3015                         if(free) {
3016                                 if(typeInfo->free)
3017                                         typeInfo->free(layer->data, totelem, typeInfo->size);
3018                                 layer->flag &= ~CD_FLAG_IN_MEMORY;
3019                         }
3020                 }
3021         }
3022
3023         cdf_write_close(cdf);
3024         cdf_free(cdf);
3025 }
3026
3027 void CustomData_external_add(CustomData *data, ID *UNUSED(id), int type, int UNUSED(totelem), const char *filename)
3028 {
3029         CustomDataExternal *external= data->external;
3030         CustomDataLayer *layer;
3031         int layer_index;
3032
3033         layer_index = CustomData_get_active_layer_index(data, type);
3034         if(layer_index < 0) return;
3035
3036         layer = &data->layers[layer_index];
3037
3038         if(layer->flag & CD_FLAG_EXTERNAL)
3039                 return;
3040
3041         if(!external) {
3042                 external= MEM_callocN(sizeof(CustomDataExternal), "CustomDataExternal");
3043                 data->external= external;
3044         }
3045         BLI_strncpy(external->filename, filename, sizeof(external->filename));
3046
3047         layer->flag |= CD_FLAG_EXTERNAL|CD_FLAG_IN_MEMORY;
3048 }
3049
3050 void CustomData_external_remove(CustomData *data, ID *id, int type, int totelem)
3051 {
3052         CustomDataExternal *external= data->external;
3053         CustomDataLayer *layer;
3054         //char filename[FILE_MAX];
3055         int layer_index; // i, remove_file;
3056
3057         layer_index = CustomData_get_active_layer_index(data, type);
3058         if(layer_index < 0) return;
3059
3060         layer = &data->layers[layer_index];
3061
3062         if(!external)
3063                 return;
3064
3065         if(layer->flag & CD_FLAG_EXTERNAL) {
3066                 if(!(layer->flag & CD_FLAG_IN_MEMORY))
3067                         CustomData_external_read(data, id, (1<<layer->type), totelem);
3068
3069                 layer->flag &= ~CD_FLAG_EXTERNAL;
3070
3071 #if 0
3072                 remove_file= 1;
3073                 for(i=0; i<data->totlayer; i++)
3074                         if(data->layers[i].flag & CD_FLAG_EXTERNAL)
3075                                 remove_file= 0;
3076
3077                 if(remove_file) {
3078                         customdata_external_filename(filename, id, external);
3079                         cdf_remove(filename);
3080                         CustomData_external_free(data);
3081                 }
3082 #endif
3083         }
3084 }
3085
3086 int CustomData_external_test(CustomData *data, int type)
3087 {
3088         CustomDataLayer *layer;
3089         int layer_index;
3090
3091         layer_index = CustomData_get_active_layer_index(data, type);
3092         if(layer_index < 0) return 0;
3093
3094         layer = &data->layers[layer_index];
3095         return (layer->flag & CD_FLAG_EXTERNAL);
3096 }
3097
3098 #if 0
3099 void CustomData_external_remove_object(CustomData *data, ID *id)
3100 {
3101         CustomDataExternal *external= data->external;
3102         char filename[FILE_MAX];
3103
3104         if(!external)
3105                 return;
3106
3107         customdata_external_filename(filename, id, external);
3108         cdf_remove(filename);
3109         CustomData_external_free(data);
3110 }
3111 #endif
3112