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