Cleanup: rename BKE_libblock_free_us to BKE_id_free_us.
[blender.git] / source / blender / blenkernel / intern / mesh_convert.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * ***** END GPL LICENSE BLOCK *****
19  */
20
21 /** \file blender/blenkernel/intern/mesh_convert.c
22  *  \ingroup bke
23  */
24
25
26 #include "MEM_guardedalloc.h"
27
28 #include "DNA_scene_types.h"
29 #include "DNA_key_types.h"
30 #include "DNA_material_types.h"
31 #include "DNA_meta_types.h"
32 #include "DNA_object_types.h"
33 #include "DNA_mesh_types.h"
34 #include "DNA_curve_types.h"
35
36 #include "BLI_utildefines.h"
37 #include "BLI_math.h"
38 #include "BLI_listbase.h"
39 #include "BLI_edgehash.h"
40
41 #include "BKE_main.h"
42 #include "BKE_DerivedMesh.h"
43 #include "BKE_global.h"
44 #include "BKE_key.h"
45 #include "BKE_mesh.h"
46 #include "BKE_mesh_runtime.h"
47 #include "BKE_modifier.h"
48 #include "BKE_displist.h"
49 #include "BKE_library.h"
50 #include "BKE_material.h"
51 #include "BKE_mball.h"
52 /* these 2 are only used by conversion functions */
53 #include "BKE_curve.h"
54 /* -- */
55 #include "BKE_object.h"
56
57 #include "DEG_depsgraph.h"
58 #include "DEG_depsgraph_query.h"
59
60 /* Define for cases when you want extra validation of mesh
61  * after certain modifications.
62  */
63 // #undef VALIDATE_MESH
64
65 #ifdef VALIDATE_MESH
66 #  define ASSERT_IS_VALID_MESH(mesh) (BLI_assert((mesh == NULL) || (BKE_mesh_is_valid(mesh) == true)))
67 #else
68 #  define ASSERT_IS_VALID_MESH(mesh)
69 #endif
70
71 void BKE_mesh_from_metaball(ListBase *lb, Mesh *me)
72 {
73         DispList *dl;
74         MVert *mvert;
75         MLoop *mloop, *allloop;
76         MPoly *mpoly;
77         const float *nors, *verts;
78         int a, *index;
79
80         dl = lb->first;
81         if (dl == NULL) return;
82
83         if (dl->type == DL_INDEX4) {
84                 mvert = CustomData_add_layer(&me->vdata, CD_MVERT, CD_CALLOC, NULL, dl->nr);
85                 allloop = mloop = CustomData_add_layer(&me->ldata, CD_MLOOP, CD_CALLOC, NULL, dl->parts * 4);
86                 mpoly = CustomData_add_layer(&me->pdata, CD_MPOLY, CD_CALLOC, NULL, dl->parts);
87                 me->mvert = mvert;
88                 me->mloop = mloop;
89                 me->mpoly = mpoly;
90                 me->totvert = dl->nr;
91                 me->totpoly = dl->parts;
92
93                 a = dl->nr;
94                 nors = dl->nors;
95                 verts = dl->verts;
96                 while (a--) {
97                         copy_v3_v3(mvert->co, verts);
98                         normal_float_to_short_v3(mvert->no, nors);
99                         mvert++;
100                         nors += 3;
101                         verts += 3;
102                 }
103
104                 a = dl->parts;
105                 index = dl->index;
106                 while (a--) {
107                         int count = index[2] != index[3] ? 4 : 3;
108
109                         mloop[0].v = index[0];
110                         mloop[1].v = index[1];
111                         mloop[2].v = index[2];
112                         if (count == 4)
113                                 mloop[3].v = index[3];
114
115                         mpoly->totloop = count;
116                         mpoly->loopstart = (int)(mloop - allloop);
117                         mpoly->flag = ME_SMOOTH;
118
119
120                         mpoly++;
121                         mloop += count;
122                         me->totloop += count;
123                         index += 4;
124                 }
125
126                 BKE_mesh_update_customdata_pointers(me, true);
127
128                 BKE_mesh_calc_normals(me);
129
130                 BKE_mesh_calc_edges(me, true, false);
131         }
132 }
133
134 /**
135  * Specialized function to use when we _know_ existing edges don't overlap with poly edges.
136  */
137 static void make_edges_mdata_extend(
138         MEdge **r_alledge, int *r_totedge,
139         const MPoly *mpoly, MLoop *mloop,
140         const int totpoly)
141 {
142         int totedge = *r_totedge;
143         int totedge_new;
144         EdgeHash *eh;
145         unsigned int eh_reserve;
146         const MPoly *mp;
147         int i;
148
149         eh_reserve = max_ii(totedge, BLI_EDGEHASH_SIZE_GUESS_FROM_POLYS(totpoly));
150         eh = BLI_edgehash_new_ex(__func__, eh_reserve);
151
152         for (i = 0, mp = mpoly; i < totpoly; i++, mp++) {
153                 BKE_mesh_poly_edgehash_insert(eh, mp, mloop + mp->loopstart);
154         }
155
156         totedge_new = BLI_edgehash_len(eh);
157
158 #ifdef DEBUG
159         /* ensure that there's no overlap! */
160         if (totedge_new) {
161                 MEdge *medge = *r_alledge;
162                 for (i = 0; i < totedge; i++, medge++) {
163                         BLI_assert(BLI_edgehash_haskey(eh, medge->v1, medge->v2) == false);
164                 }
165         }
166 #endif
167
168         if (totedge_new) {
169                 EdgeHashIterator *ehi;
170                 MEdge *medge;
171                 unsigned int e_index = totedge;
172
173                 *r_alledge = medge = (*r_alledge ? MEM_reallocN(*r_alledge, sizeof(MEdge) * (totedge + totedge_new)) :
174                                                    MEM_calloc_arrayN(totedge_new, sizeof(MEdge), __func__));
175                 medge += totedge;
176
177                 totedge += totedge_new;
178
179                 /* --- */
180                 for (ehi = BLI_edgehashIterator_new(eh);
181                      BLI_edgehashIterator_isDone(ehi) == false;
182                      BLI_edgehashIterator_step(ehi), ++medge, e_index++)
183                 {
184                         BLI_edgehashIterator_getKey(ehi, &medge->v1, &medge->v2);
185                         BLI_edgehashIterator_setValue(ehi, POINTER_FROM_UINT(e_index));
186
187                         medge->crease = medge->bweight = 0;
188                         medge->flag = ME_EDGEDRAW | ME_EDGERENDER;
189                 }
190                 BLI_edgehashIterator_free(ehi);
191
192                 *r_totedge = totedge;
193
194
195                 for (i = 0, mp = mpoly; i < totpoly; i++, mp++) {
196                         MLoop *l = &mloop[mp->loopstart];
197                         MLoop *l_prev = (l + (mp->totloop - 1));
198                         int j;
199                         for (j = 0; j < mp->totloop; j++, l++) {
200                                 /* lookup hashed edge index */
201                                 l_prev->e = POINTER_AS_UINT(BLI_edgehash_lookup(eh, l_prev->v, l->v));
202                                 l_prev = l;
203                         }
204                 }
205         }
206
207         BLI_edgehash_free(eh, NULL);
208 }
209
210
211 /* Initialize mverts, medges and, faces for converting nurbs to mesh and derived mesh */
212 /* return non-zero on error */
213 int BKE_mesh_nurbs_to_mdata(
214         Object *ob, MVert **r_allvert, int *r_totvert,
215         MEdge **r_alledge, int *r_totedge, MLoop **r_allloop, MPoly **r_allpoly,
216         int *r_totloop, int *r_totpoly)
217 {
218         ListBase disp = {NULL, NULL};
219
220         if (ob->runtime.curve_cache) {
221                 disp = ob->runtime.curve_cache->disp;
222         }
223
224         return BKE_mesh_nurbs_displist_to_mdata(
225                 ob, &disp,
226                 r_allvert, r_totvert,
227                 r_alledge, r_totedge,
228                 r_allloop, r_allpoly, NULL,
229                 r_totloop, r_totpoly);
230 }
231
232 /* BMESH: this doesn't calculate all edges from polygons,
233  * only free standing edges are calculated */
234
235 /* Initialize mverts, medges and, faces for converting nurbs to mesh and derived mesh */
236 /* use specified dispbase */
237 int BKE_mesh_nurbs_displist_to_mdata(
238         Object *ob, const ListBase *dispbase,
239         MVert **r_allvert, int *r_totvert,
240         MEdge **r_alledge, int *r_totedge,
241         MLoop **r_allloop, MPoly **r_allpoly,
242         MLoopUV **r_alluv,
243         int *r_totloop, int *r_totpoly)
244 {
245         Curve *cu = ob->data;
246         DispList *dl;
247         MVert *mvert;
248         MPoly *mpoly;
249         MLoop *mloop;
250         MLoopUV *mloopuv = NULL;
251         MEdge *medge;
252         const float *data;
253         int a, b, ofs, vertcount, startvert, totvert = 0, totedge = 0, totloop = 0, totpoly = 0;
254         int p1, p2, p3, p4, *index;
255         const bool conv_polys = ((CU_DO_2DFILL(cu) == false) ||  /* 2d polys are filled with DL_INDEX3 displists */
256                                  (ob->type == OB_SURF));  /* surf polys are never filled */
257
258         /* count */
259         dl = dispbase->first;
260         while (dl) {
261                 if (dl->type == DL_SEGM) {
262                         totvert += dl->parts * dl->nr;
263                         totedge += dl->parts * (dl->nr - 1);
264                 }
265                 else if (dl->type == DL_POLY) {
266                         if (conv_polys) {
267                                 totvert += dl->parts * dl->nr;
268                                 totedge += dl->parts * dl->nr;
269                         }
270                 }
271                 else if (dl->type == DL_SURF) {
272                         int tot;
273                         totvert += dl->parts * dl->nr;
274                         tot = (dl->parts - 1 + ((dl->flag & DL_CYCL_V) == 2)) * (dl->nr - 1 + (dl->flag & DL_CYCL_U));
275                         totpoly += tot;
276                         totloop += tot * 4;
277                 }
278                 else if (dl->type == DL_INDEX3) {
279                         int tot;
280                         totvert += dl->nr;
281                         tot = dl->parts;
282                         totpoly += tot;
283                         totloop += tot * 3;
284                 }
285                 dl = dl->next;
286         }
287
288         if (totvert == 0) {
289                 /* error("can't convert"); */
290                 /* Make Sure you check ob->data is a curve */
291                 return -1;
292         }
293
294         *r_allvert = mvert = MEM_calloc_arrayN(totvert, sizeof(MVert), "nurbs_init mvert");
295         *r_alledge = medge = MEM_calloc_arrayN(totedge, sizeof(MEdge), "nurbs_init medge");
296         *r_allloop = mloop = MEM_calloc_arrayN(totpoly, 4 * sizeof(MLoop), "nurbs_init mloop"); // totloop
297         *r_allpoly = mpoly = MEM_calloc_arrayN(totpoly, sizeof(MPoly), "nurbs_init mloop");
298
299         if (r_alluv)
300                 *r_alluv = mloopuv = MEM_calloc_arrayN(totpoly, 4 * sizeof(MLoopUV), "nurbs_init mloopuv");
301
302         /* verts and faces */
303         vertcount = 0;
304
305         dl = dispbase->first;
306         while (dl) {
307                 const bool is_smooth = (dl->rt & CU_SMOOTH) != 0;
308
309                 if (dl->type == DL_SEGM) {
310                         startvert = vertcount;
311                         a = dl->parts * dl->nr;
312                         data = dl->verts;
313                         while (a--) {
314                                 copy_v3_v3(mvert->co, data);
315                                 data += 3;
316                                 vertcount++;
317                                 mvert++;
318                         }
319
320                         for (a = 0; a < dl->parts; a++) {
321                                 ofs = a * dl->nr;
322                                 for (b = 1; b < dl->nr; b++) {
323                                         medge->v1 = startvert + ofs + b - 1;
324                                         medge->v2 = startvert + ofs + b;
325                                         medge->flag = ME_LOOSEEDGE | ME_EDGERENDER | ME_EDGEDRAW;
326
327                                         medge++;
328                                 }
329                         }
330
331                 }
332                 else if (dl->type == DL_POLY) {
333                         if (conv_polys) {
334                                 startvert = vertcount;
335                                 a = dl->parts * dl->nr;
336                                 data = dl->verts;
337                                 while (a--) {
338                                         copy_v3_v3(mvert->co, data);
339                                         data += 3;
340                                         vertcount++;
341                                         mvert++;
342                                 }
343
344                                 for (a = 0; a < dl->parts; a++) {
345                                         ofs = a * dl->nr;
346                                         for (b = 0; b < dl->nr; b++) {
347                                                 medge->v1 = startvert + ofs + b;
348                                                 if (b == dl->nr - 1) medge->v2 = startvert + ofs;
349                                                 else medge->v2 = startvert + ofs + b + 1;
350                                                 medge->flag = ME_LOOSEEDGE | ME_EDGERENDER | ME_EDGEDRAW;
351                                                 medge++;
352                                         }
353                                 }
354                         }
355                 }
356                 else if (dl->type == DL_INDEX3) {
357                         startvert = vertcount;
358                         a = dl->nr;
359                         data = dl->verts;
360                         while (a--) {
361                                 copy_v3_v3(mvert->co, data);
362                                 data += 3;
363                                 vertcount++;
364                                 mvert++;
365                         }
366
367                         a = dl->parts;
368                         index = dl->index;
369                         while (a--) {
370                                 mloop[0].v = startvert + index[0];
371                                 mloop[1].v = startvert + index[2];
372                                 mloop[2].v = startvert + index[1];
373                                 mpoly->loopstart = (int)(mloop - (*r_allloop));
374                                 mpoly->totloop = 3;
375                                 mpoly->mat_nr = dl->col;
376
377                                 if (mloopuv) {
378                                         int i;
379
380                                         for (i = 0; i < 3; i++, mloopuv++) {
381                                                 mloopuv->uv[0] = (mloop[i].v - startvert) / (float)(dl->nr - 1);
382                                                 mloopuv->uv[1] = 0.0f;
383                                         }
384                                 }
385
386                                 if (is_smooth) mpoly->flag |= ME_SMOOTH;
387                                 mpoly++;
388                                 mloop += 3;
389                                 index += 3;
390                         }
391                 }
392                 else if (dl->type == DL_SURF) {
393                         startvert = vertcount;
394                         a = dl->parts * dl->nr;
395                         data = dl->verts;
396                         while (a--) {
397                                 copy_v3_v3(mvert->co, data);
398                                 data += 3;
399                                 vertcount++;
400                                 mvert++;
401                         }
402
403                         for (a = 0; a < dl->parts; a++) {
404
405                                 if ( (dl->flag & DL_CYCL_V) == 0 && a == dl->parts - 1) break;
406
407                                 if (dl->flag & DL_CYCL_U) {         /* p2 -> p1 -> */
408                                         p1 = startvert + dl->nr * a;    /* p4 -> p3 -> */
409                                         p2 = p1 + dl->nr - 1;       /* -----> next row */
410                                         p3 = p1 + dl->nr;
411                                         p4 = p2 + dl->nr;
412                                         b = 0;
413                                 }
414                                 else {
415                                         p2 = startvert + dl->nr * a;
416                                         p1 = p2 + 1;
417                                         p4 = p2 + dl->nr;
418                                         p3 = p1 + dl->nr;
419                                         b = 1;
420                                 }
421                                 if ( (dl->flag & DL_CYCL_V) && a == dl->parts - 1) {
422                                         p3 -= dl->parts * dl->nr;
423                                         p4 -= dl->parts * dl->nr;
424                                 }
425
426                                 for (; b < dl->nr; b++) {
427                                         mloop[0].v = p1;
428                                         mloop[1].v = p3;
429                                         mloop[2].v = p4;
430                                         mloop[3].v = p2;
431                                         mpoly->loopstart = (int)(mloop - (*r_allloop));
432                                         mpoly->totloop = 4;
433                                         mpoly->mat_nr = dl->col;
434
435                                         if (mloopuv) {
436                                                 int orco_sizeu = dl->nr - 1;
437                                                 int orco_sizev = dl->parts - 1;
438                                                 int i;
439
440                                                 /* exception as handled in convertblender.c too */
441                                                 if (dl->flag & DL_CYCL_U) {
442                                                         orco_sizeu++;
443                                                         if (dl->flag & DL_CYCL_V)
444                                                                 orco_sizev++;
445                                                 }
446                                                 else if (dl->flag & DL_CYCL_V) {
447                                                         orco_sizev++;
448                                                 }
449
450                                                 for (i = 0; i < 4; i++, mloopuv++) {
451                                                         /* find uv based on vertex index into grid array */
452                                                         int v = mloop[i].v - startvert;
453
454                                                         mloopuv->uv[0] = (v / dl->nr) / (float)orco_sizev;
455                                                         mloopuv->uv[1] = (v % dl->nr) / (float)orco_sizeu;
456
457                                                         /* cyclic correction */
458                                                         if ((i == 1 || i == 2) && mloopuv->uv[0] == 0.0f)
459                                                                 mloopuv->uv[0] = 1.0f;
460                                                         if ((i == 0 || i == 1) && mloopuv->uv[1] == 0.0f)
461                                                                 mloopuv->uv[1] = 1.0f;
462                                                 }
463                                         }
464
465                                         if (is_smooth) mpoly->flag |= ME_SMOOTH;
466                                         mpoly++;
467                                         mloop += 4;
468
469                                         p4 = p3;
470                                         p3++;
471                                         p2 = p1;
472                                         p1++;
473                                 }
474                         }
475                 }
476
477                 dl = dl->next;
478         }
479
480         if (totpoly) {
481                 make_edges_mdata_extend(
482                         r_alledge, &totedge,
483                         *r_allpoly, *r_allloop, totpoly);
484         }
485
486         *r_totpoly = totpoly;
487         *r_totloop = totloop;
488         *r_totedge = totedge;
489         *r_totvert = totvert;
490
491         return 0;
492 }
493
494 Mesh *BKE_mesh_new_nomain_from_curve_displist(Object *ob, ListBase *dispbase)
495 {
496         Curve *cu = ob->data;
497         Mesh *mesh;
498         MVert *allvert;
499         MEdge *alledge;
500         MLoop *allloop;
501         MPoly *allpoly;
502         MLoopUV *alluv = NULL;
503         int totvert, totedge, totloop, totpoly;
504         bool use_orco_uv = (cu->flag & CU_UV_ORCO) != 0;
505
506         if (BKE_mesh_nurbs_displist_to_mdata(
507                 ob, dispbase, &allvert, &totvert, &alledge,
508                 &totedge, &allloop, &allpoly, (use_orco_uv) ? &alluv : NULL,
509                 &totloop, &totpoly) != 0)
510         {
511                 /* Error initializing mdata. This often happens when curve is empty */
512                 return BKE_mesh_new_nomain(0, 0, 0, 0, 0);
513         }
514
515         mesh = BKE_mesh_new_nomain(totvert, totedge, 0, totloop, totpoly);
516         mesh->runtime.cd_dirty_vert |= CD_MASK_NORMAL;
517
518         memcpy(mesh->mvert, allvert, totvert * sizeof(MVert));
519         memcpy(mesh->medge, alledge, totedge * sizeof(MEdge));
520         memcpy(mesh->mloop, allloop, totloop * sizeof(MLoop));
521         memcpy(mesh->mpoly, allpoly, totpoly * sizeof(MPoly));
522
523         if (alluv) {
524                 const char *uvname = "Orco";
525                 CustomData_add_layer_named(&mesh->ldata, CD_MLOOPUV, CD_ASSIGN, alluv, totloop, uvname);
526         }
527
528         MEM_freeN(allvert);
529         MEM_freeN(alledge);
530         MEM_freeN(allloop);
531         MEM_freeN(allpoly);
532
533         return mesh;
534 }
535
536 Mesh *BKE_mesh_new_nomain_from_curve(Object *ob)
537 {
538         ListBase disp = {NULL, NULL};
539
540         if (ob->runtime.curve_cache) {
541                 disp = ob->runtime.curve_cache->disp;
542         }
543
544         return BKE_mesh_new_nomain_from_curve_displist(ob, &disp);
545 }
546
547 /* this may fail replacing ob->data, be sure to check ob->type */
548 void BKE_mesh_from_nurbs_displist(
549         Main *bmain, Object *ob, ListBase *dispbase, const bool use_orco_uv, const char *obdata_name, bool temporary)
550 {
551         Object *ob1;
552         Mesh *me_eval = ob->runtime.mesh_eval;
553         Mesh *me;
554         Curve *cu;
555         MVert *allvert = NULL;
556         MEdge *alledge = NULL;
557         MLoop *allloop = NULL;
558         MLoopUV *alluv = NULL;
559         MPoly *allpoly = NULL;
560         int totvert, totedge, totloop, totpoly;
561
562         cu = ob->data;
563
564         if (me_eval == NULL) {
565                 if (BKE_mesh_nurbs_displist_to_mdata(
566                             ob, dispbase, &allvert, &totvert,
567                             &alledge, &totedge, &allloop,
568                             &allpoly, (use_orco_uv) ? &alluv : NULL,
569                             &totloop, &totpoly) != 0)
570                 {
571                         /* Error initializing */
572                         return;
573                 }
574
575                 /* make mesh */
576                 me = BKE_mesh_add(bmain, obdata_name);
577                 me->totvert = totvert;
578                 me->totedge = totedge;
579                 me->totloop = totloop;
580                 me->totpoly = totpoly;
581
582                 me->mvert = CustomData_add_layer(&me->vdata, CD_MVERT, CD_ASSIGN, allvert, me->totvert);
583                 me->medge = CustomData_add_layer(&me->edata, CD_MEDGE, CD_ASSIGN, alledge, me->totedge);
584                 me->mloop = CustomData_add_layer(&me->ldata, CD_MLOOP, CD_ASSIGN, allloop, me->totloop);
585                 me->mpoly = CustomData_add_layer(&me->pdata, CD_MPOLY, CD_ASSIGN, allpoly, me->totpoly);
586
587                 if (alluv) {
588                         const char *uvname = "Orco";
589                         me->mloopuv = CustomData_add_layer_named(&me->ldata, CD_MLOOPUV, CD_ASSIGN, alluv, me->totloop, uvname);
590                 }
591
592                 BKE_mesh_calc_normals(me);
593         }
594         else {
595                 me = BKE_mesh_add(bmain, obdata_name);
596                 ob->runtime.mesh_eval = NULL;
597                 BKE_mesh_nomain_to_mesh(me_eval, me, ob, CD_MASK_MESH, false);
598         }
599
600         me->totcol = cu->totcol;
601         me->mat = cu->mat;
602
603         /* Copy evaluated texture space from curve to mesh.
604          *
605          * Note that we disable auto texture space feature since that will cause
606          * texture space to evaluate differently for curve and mesh, since curve
607          * uses CV to calculate bounding box, and mesh uses what is coming from
608          * tessellated curve.
609          */
610         me->texflag = cu->texflag & ~CU_AUTOSPACE;
611         copy_v3_v3(me->loc, cu->loc);
612         copy_v3_v3(me->size, cu->size);
613         copy_v3_v3(me->rot, cu->rot);
614         BKE_mesh_texspace_calc(me);
615
616         cu->mat = NULL;
617         cu->totcol = 0;
618
619         /* Do not decrement ob->data usercount here, it's done at end of func with BKE_id_free_us() call. */
620         ob->data = me;
621         ob->type = OB_MESH;
622
623         /* other users */
624         ob1 = bmain->object.first;
625         while (ob1) {
626                 if (ob1->data == cu) {
627                         ob1->type = OB_MESH;
628
629                         id_us_min((ID *)ob1->data);
630                         ob1->data = ob->data;
631                         id_us_plus((ID *)ob1->data);
632                 }
633                 ob1 = ob1->id.next;
634         }
635
636         if (temporary) {
637                 /* For temporary objects in BKE_mesh_new_from_object don't remap
638                  * the entire scene with associated depsgraph updates, which are
639                  * problematic for renderers exporting data. */
640                 id_us_min(&cu->id);
641                 BKE_id_free(bmain, cu);
642         }
643         else {
644                 BKE_id_free_us(bmain, cu);
645         }
646 }
647
648 void BKE_mesh_from_nurbs(Main *bmain, Object *ob)
649 {
650         Curve *cu = (Curve *) ob->data;
651         bool use_orco_uv = (cu->flag & CU_UV_ORCO) != 0;
652         ListBase disp = {NULL, NULL};
653
654         if (ob->runtime.curve_cache) {
655                 disp = ob->runtime.curve_cache->disp;
656         }
657
658         BKE_mesh_from_nurbs_displist(bmain, ob, &disp, use_orco_uv, cu->id.name, false);
659 }
660
661 typedef struct EdgeLink {
662         struct EdgeLink *next, *prev;
663         void *edge;
664 } EdgeLink;
665
666 typedef struct VertLink {
667         Link *next, *prev;
668         unsigned int index;
669 } VertLink;
670
671 static void prependPolyLineVert(ListBase *lb, unsigned int index)
672 {
673         VertLink *vl = MEM_callocN(sizeof(VertLink), "VertLink");
674         vl->index = index;
675         BLI_addhead(lb, vl);
676 }
677
678 static void appendPolyLineVert(ListBase *lb, unsigned int index)
679 {
680         VertLink *vl = MEM_callocN(sizeof(VertLink), "VertLink");
681         vl->index = index;
682         BLI_addtail(lb, vl);
683 }
684
685 void BKE_mesh_to_curve_nurblist(const Mesh *me, ListBase *nurblist, const int edge_users_test)
686 {
687         MVert       *mvert = me->mvert;
688         MEdge *med, *medge = me->medge;
689         MPoly *mp,  *mpoly = me->mpoly;
690         MLoop       *mloop = me->mloop;
691
692         int medge_len = me->totedge;
693         int mpoly_len = me->totpoly;
694         int totedges = 0;
695         int i;
696
697         /* only to detect edge polylines */
698         int *edge_users;
699
700         ListBase edges = {NULL, NULL};
701
702         /* get boundary edges */
703         edge_users = MEM_calloc_arrayN(medge_len, sizeof(int), __func__);
704         for (i = 0, mp = mpoly; i < mpoly_len; i++, mp++) {
705                 MLoop *ml = &mloop[mp->loopstart];
706                 int j;
707                 for (j = 0; j < mp->totloop; j++, ml++) {
708                         edge_users[ml->e]++;
709                 }
710         }
711
712         /* create edges from all faces (so as to find edges not in any faces) */
713         med = medge;
714         for (i = 0; i < medge_len; i++, med++) {
715                 if (edge_users[i] == edge_users_test) {
716                         EdgeLink *edl = MEM_callocN(sizeof(EdgeLink), "EdgeLink");
717                         edl->edge = med;
718
719                         BLI_addtail(&edges, edl);   totedges++;
720                 }
721         }
722         MEM_freeN(edge_users);
723
724         if (edges.first) {
725                 while (edges.first) {
726                         /* each iteration find a polyline and add this as a nurbs poly spline */
727
728                         ListBase polyline = {NULL, NULL}; /* store a list of VertLink's */
729                         bool closed = false;
730                         int totpoly = 0;
731                         MEdge *med_current = ((EdgeLink *)edges.last)->edge;
732                         unsigned int startVert = med_current->v1;
733                         unsigned int endVert = med_current->v2;
734                         bool ok = true;
735
736                         appendPolyLineVert(&polyline, startVert);   totpoly++;
737                         appendPolyLineVert(&polyline, endVert);     totpoly++;
738                         BLI_freelinkN(&edges, edges.last);          totedges--;
739
740                         while (ok) { /* while connected edges are found... */
741                                 EdgeLink *edl = edges.last;
742                                 ok = false;
743                                 while (edl) {
744                                         EdgeLink *edl_prev = edl->prev;
745
746                                         med = edl->edge;
747
748                                         if (med->v1 == endVert) {
749                                                 endVert = med->v2;
750                                                 appendPolyLineVert(&polyline, med->v2); totpoly++;
751                                                 BLI_freelinkN(&edges, edl);             totedges--;
752                                                 ok = true;
753                                         }
754                                         else if (med->v2 == endVert) {
755                                                 endVert = med->v1;
756                                                 appendPolyLineVert(&polyline, endVert); totpoly++;
757                                                 BLI_freelinkN(&edges, edl);             totedges--;
758                                                 ok = true;
759                                         }
760                                         else if (med->v1 == startVert) {
761                                                 startVert = med->v2;
762                                                 prependPolyLineVert(&polyline, startVert);  totpoly++;
763                                                 BLI_freelinkN(&edges, edl);                 totedges--;
764                                                 ok = true;
765                                         }
766                                         else if (med->v2 == startVert) {
767                                                 startVert = med->v1;
768                                                 prependPolyLineVert(&polyline, startVert);  totpoly++;
769                                                 BLI_freelinkN(&edges, edl);                 totedges--;
770                                                 ok = true;
771                                         }
772
773                                         edl = edl_prev;
774                                 }
775                         }
776
777                         /* Now we have a polyline, make into a curve */
778                         if (startVert == endVert) {
779                                 BLI_freelinkN(&polyline, polyline.last);
780                                 totpoly--;
781                                 closed = true;
782                         }
783
784                         /* --- nurbs --- */
785                         {
786                                 Nurb *nu;
787                                 BPoint *bp;
788                                 VertLink *vl;
789
790                                 /* create new 'nurb' within the curve */
791                                 nu = (Nurb *)MEM_callocN(sizeof(Nurb), "MeshNurb");
792
793                                 nu->pntsu = totpoly;
794                                 nu->pntsv = 1;
795                                 nu->orderu = 4;
796                                 nu->flagu = CU_NURB_ENDPOINT | (closed ? CU_NURB_CYCLIC : 0);  /* endpoint */
797                                 nu->resolu = 12;
798
799                                 nu->bp = (BPoint *)MEM_calloc_arrayN(totpoly, sizeof(BPoint), "bpoints");
800
801                                 /* add points */
802                                 vl = polyline.first;
803                                 for (i = 0, bp = nu->bp; i < totpoly; i++, bp++, vl = (VertLink *)vl->next) {
804                                         copy_v3_v3(bp->vec, mvert[vl->index].co);
805                                         bp->f1 = SELECT;
806                                         bp->radius = bp->weight = 1.0;
807                                 }
808                                 BLI_freelistN(&polyline);
809
810                                 /* add nurb to curve */
811                                 BLI_addtail(nurblist, nu);
812                         }
813                         /* --- done with nurbs --- */
814                 }
815         }
816 }
817
818 void BKE_mesh_to_curve(Main *bmain, Depsgraph *depsgraph, Scene *UNUSED(scene), Object *ob)
819 {
820         /* make new mesh data from the original copy */
821         Scene *scene_eval = DEG_get_evaluated_scene(depsgraph);
822         Object *ob_eval = DEG_get_evaluated_object(depsgraph, ob);
823         Mesh *me_eval = mesh_get_eval_final(depsgraph, scene_eval, ob_eval, CD_MASK_MESH);
824         ListBase nurblist = {NULL, NULL};
825
826         BKE_mesh_to_curve_nurblist(me_eval, &nurblist, 0);
827         BKE_mesh_to_curve_nurblist(me_eval, &nurblist, 1);
828
829         if (nurblist.first) {
830                 Curve *cu = BKE_curve_add(bmain, ob->id.name + 2, OB_CURVE);
831                 cu->flag |= CU_3D;
832
833                 cu->nurb = nurblist;
834
835                 id_us_min(&((Mesh *)ob->data)->id);
836                 ob->data = cu;
837                 ob->type = OB_CURVE;
838
839                 BKE_object_free_derived_caches(ob);
840         }
841 }
842
843 /* settings: 1 - preview, 2 - render */
844 Mesh *BKE_mesh_new_from_object(
845         Depsgraph *depsgraph, Main *bmain, Scene *sce, Object *ob,
846         const bool apply_modifiers, const bool calc_undeformed)
847 {
848         Mesh *tmpmesh;
849         Curve *tmpcu = NULL, *copycu;
850         int i;
851         const bool render = (DEG_get_mode(depsgraph) == DAG_EVAL_RENDER);
852         const bool cage = !apply_modifiers;
853         bool do_mat_id_data_us = true;
854
855         /* perform the mesh extraction based on type */
856         switch (ob->type) {
857                 case OB_FONT:
858                 case OB_CURVE:
859                 case OB_SURF:
860                 {
861                         ListBase dispbase = {NULL, NULL};
862                         Mesh *me_eval_final = NULL;
863                         int uv_from_orco;
864
865                         /* copies object and modifiers (but not the data) */
866                         Object *tmpobj;
867                         /* TODO: make it temp copy outside bmain! */
868                         BKE_id_copy_ex(bmain, &ob->id, (ID **)&tmpobj, LIB_ID_COPY_CACHES | LIB_ID_CREATE_NO_DEG_TAG, false);
869                         tmpcu = (Curve *)tmpobj->data;
870
871                         /* Copy cached display list, it might be needed by the stack evaluation.
872                          * Ideally stack should be able to use render-time display list, but doing
873                          * so is quite tricky and not safe so close to the release.
874                          *
875                          * TODO(sergey): Look into more proper solution.
876                          */
877                         if (ob->runtime.curve_cache != NULL) {
878                                 if (tmpobj->runtime.curve_cache == NULL) {
879                                         tmpobj->runtime.curve_cache = MEM_callocN(sizeof(CurveCache), "CurveCache for curve types");
880                                 }
881                                 BKE_displist_copy(&tmpobj->runtime.curve_cache->disp, &ob->runtime.curve_cache->disp);
882                         }
883
884                         /* if getting the original caged mesh, delete object modifiers */
885                         if (cage)
886                                 BKE_object_free_modifiers(tmpobj, 0);
887
888                         /* copies the data */
889                         BKE_id_copy_ex(bmain, ob->data, (ID **)&copycu, LIB_ID_CREATE_NO_DEG_TAG, false);
890                         id_us_min(tmpobj->data);
891                         tmpobj->data = copycu;
892
893                         /* make sure texture space is calculated for a copy of curve,
894                          * it will be used for the final result.
895                          */
896                         BKE_curve_texspace_calc(copycu);
897
898                         /* temporarily set edit so we get updates from edit mode, but
899                          * also because for text datablocks copying it while in edit
900                          * mode gives invalid data structures */
901                         copycu->editfont = tmpcu->editfont;
902                         copycu->editnurb = tmpcu->editnurb;
903
904                         /* get updated display list, and convert to a mesh */
905                         BKE_displist_make_curveTypes_forRender(depsgraph, sce, tmpobj, &dispbase, &me_eval_final, false, render);
906
907                         copycu->editfont = NULL;
908                         copycu->editnurb = NULL;
909
910                         tmpobj->runtime.mesh_eval = me_eval_final;
911
912                         /* convert object type to mesh */
913                         uv_from_orco = (tmpcu->flag & CU_UV_ORCO) != 0;
914                         BKE_mesh_from_nurbs_displist(bmain, tmpobj, &dispbase, uv_from_orco, tmpcu->id.name + 2, true);
915
916                         tmpmesh = tmpobj->data;
917
918                         BKE_displist_free(&dispbase);
919
920                         /* BKE_mesh_from_nurbs changes the type to a mesh, check it worked.
921                          * if it didn't the curve did not have any segments or otherwise
922                          * would have generated an empty mesh */
923                         if (tmpobj->type != OB_MESH) {
924                                 BKE_id_free(bmain, tmpobj);
925                                 return NULL;
926                         }
927
928                         BKE_id_free(bmain, tmpobj);
929
930                         /* XXX The curve to mesh conversion is convoluted... But essentially, BKE_mesh_from_nurbs_displist()
931                          *     already transfers the ownership of materials from the temp copy of the Curve ID to the new
932                          *     Mesh ID, so we do not want to increase materials' usercount later. */
933                         do_mat_id_data_us = false;
934
935                         break;
936                 }
937
938                 case OB_MBALL:
939                 {
940                         /* metaballs don't have modifiers, so just convert to mesh */
941                         Object *basis_ob = BKE_mball_basis_find(sce, ob);
942                         /* todo, re-generatre for render-res */
943                         /* metaball_polygonize(scene, ob) */
944
945                         if (ob != basis_ob)
946                                 return NULL;  /* only do basis metaball */
947
948                         tmpmesh = BKE_mesh_add(bmain, ((ID *)ob->data)->name + 2);
949                         /* BKE_mesh_add gives us a user count we don't need */
950                         id_us_min(&tmpmesh->id);
951
952                         if (render) {
953                                 ListBase disp = {NULL, NULL};
954                                 BKE_displist_make_mball_forRender(depsgraph, sce, ob, &disp);
955                                 BKE_mesh_from_metaball(&disp, tmpmesh);
956                                 BKE_displist_free(&disp);
957                         }
958                         else {
959                                 ListBase disp = {NULL, NULL};
960                                 if (ob->runtime.curve_cache) {
961                                         disp = ob->runtime.curve_cache->disp;
962                                 }
963                                 BKE_mesh_from_metaball(&disp, tmpmesh);
964                         }
965
966                         BKE_mesh_texspace_copy_from_object(tmpmesh, ob);
967
968                         break;
969
970                 }
971                 case OB_MESH:
972                         /* copies object and modifiers (but not the data) */
973                         if (cage) {
974                                 /* copies the data */
975                                 Mesh *mesh = ob->data;
976                                 BKE_id_copy_ex(bmain, &mesh->id, (ID **)&tmpmesh, 0, false);
977                                 /* XXX BKE_mesh_copy() already handles materials usercount. */
978                                 do_mat_id_data_us = false;
979                         }
980                         /* if not getting the original caged mesh, get final derived mesh */
981                         else {
982                                 /* Make a dummy mesh, saves copying */
983                                 Mesh *me_eval;
984                                 /* CustomDataMask mask = CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL; */
985                                 CustomDataMask mask = CD_MASK_MESH; /* this seems more suitable, exporter,
986                                                                      * for example, needs CD_MASK_MDEFORMVERT */
987
988                                 if (calc_undeformed)
989                                         mask |= CD_MASK_ORCO;
990
991                                 if (render) {
992                                         me_eval = mesh_create_eval_final_render(depsgraph, sce, ob, mask);
993                                 }
994                                 else {
995                                         me_eval = mesh_create_eval_final_view(depsgraph, sce, ob, mask);
996                                 }
997
998                                 tmpmesh = BKE_mesh_add(bmain, ((ID *)ob->data)->name + 2);
999                                 BKE_mesh_nomain_to_mesh(me_eval, tmpmesh, ob, mask, true);
1000
1001                                 /* Copy autosmooth settings from original mesh. */
1002                                 Mesh *me = (Mesh *)ob->data;
1003                                 tmpmesh->flag |= (me->flag & ME_AUTOSMOOTH);
1004                                 tmpmesh->smoothresh = me->smoothresh;
1005                         }
1006
1007                         /* BKE_mesh_add/copy gives us a user count we don't need */
1008                         id_us_min(&tmpmesh->id);
1009
1010                         break;
1011                 default:
1012                         /* "Object does not have geometry data") */
1013                         return NULL;
1014         }
1015
1016         /* Copy materials to new mesh */
1017         switch (ob->type) {
1018                 case OB_SURF:
1019                 case OB_FONT:
1020                 case OB_CURVE:
1021                         tmpmesh->totcol = tmpcu->totcol;
1022
1023                         /* free old material list (if it exists) and adjust user counts */
1024                         if (tmpcu->mat) {
1025                                 for (i = tmpcu->totcol; i-- > 0; ) {
1026                                         /* are we an object material or data based? */
1027                                         tmpmesh->mat[i] = give_current_material(ob, i + 1);
1028
1029                                         if (((ob->matbits && ob->matbits[i]) || do_mat_id_data_us)  && tmpmesh->mat[i]) {
1030                                                 id_us_plus(&tmpmesh->mat[i]->id);
1031                                         }
1032                                 }
1033                         }
1034                         break;
1035
1036                 case OB_MBALL:
1037                 {
1038                         MetaBall *tmpmb = (MetaBall *)ob->data;
1039                         tmpmesh->mat = MEM_dupallocN(tmpmb->mat);
1040                         tmpmesh->totcol = tmpmb->totcol;
1041
1042                         /* free old material list (if it exists) and adjust user counts */
1043                         if (tmpmb->mat) {
1044                                 for (i = tmpmb->totcol; i-- > 0; ) {
1045                                         /* are we an object material or data based? */
1046                                         tmpmesh->mat[i] = give_current_material(ob, i + 1);
1047
1048                                         if (((ob->matbits && ob->matbits[i]) || do_mat_id_data_us) && tmpmesh->mat[i]) {
1049                                                 id_us_plus(&tmpmesh->mat[i]->id);
1050                                         }
1051                                 }
1052                         }
1053                         break;
1054                 }
1055
1056                 case OB_MESH:
1057                         if (!cage) {
1058                                 Mesh *origmesh = ob->data;
1059                                 tmpmesh->flag = origmesh->flag;
1060                                 tmpmesh->mat = MEM_dupallocN(origmesh->mat);
1061                                 tmpmesh->totcol = origmesh->totcol;
1062                                 tmpmesh->smoothresh = origmesh->smoothresh;
1063                                 if (origmesh->mat) {
1064                                         for (i = origmesh->totcol; i-- > 0; ) {
1065                                                 /* are we an object material or data based? */
1066                                                 tmpmesh->mat[i] = give_current_material(ob, i + 1);
1067
1068                                                 if (((ob->matbits && ob->matbits[i]) || do_mat_id_data_us)  && tmpmesh->mat[i]) {
1069                                                         id_us_plus(&tmpmesh->mat[i]->id);
1070                                                 }
1071                                         }
1072                                 }
1073                         }
1074                         break;
1075         } /* end copy materials */
1076
1077         return tmpmesh;
1078 }
1079
1080
1081 static void add_shapekey_layers(Mesh *mesh_dest, Mesh *mesh_src)
1082 {
1083         KeyBlock *kb;
1084         Key *key = mesh_src->key;
1085         int i;
1086
1087         if (!mesh_src->key)
1088                 return;
1089
1090         /* ensure we can use mesh vertex count for derived mesh custom data */
1091         if (mesh_src->totvert != mesh_dest->totvert) {
1092                 fprintf(stderr,
1093                         "%s: vertex size mismatch (mesh/dm) '%s' (%d != %d)\n",
1094                         __func__, mesh_src->id.name + 2, mesh_src->totvert, mesh_dest->totvert);
1095                 return;
1096         }
1097
1098         for (i = 0, kb = key->block.first; kb; kb = kb->next, i++) {
1099                 int ci;
1100                 float *array;
1101
1102                 if (mesh_src->totvert != kb->totelem) {
1103                         fprintf(stderr,
1104                                 "%s: vertex size mismatch (Mesh '%s':%d != KeyBlock '%s':%d)\n",
1105                                 __func__, mesh_src->id.name + 2, mesh_src->totvert, kb->name, kb->totelem);
1106                         array = MEM_calloc_arrayN((size_t)mesh_src->totvert, 3 * sizeof(float), __func__);
1107                 }
1108                 else {
1109                         array = MEM_malloc_arrayN((size_t)mesh_src->totvert, 3 * sizeof(float), __func__);
1110                         memcpy(array, kb->data, (size_t)mesh_src->totvert * 3 * sizeof(float));
1111                 }
1112
1113                 CustomData_add_layer_named(&mesh_dest->vdata, CD_SHAPEKEY, CD_ASSIGN, array, mesh_dest->totvert, kb->name);
1114                 ci = CustomData_get_layer_index_n(&mesh_dest->vdata, CD_SHAPEKEY, i);
1115
1116                 mesh_dest->vdata.layers[ci].uid = kb->uid;
1117         }
1118 }
1119
1120
1121 Mesh *BKE_mesh_create_derived_for_modifier(
1122         struct Depsgraph *depsgraph, Scene *scene, Object *ob,
1123         ModifierData *md, int build_shapekey_layers)
1124 {
1125         Mesh *me = ob->data;
1126         const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1127         Mesh *result;
1128         KeyBlock *kb;
1129         ModifierEvalContext mectx = {depsgraph, ob, 0};
1130
1131         if (!(md->mode & eModifierMode_Realtime)) {
1132                 return NULL;
1133         }
1134
1135         if (mti->isDisabled && mti->isDisabled(scene, md, 0)) {
1136                 return NULL;
1137         }
1138
1139         if (build_shapekey_layers && me->key && (kb = BLI_findlink(&me->key->block, ob->shapenr - 1))) {
1140                 BKE_keyblock_convert_to_mesh(kb, me);
1141         }
1142
1143         if (mti->type == eModifierTypeType_OnlyDeform) {
1144                 int numVerts;
1145                 float (*deformedVerts)[3] = BKE_mesh_vertexCos_get(me, &numVerts);
1146
1147                 mti->deformVerts(md, &mectx, NULL, deformedVerts, numVerts);
1148                 BKE_id_copy_ex(
1149                         NULL, &me->id, (ID **)&result,
1150                         LIB_ID_CREATE_NO_MAIN |
1151                         LIB_ID_CREATE_NO_USER_REFCOUNT |
1152                         LIB_ID_CREATE_NO_DEG_TAG |
1153                         LIB_ID_COPY_NO_PREVIEW,
1154                         false);
1155                 BKE_mesh_apply_vert_coords(result, deformedVerts);
1156
1157                 if (build_shapekey_layers)
1158                         add_shapekey_layers(result, me);
1159
1160                 MEM_freeN(deformedVerts);
1161         }
1162         else {
1163                 Mesh *mesh_temp;
1164                 BKE_id_copy_ex(
1165                         NULL, &me->id, (ID **)&mesh_temp,
1166                         LIB_ID_CREATE_NO_MAIN |
1167                         LIB_ID_CREATE_NO_USER_REFCOUNT |
1168                         LIB_ID_CREATE_NO_DEG_TAG |
1169                         LIB_ID_COPY_NO_PREVIEW,
1170                         false);
1171
1172                 if (build_shapekey_layers)
1173                         add_shapekey_layers(mesh_temp, me);
1174
1175                 result = mti->applyModifier(md, &mectx, mesh_temp);
1176                 ASSERT_IS_VALID_MESH(result);
1177
1178                 if (mesh_temp != result) {
1179                         BKE_id_free(NULL, mesh_temp);
1180                 }
1181         }
1182
1183         return result;
1184 }
1185
1186 /* This is a Mesh-based copy of the same function in DerivedMesh.c */
1187 static void shapekey_layers_to_keyblocks(Mesh *mesh_src, Mesh *mesh_dst, int actshape_uid)
1188 {
1189         KeyBlock *kb;
1190         int i, j, tot;
1191
1192         if (!mesh_dst->key)
1193                 return;
1194
1195         tot = CustomData_number_of_layers(&mesh_src->vdata, CD_SHAPEKEY);
1196         for (i = 0; i < tot; i++) {
1197                 CustomDataLayer *layer = &mesh_src->vdata.layers[CustomData_get_layer_index_n(&mesh_src->vdata, CD_SHAPEKEY, i)];
1198                 float (*cos)[3], (*kbcos)[3];
1199
1200                 for (kb = mesh_dst->key->block.first; kb; kb = kb->next) {
1201                         if (kb->uid == layer->uid)
1202                                 break;
1203                 }
1204
1205                 if (!kb) {
1206                         kb = BKE_keyblock_add(mesh_dst->key, layer->name);
1207                         kb->uid = layer->uid;
1208                 }
1209
1210                 if (kb->data)
1211                         MEM_freeN(kb->data);
1212
1213                 cos = CustomData_get_layer_n(&mesh_src->vdata, CD_SHAPEKEY, i);
1214                 kb->totelem = mesh_src->totvert;
1215
1216                 kb->data = kbcos = MEM_malloc_arrayN(kb->totelem, 3 * sizeof(float), __func__);
1217                 if (kb->uid == actshape_uid) {
1218                         MVert *mvert = mesh_src->mvert;
1219
1220                         for (j = 0; j < mesh_src->totvert; j++, kbcos++, mvert++) {
1221                                 copy_v3_v3(*kbcos, mvert->co);
1222                         }
1223                 }
1224                 else {
1225                         for (j = 0; j < kb->totelem; j++, cos++, kbcos++) {
1226                                 copy_v3_v3(*kbcos, *cos);
1227                         }
1228                 }
1229         }
1230
1231         for (kb = mesh_dst->key->block.first; kb; kb = kb->next) {
1232                 if (kb->totelem != mesh_src->totvert) {
1233                         if (kb->data)
1234                                 MEM_freeN(kb->data);
1235
1236                         kb->totelem = mesh_src->totvert;
1237                         kb->data = MEM_calloc_arrayN(kb->totelem, 3 * sizeof(float), __func__);
1238                         fprintf(stderr, "%s: lost a shapekey layer: '%s'! (bmesh internal error)\n", __func__, kb->name);
1239                 }
1240         }
1241 }
1242
1243
1244 /* This is a Mesh-based copy of DM_to_mesh() */
1245 void BKE_mesh_nomain_to_mesh(Mesh *mesh_src, Mesh *mesh_dst, Object *ob, CustomDataMask mask, bool take_ownership)
1246 {
1247         /* mesh_src might depend on mesh_dst, so we need to do everything with a local copy */
1248         /* TODO(Sybren): the above claim came from DM_to_mesh(); check whether it is still true with Mesh */
1249         Mesh tmp = *mesh_dst;
1250         int totvert, totedge /*, totface */ /* UNUSED */, totloop, totpoly;
1251         int did_shapekeys = 0;
1252         eCDAllocType alloctype = CD_DUPLICATE;
1253
1254         if (take_ownership /* && dm->type == DM_TYPE_CDDM && dm->needsFree */) {
1255                 bool has_any_referenced_layers =
1256                         CustomData_has_referenced(&mesh_src->vdata) ||
1257                         CustomData_has_referenced(&mesh_src->edata) ||
1258                         CustomData_has_referenced(&mesh_src->ldata) ||
1259                         CustomData_has_referenced(&mesh_src->fdata) ||
1260                         CustomData_has_referenced(&mesh_src->pdata);
1261                 if (!has_any_referenced_layers) {
1262                         alloctype = CD_ASSIGN;
1263                 }
1264         }
1265         CustomData_reset(&tmp.vdata);
1266         CustomData_reset(&tmp.edata);
1267         CustomData_reset(&tmp.fdata);
1268         CustomData_reset(&tmp.ldata);
1269         CustomData_reset(&tmp.pdata);
1270
1271         BKE_mesh_ensure_normals(mesh_src);
1272
1273         totvert = tmp.totvert = mesh_src->totvert;
1274         totedge = tmp.totedge = mesh_src->totedge;
1275         totloop = tmp.totloop = mesh_src->totloop;
1276         totpoly = tmp.totpoly = mesh_src->totpoly;
1277         tmp.totface = 0;
1278
1279         CustomData_copy(&mesh_src->vdata, &tmp.vdata, mask, alloctype, totvert);
1280         CustomData_copy(&mesh_src->edata, &tmp.edata, mask, alloctype, totedge);
1281         CustomData_copy(&mesh_src->ldata, &tmp.ldata, mask, alloctype, totloop);
1282         CustomData_copy(&mesh_src->pdata, &tmp.pdata, mask, alloctype, totpoly);
1283         tmp.cd_flag = mesh_src->cd_flag;
1284         tmp.runtime.deformed_only = mesh_src->runtime.deformed_only;
1285
1286         if (CustomData_has_layer(&mesh_src->vdata, CD_SHAPEKEY)) {
1287                 KeyBlock *kb;
1288                 int uid;
1289
1290                 if (ob) {
1291                         kb = BLI_findlink(&mesh_dst->key->block, ob->shapenr - 1);
1292                         if (kb) {
1293                                 uid = kb->uid;
1294                         }
1295                         else {
1296                                 printf("%s: error - could not find active shapekey %d!\n",
1297                                        __func__, ob->shapenr - 1);
1298
1299                                 uid = INT_MAX;
1300                         }
1301                 }
1302                 else {
1303                         /* if no object, set to INT_MAX so we don't mess up any shapekey layers */
1304                         uid = INT_MAX;
1305                 }
1306
1307                 shapekey_layers_to_keyblocks(mesh_src, mesh_dst, uid);
1308                 did_shapekeys = 1;
1309         }
1310
1311         /* copy texture space */
1312         if (ob) {
1313                 BKE_mesh_texspace_copy_from_object(&tmp, ob);
1314         }
1315
1316         /* not all DerivedMeshes store their verts/edges/faces in CustomData, so
1317          * we set them here in case they are missing */
1318         /* TODO(Sybren): we could probably replace CD_ASSIGN with alloctype and always directly pass mesh_src->mxxx,
1319          * instead of using a ternary operator. */
1320         if (!CustomData_has_layer(&tmp.vdata, CD_MVERT)) {
1321                 CustomData_add_layer(
1322                         &tmp.vdata, CD_MVERT, CD_ASSIGN,
1323                         (alloctype == CD_ASSIGN) ? mesh_src->mvert : MEM_dupallocN(mesh_src->mvert),
1324                         totvert);
1325         }
1326         if (!CustomData_has_layer(&tmp.edata, CD_MEDGE)) {
1327                 CustomData_add_layer(
1328                         &tmp.edata, CD_MEDGE, CD_ASSIGN,
1329                         (alloctype == CD_ASSIGN) ? mesh_src->medge : MEM_dupallocN(mesh_src->medge),
1330                         totedge);
1331         }
1332         if (!CustomData_has_layer(&tmp.pdata, CD_MPOLY)) {
1333                 /* TODO(Sybren): assignment to tmp.mxxx is probably not necessary due to the
1334                  * BKE_mesh_update_customdata_pointers() call below. */
1335                 tmp.mloop = (alloctype == CD_ASSIGN) ? mesh_src->mloop : MEM_dupallocN(mesh_src->mloop);
1336                 tmp.mpoly = (alloctype == CD_ASSIGN) ? mesh_src->mpoly : MEM_dupallocN(mesh_src->mpoly);
1337
1338                 CustomData_add_layer(&tmp.ldata, CD_MLOOP, CD_ASSIGN, tmp.mloop, tmp.totloop);
1339                 CustomData_add_layer(&tmp.pdata, CD_MPOLY, CD_ASSIGN, tmp.mpoly, tmp.totpoly);
1340         }
1341
1342         /* object had got displacement layer, should copy this layer to save sculpted data */
1343         /* NOTE: maybe some other layers should be copied? nazgul */
1344         if (CustomData_has_layer(&mesh_dst->ldata, CD_MDISPS)) {
1345                 if (totloop == mesh_dst->totloop) {
1346                         MDisps *mdisps = CustomData_get_layer(&mesh_dst->ldata, CD_MDISPS);
1347                         CustomData_add_layer(&tmp.ldata, CD_MDISPS, alloctype, mdisps, totloop);
1348                 }
1349         }
1350
1351         /* yes, must be before _and_ after tessellate */
1352         BKE_mesh_update_customdata_pointers(&tmp, false);
1353
1354         /* since 2.65 caller must do! */
1355         // BKE_mesh_tessface_calc(&tmp);
1356
1357         CustomData_free(&mesh_dst->vdata, mesh_dst->totvert);
1358         CustomData_free(&mesh_dst->edata, mesh_dst->totedge);
1359         CustomData_free(&mesh_dst->fdata, mesh_dst->totface);
1360         CustomData_free(&mesh_dst->ldata, mesh_dst->totloop);
1361         CustomData_free(&mesh_dst->pdata, mesh_dst->totpoly);
1362
1363         /* ok, this should now use new CD shapekey data,
1364          * which should be fed through the modifier
1365          * stack */
1366         if (tmp.totvert != mesh_dst->totvert && !did_shapekeys && mesh_dst->key) {
1367                 printf("%s: YEEK! this should be recoded! Shape key loss!: ID '%s'\n", __func__, tmp.id.name);
1368                 if (tmp.key && !(tmp.id.tag & LIB_TAG_NO_MAIN)) {
1369                         id_us_min(&tmp.key->id);
1370                 }
1371                 tmp.key = NULL;
1372         }
1373
1374         /* Clear selection history */
1375         MEM_SAFE_FREE(tmp.mselect);
1376         tmp.totselect = 0;
1377         BLI_assert(ELEM(tmp.bb, NULL, mesh_dst->bb));
1378         if (mesh_dst->bb) {
1379                 MEM_freeN(mesh_dst->bb);
1380                 tmp.bb = NULL;
1381         }
1382
1383         /* skip the listbase */
1384         MEMCPY_STRUCT_OFS(mesh_dst, &tmp, id.prev);
1385
1386         if (take_ownership) {
1387                 if (alloctype == CD_ASSIGN) {
1388                         CustomData_free_typemask(&mesh_src->vdata, mesh_src->totvert, ~mask);
1389                         CustomData_free_typemask(&mesh_src->edata, mesh_src->totedge, ~mask);
1390                         CustomData_free_typemask(&mesh_src->ldata, mesh_src->totloop, ~mask);
1391                         CustomData_free_typemask(&mesh_src->pdata, mesh_src->totpoly, ~mask);
1392                 }
1393                 BKE_id_free(NULL, mesh_src);
1394         }
1395 }
1396
1397 /* This is a Mesh-based copy of DM_to_meshkey() */
1398 void BKE_mesh_nomain_to_meshkey(Mesh *mesh_src, Mesh *mesh_dst, KeyBlock *kb)
1399 {
1400         int a, totvert = mesh_src->totvert;
1401         float *fp;
1402         MVert *mvert;
1403
1404         if (totvert == 0 || mesh_dst->totvert == 0 || mesh_dst->totvert != totvert) {
1405                 return;
1406         }
1407
1408         if (kb->data) MEM_freeN(kb->data);
1409         kb->data = MEM_malloc_arrayN(mesh_dst->key->elemsize, mesh_dst->totvert, "kb->data");
1410         kb->totelem = totvert;
1411
1412         fp = kb->data;
1413         mvert = mesh_src->mvert;
1414
1415         for (a = 0; a < kb->totelem; a++, fp += 3, mvert++) {
1416                 copy_v3_v3(fp, mvert->co);
1417         }
1418 }