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