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