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