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