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