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