Fix T54098: Crash existing /w dyntopo sculpt
[blender.git] / source / blender / bmesh / intern / bmesh_mesh_conv.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  * Contributor(s): Geoffrey Bantle.
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/bmesh/intern/bmesh_mesh_conv.c
24  *  \ingroup bmesh
25  *
26  * BM mesh conversion functions.
27  *
28  * \section bm_mesh_conv_shapekey Converting Shape Keys
29  *
30  * When converting to/from a Mesh/BMesh you can optionally pass a shape key to edit.
31  * This has the effect of editing the shape key-block rather then the original mesh vertex coords
32  * (although additional geometry is still allowed and uses fallback locations on converting).
33  *
34  * While this works for any mesh/bmesh this is made use of by entering and exiting edit-mode.
35  *
36  * There are comments in code but this should help explain the general
37  * intention as to how this works converting from/to bmesh.
38  *
39  *
40  * \subsection user_pov User Perspective
41  *
42  * - Editmode operations when a shape key-block is active edits only that key-block.
43  * - The first Basis key-block always matches the Mesh verts.
44  * - Changing vertex locations of _any_ Basis will apply offsets to those shape keys using this as their Basis.
45  *
46  *
47  * \subsection enter_editmode Entering EditMode - #BM_mesh_bm_from_me
48  *
49  * - the active key-block is used for BMesh vertex locations on entering edit-mode.
50  * So obviously the meshes vertex locations remain unchanged and the shape key its self is not being edited directly.
51  * Simply the #BMVert.co is a initialized from active shape key (when its set).
52  * - all key-blocks are added as CustomData layers (read code for details).
53  *
54  *
55  * \subsection exit_editmode Exiting EditMode - #BM_mesh_bm_to_me
56  *
57  * This is where the most confusing code is! Won't attempt to document the details here, for that read the code.
58  * But basics are as follows.
59  *
60  * - Vertex locations (possibly modified from initial active key-block) are copied directly into #MVert.co
61  * (special confusing note that these may be restored later, when editing the 'Basis', read on).
62  * - if the 'Key' is relative, and the active key-block is the basis for ANY other key-blocks - get an array of offsets
63  * between the new vertex locations and the original shape key (before entering edit-mode),
64  * these offsets get applied later on to inactive key-blocks using the active one (which we are editing) as their Basis.
65  *
66  * Copying the locations back to the shape keys is quite confusing...
67  * One main area of confusion is that when editing a 'Basis' key-block 'me->key->refkey'
68  * The coords are written into the mesh, from the users perspective the Basis coords are written into the mesh
69  * when exiting edit-mode.
70  *
71  * When _not_ editing the 'Basis', the original vertex locations (stored in the mesh and unchanged during edit-mode),
72  * are copied back into the mesh.
73  *
74  * This has the effect from the users POV of leaving the mesh un-touched, and only editing the active shape key-block.
75  *
76  */
77
78 #include "DNA_mesh_types.h"
79 #include "DNA_meshdata_types.h"
80 #include "DNA_object_types.h"
81 #include "DNA_modifier_types.h"
82 #include "DNA_key_types.h"
83
84 #include "MEM_guardedalloc.h"
85
86 #include "BLI_listbase.h"
87 #include "BLI_alloca.h"
88 #include "BLI_math_vector.h"
89
90 #include "BKE_mesh.h"
91 #include "BKE_customdata.h"
92 #include "BKE_multires.h"
93
94 #include "BKE_global.h" /* ugh - for looping over all objects */
95 #include "BKE_main.h"
96 #include "BKE_key.h"
97
98 #include "bmesh.h"
99 #include "intern/bmesh_private.h" /* for element checking */
100
101 /**
102  * Currently this is only used for Python scripts
103  * which may fail to keep matching UV/TexFace layers.
104  *
105  * \note This should only perform any changes in exceptional cases,
106  * if we need this to be faster we could inline #BM_data_layer_add and only
107  * call #update_data_blocks once at the end.
108  */
109 void BM_mesh_cd_validate(BMesh *bm)
110 {
111         int totlayer_mtex = CustomData_number_of_layers(&bm->pdata, CD_MTEXPOLY);
112         int totlayer_uv = CustomData_number_of_layers(&bm->ldata, CD_MLOOPUV);
113
114         if (LIKELY(totlayer_mtex == totlayer_uv)) {
115                 /* pass */
116         }
117         else if (totlayer_mtex < totlayer_uv) {
118                 const int uv_index_first = CustomData_get_layer_index(&bm->ldata, CD_MLOOPUV);
119                 do {
120                         const char *from_name =  bm->ldata.layers[uv_index_first + totlayer_mtex].name;
121                         BM_data_layer_add_named(bm, &bm->pdata, CD_MTEXPOLY, from_name);
122                         CustomData_set_layer_unique_name(&bm->pdata, totlayer_mtex);
123                 } while (totlayer_uv != ++totlayer_mtex);
124         }
125         else if (totlayer_uv < totlayer_mtex) {
126                 const int mtex_index_first = CustomData_get_layer_index(&bm->pdata, CD_MTEXPOLY);
127                 do {
128                         const char *from_name = bm->pdata.layers[mtex_index_first + totlayer_uv].name;
129                         BM_data_layer_add_named(bm, &bm->ldata, CD_MLOOPUV, from_name);
130                         CustomData_set_layer_unique_name(&bm->ldata, totlayer_uv);
131                 } while (totlayer_mtex != ++totlayer_uv);
132         }
133
134         BLI_assert(totlayer_mtex == totlayer_uv);
135 }
136
137 void BM_mesh_cd_flag_ensure(BMesh *bm, Mesh *mesh, const char cd_flag)
138 {
139         const char cd_flag_all = BM_mesh_cd_flag_from_bmesh(bm) | cd_flag;
140         BM_mesh_cd_flag_apply(bm, cd_flag_all);
141         if (mesh) {
142                 mesh->cd_flag = cd_flag_all;
143         }
144 }
145
146 void BM_mesh_cd_flag_apply(BMesh *bm, const char cd_flag)
147 {
148         /* CustomData_bmesh_init_pool() must run first */
149         BLI_assert(bm->vdata.totlayer == 0 || bm->vdata.pool != NULL);
150         BLI_assert(bm->edata.totlayer == 0 || bm->edata.pool != NULL);
151         BLI_assert(bm->pdata.totlayer == 0 || bm->pdata.pool != NULL);
152
153         if (cd_flag & ME_CDFLAG_VERT_BWEIGHT) {
154                 if (!CustomData_has_layer(&bm->vdata, CD_BWEIGHT)) {
155                         BM_data_layer_add(bm, &bm->vdata, CD_BWEIGHT);
156                 }
157         }
158         else {
159                 if (CustomData_has_layer(&bm->vdata, CD_BWEIGHT)) {
160                         BM_data_layer_free(bm, &bm->vdata, CD_BWEIGHT);
161                 }
162         }
163
164         if (cd_flag & ME_CDFLAG_EDGE_BWEIGHT) {
165                 if (!CustomData_has_layer(&bm->edata, CD_BWEIGHT)) {
166                         BM_data_layer_add(bm, &bm->edata, CD_BWEIGHT);
167                 }
168         }
169         else {
170                 if (CustomData_has_layer(&bm->edata, CD_BWEIGHT)) {
171                         BM_data_layer_free(bm, &bm->edata, CD_BWEIGHT);
172                 }
173         }
174
175         if (cd_flag & ME_CDFLAG_EDGE_CREASE) {
176                 if (!CustomData_has_layer(&bm->edata, CD_CREASE)) {
177                         BM_data_layer_add(bm, &bm->edata, CD_CREASE);
178                 }
179         }
180         else {
181                 if (CustomData_has_layer(&bm->edata, CD_CREASE)) {
182                         BM_data_layer_free(bm, &bm->edata, CD_CREASE);
183                 }
184         }
185 }
186
187 char BM_mesh_cd_flag_from_bmesh(BMesh *bm)
188 {
189         char cd_flag = 0;
190         if (CustomData_has_layer(&bm->vdata, CD_BWEIGHT)) {
191                 cd_flag |= ME_CDFLAG_VERT_BWEIGHT;
192         }
193         if (CustomData_has_layer(&bm->edata, CD_BWEIGHT)) {
194                 cd_flag |= ME_CDFLAG_EDGE_BWEIGHT;
195         }
196         if (CustomData_has_layer(&bm->edata, CD_CREASE)) {
197                 cd_flag |= ME_CDFLAG_EDGE_CREASE;
198         }
199         return cd_flag;
200 }
201
202 /* Static function for alloc (duplicate in modifiers_bmesh.c) */
203 static BMFace *bm_face_create_from_mpoly(
204         MPoly *mp, MLoop *ml,
205         BMesh *bm, BMVert **vtable, BMEdge **etable)
206 {
207         BMVert **verts = BLI_array_alloca(verts, mp->totloop);
208         BMEdge **edges = BLI_array_alloca(edges, mp->totloop);
209         int j;
210
211         for (j = 0; j < mp->totloop; j++, ml++) {
212                 verts[j] = vtable[ml->v];
213                 edges[j] = etable[ml->e];
214         }
215
216         return BM_face_create(bm, verts, edges, mp->totloop, NULL, BM_CREATE_SKIP_CD);
217 }
218
219
220 /**
221  * \brief Mesh -> BMesh
222  * \param bm: The mesh to write into, while this is typically a newly created BMesh,
223  * merging into existing data is supported.
224  * Note the custom-data layout isn't used.
225  * If more comprehensive merging is needed we should move this into a separate function
226  * since this should be kept fast for edit-mode switching and storing undo steps.
227  *
228  * \warning This function doesn't calculate face normals.
229  */
230 void BM_mesh_bm_from_me(
231         BMesh *bm, Mesh *me,
232         const struct BMeshFromMeshParams *params)
233 {
234         const bool is_new =
235                 !(bm->totvert ||
236                   (bm->vdata.totlayer || bm->edata.totlayer || bm->pdata.totlayer || bm->ldata.totlayer));
237         MVert *mvert;
238         MEdge *medge;
239         MLoop *mloop;
240         MPoly *mp;
241         KeyBlock *actkey, *block;
242         BMVert *v, **vtable = NULL;
243         BMEdge *e, **etable = NULL;
244         BMFace *f, **ftable = NULL;
245         float (*keyco)[3] = NULL;
246         int totuv, totloops, i;
247
248         if (!me || !me->totvert) {
249                 if (me && is_new) { /*no verts? still copy customdata layout*/
250                         CustomData_copy(&me->vdata, &bm->vdata, CD_MASK_BMESH, CD_ASSIGN, 0);
251                         CustomData_copy(&me->edata, &bm->edata, CD_MASK_BMESH, CD_ASSIGN, 0);
252                         CustomData_copy(&me->ldata, &bm->ldata, CD_MASK_BMESH, CD_ASSIGN, 0);
253                         CustomData_copy(&me->pdata, &bm->pdata, CD_MASK_BMESH, CD_ASSIGN, 0);
254
255                         CustomData_bmesh_init_pool(&bm->vdata, me->totvert, BM_VERT);
256                         CustomData_bmesh_init_pool(&bm->edata, me->totedge, BM_EDGE);
257                         CustomData_bmesh_init_pool(&bm->ldata, me->totloop, BM_LOOP);
258                         CustomData_bmesh_init_pool(&bm->pdata, me->totpoly, BM_FACE);
259                 }
260                 return; /* sanity check */
261         }
262
263         if (is_new) {
264                 CustomData_copy(&me->vdata, &bm->vdata, CD_MASK_BMESH, CD_CALLOC, 0);
265                 CustomData_copy(&me->edata, &bm->edata, CD_MASK_BMESH, CD_CALLOC, 0);
266                 CustomData_copy(&me->ldata, &bm->ldata, CD_MASK_BMESH, CD_CALLOC, 0);
267                 CustomData_copy(&me->pdata, &bm->pdata, CD_MASK_BMESH, CD_CALLOC, 0);
268
269                 /* make sure uv layer names are consisten */
270                 totuv = CustomData_number_of_layers(&bm->pdata, CD_MTEXPOLY);
271                 for (i = 0; i < totuv; i++) {
272                         int li = CustomData_get_layer_index_n(&bm->pdata, CD_MTEXPOLY, i);
273                         CustomData_set_layer_name(&bm->ldata, CD_MLOOPUV, i, bm->pdata.layers[li].name);
274                 }
275         }
276
277         /* -------------------------------------------------------------------- */
278         /* Shape Key */
279         int tot_shape_keys = me->key ? BLI_listbase_count(&me->key->block) : 0;
280         if (is_new == false) {
281                 tot_shape_keys = min_ii(tot_shape_keys, CustomData_number_of_layers(&bm->vdata, CD_SHAPEKEY));
282         }
283         const float (**shape_key_table)[3] = tot_shape_keys ? BLI_array_alloca(shape_key_table, tot_shape_keys) : NULL;
284
285         if ((params->active_shapekey != 0) && (me->key != NULL)) {
286                 actkey = BLI_findlink(&me->key->block, params->active_shapekey - 1);
287         }
288         else {
289                 actkey = NULL;
290         }
291
292         if (is_new) {
293                 if (tot_shape_keys || params->add_key_index) {
294                         CustomData_add_layer(&bm->vdata, CD_SHAPE_KEYINDEX, CD_ASSIGN, NULL, 0);
295                 }
296         }
297
298         if (tot_shape_keys) {
299                 if (is_new) {
300                         /* check if we need to generate unique ids for the shapekeys.
301                          * this also exists in the file reading code, but is here for
302                          * a sanity check */
303                         if (!me->key->uidgen) {
304                                 fprintf(stderr,
305                                         "%s had to generate shape key uid's in a situation we shouldn't need to! "
306                                         "(bmesh internal error)\n",
307                                         __func__);
308
309                                 me->key->uidgen = 1;
310                                 for (block = me->key->block.first; block; block = block->next) {
311                                         block->uid = me->key->uidgen++;
312                                 }
313                         }
314                 }
315
316                 if (actkey && actkey->totelem == me->totvert) {
317                         keyco = params->use_shapekey ? actkey->data : NULL;
318                         if (is_new) {
319                                 bm->shapenr = params->active_shapekey;
320                         }
321                 }
322
323                 for (i = 0, block = me->key->block.first; i < tot_shape_keys; block = block->next, i++) {
324                         if (is_new) {
325                                 CustomData_add_layer_named(&bm->vdata, CD_SHAPEKEY,
326                                                            CD_ASSIGN, NULL, 0, block->name);
327                                 int j = CustomData_get_layer_index_n(&bm->vdata, CD_SHAPEKEY, i);
328                                 bm->vdata.layers[j].uid = block->uid;
329                         }
330                         shape_key_table[i] = (const float (*)[3])block->data;
331                 }
332         }
333
334         if (is_new) {
335                 CustomData_bmesh_init_pool(&bm->vdata, me->totvert, BM_VERT);
336                 CustomData_bmesh_init_pool(&bm->edata, me->totedge, BM_EDGE);
337                 CustomData_bmesh_init_pool(&bm->ldata, me->totloop, BM_LOOP);
338                 CustomData_bmesh_init_pool(&bm->pdata, me->totpoly, BM_FACE);
339
340                 BM_mesh_cd_flag_apply(bm, me->cd_flag);
341         }
342
343         const int cd_vert_bweight_offset = CustomData_get_offset(&bm->vdata, CD_BWEIGHT);
344         const int cd_edge_bweight_offset = CustomData_get_offset(&bm->edata, CD_BWEIGHT);
345         const int cd_edge_crease_offset  = CustomData_get_offset(&bm->edata, CD_CREASE);
346         const int cd_shape_key_offset = me->key ? CustomData_get_offset(&bm->vdata, CD_SHAPEKEY) : -1;
347         const int cd_shape_keyindex_offset = is_new && (tot_shape_keys || params->add_key_index) ?
348                   CustomData_get_offset(&bm->vdata, CD_SHAPE_KEYINDEX) : -1;
349
350         vtable = MEM_mallocN(sizeof(BMVert **) * me->totvert, __func__);
351
352         for (i = 0, mvert = me->mvert; i < me->totvert; i++, mvert++) {
353                 v = vtable[i] = BM_vert_create(bm, keyco ? keyco[i] : mvert->co, NULL, BM_CREATE_SKIP_CD);
354                 BM_elem_index_set(v, i); /* set_ok */
355
356                 /* transfer flag */
357                 v->head.hflag = BM_vert_flag_from_mflag(mvert->flag & ~SELECT);
358
359                 /* this is necessary for selection counts to work properly */
360                 if (mvert->flag & SELECT) {
361                         BM_vert_select_set(bm, v, true);
362                 }
363
364                 normal_short_to_float_v3(v->no, mvert->no);
365
366                 /* Copy Custom Data */
367                 CustomData_to_bmesh_block(&me->vdata, &bm->vdata, i, &v->head.data, true);
368
369                 if (cd_vert_bweight_offset != -1) BM_ELEM_CD_SET_FLOAT(v, cd_vert_bweight_offset, (float)mvert->bweight / 255.0f);
370
371                 /* set shape key original index */
372                 if (cd_shape_keyindex_offset != -1) BM_ELEM_CD_SET_INT(v, cd_shape_keyindex_offset, i);
373
374                 /* set shapekey data */
375                 if (tot_shape_keys) {
376                         float (*co_dst)[3] = BM_ELEM_CD_GET_VOID_P(v, cd_shape_key_offset);
377                         for (int j = 0; j < tot_shape_keys; j++, co_dst++) {
378                                 copy_v3_v3(*co_dst, shape_key_table[j][i]);
379                         }
380                 }
381         }
382         if (is_new) {
383                 bm->elem_index_dirty &= ~BM_VERT; /* added in order, clear dirty flag */
384         }
385
386         etable = MEM_mallocN(sizeof(BMEdge **) * me->totedge, __func__);
387
388         medge = me->medge;
389         for (i = 0; i < me->totedge; i++, medge++) {
390                 e = etable[i] = BM_edge_create(bm, vtable[medge->v1], vtable[medge->v2], NULL, BM_CREATE_SKIP_CD);
391                 BM_elem_index_set(e, i); /* set_ok */
392
393                 /* transfer flags */
394                 e->head.hflag = BM_edge_flag_from_mflag(medge->flag & ~SELECT);
395
396                 /* this is necessary for selection counts to work properly */
397                 if (medge->flag & SELECT) {
398                         BM_edge_select_set(bm, e, true);
399                 }
400
401                 /* Copy Custom Data */
402                 CustomData_to_bmesh_block(&me->edata, &bm->edata, i, &e->head.data, true);
403
404                 if (cd_edge_bweight_offset != -1) BM_ELEM_CD_SET_FLOAT(e, cd_edge_bweight_offset, (float)medge->bweight / 255.0f);
405                 if (cd_edge_crease_offset  != -1) BM_ELEM_CD_SET_FLOAT(e, cd_edge_crease_offset,  (float)medge->crease  / 255.0f);
406
407         }
408         if (is_new) {
409                 bm->elem_index_dirty &= ~BM_EDGE; /* added in order, clear dirty flag */
410         }
411
412         /* only needed for selection. */
413         if (me->mselect && me->totselect != 0) {
414                 ftable = MEM_mallocN(sizeof(BMFace **) * me->totpoly, __func__);
415         }
416
417         mloop = me->mloop;
418         mp = me->mpoly;
419         for (i = 0, totloops = 0; i < me->totpoly; i++, mp++) {
420                 BMLoop *l_iter;
421                 BMLoop *l_first;
422
423                 f = bm_face_create_from_mpoly(mp, mloop + mp->loopstart,
424                                               bm, vtable, etable);
425                 if (ftable != NULL) {
426                         ftable[i] = f;
427                 }
428
429                 if (UNLIKELY(f == NULL)) {
430                         printf("%s: Warning! Bad face in mesh"
431                                " \"%s\" at index %d!, skipping\n",
432                                __func__, me->id.name + 2, i);
433                         continue;
434                 }
435
436                 /* don't use 'i' since we may have skipped the face */
437                 BM_elem_index_set(f, bm->totface - 1); /* set_ok */
438
439                 /* transfer flag */
440                 f->head.hflag = BM_face_flag_from_mflag(mp->flag & ~ME_FACE_SEL);
441
442                 /* this is necessary for selection counts to work properly */
443                 if (mp->flag & ME_FACE_SEL) {
444                         BM_face_select_set(bm, f, true);
445                 }
446
447                 f->mat_nr = mp->mat_nr;
448                 if (i == me->act_face) bm->act_face = f;
449
450                 int j = mp->loopstart;
451                 l_iter = l_first = BM_FACE_FIRST_LOOP(f);
452                 do {
453                         /* don't use 'j' since we may have skipped some faces, hence some loops. */
454                         BM_elem_index_set(l_iter, totloops++); /* set_ok */
455
456                         /* Save index of correspsonding MLoop */
457                         CustomData_to_bmesh_block(&me->ldata, &bm->ldata, j++, &l_iter->head.data, true);
458                 } while ((l_iter = l_iter->next) != l_first);
459
460                 /* Copy Custom Data */
461                 CustomData_to_bmesh_block(&me->pdata, &bm->pdata, i, &f->head.data, true);
462
463                 if (params->calc_face_normal) {
464                         BM_face_normal_update(f);
465                 }
466         }
467         if (is_new) {
468                 bm->elem_index_dirty &= ~(BM_FACE | BM_LOOP); /* added in order, clear dirty flag */
469         }
470
471         /* -------------------------------------------------------------------- */
472         /* MSelect clears the array elements (avoid adding multiple times).
473          *
474          * Take care to keep this last and not use (v/e/ftable) after this.
475          */
476
477         if (me->mselect && me->totselect != 0) {
478                 MSelect *msel;
479                 for (i = 0, msel = me->mselect; i < me->totselect; i++, msel++) {
480                         BMElem **ele_p;
481                         switch (msel->type) {
482                                 case ME_VSEL:
483                                         ele_p = (BMElem **)&vtable[msel->index];
484                                         break;
485                                 case ME_ESEL:
486                                         ele_p = (BMElem **)&etable[msel->index];
487                                         break;
488                                 case ME_FSEL:
489                                         ele_p = (BMElem **)&ftable[msel->index];
490                                         break;
491                                 default:
492                                         continue;
493                         }
494
495                         if (*ele_p != NULL) {
496                                 BM_select_history_store_notest(bm, *ele_p);
497                                 *ele_p = NULL;
498                         }
499                 }
500         }
501         else {
502                 BM_select_history_clear(bm);
503         }
504
505         MEM_freeN(vtable);
506         MEM_freeN(etable);
507         if (ftable) {
508                 MEM_freeN(ftable);
509         }
510 }
511
512
513 /**
514  * \brief BMesh -> Mesh
515  */
516 static BMVert **bm_to_mesh_vertex_map(BMesh *bm, int ototvert)
517 {
518         const int cd_shape_keyindex_offset = CustomData_get_offset(&bm->vdata, CD_SHAPE_KEYINDEX);
519         BMVert **vertMap = NULL;
520         BMVert *eve;
521         int i = 0;
522         BMIter iter;
523
524         /* caller needs to ensure this */
525         BLI_assert(ototvert > 0);
526
527         vertMap = MEM_callocN(sizeof(*vertMap) * ototvert, "vertMap");
528         if (cd_shape_keyindex_offset != -1) {
529                 BM_ITER_MESH_INDEX (eve, &iter, bm, BM_VERTS_OF_MESH, i) {
530                         const int keyi = BM_ELEM_CD_GET_INT(eve, cd_shape_keyindex_offset);
531                         if ((keyi != ORIGINDEX_NONE) &&
532                             (keyi < ototvert) &&
533                             /* not fool-proof, but chances are if we have many verts with the same index,
534                              * we will want to use the first one, since the second is more likely to be a duplicate. */
535                             (vertMap[keyi] == NULL))
536                         {
537                                 vertMap[keyi] = eve;
538                         }
539                 }
540         }
541         else {
542                 BM_ITER_MESH_INDEX (eve, &iter, bm, BM_VERTS_OF_MESH, i) {
543                         if (i < ototvert) {
544                                 vertMap[i] = eve;
545                         }
546                         else {
547                                 break;
548                         }
549                 }
550         }
551
552         return vertMap;
553 }
554
555 /**
556  * returns customdata shapekey index from a keyblock or -1
557  * \note could split this out into a more generic function */
558 static int bm_to_mesh_shape_layer_index_from_kb(BMesh *bm, KeyBlock *currkey)
559 {
560         int i;
561         int j = 0;
562
563         for (i = 0; i < bm->vdata.totlayer; i++) {
564                 if (bm->vdata.layers[i].type == CD_SHAPEKEY) {
565                         if (currkey->uid == bm->vdata.layers[i].uid) {
566                                 return j;
567                         }
568                         j++;
569                 }
570         }
571         return -1;
572 }
573
574 BLI_INLINE void bmesh_quick_edgedraw_flag(MEdge *med, BMEdge *e)
575 {
576         /* this is a cheap way to set the edge draw, its not precise and will
577          * pick the first 2 faces an edge uses.
578          * The dot comparison is a little arbitrary, but set so that a 5 subd
579          * IcoSphere won't vanish but subd 6 will (as with pre-bmesh blender) */
580
581
582         if ( /* (med->flag & ME_EDGEDRAW) && */ /* assume to be true */
583              (e->l && (e->l != e->l->radial_next)) &&
584              (dot_v3v3(e->l->f->no, e->l->radial_next->f->no) > 0.9995f))
585         {
586                 med->flag &= ~ME_EDGEDRAW;
587         }
588         else {
589                 med->flag |= ME_EDGEDRAW;
590         }
591 }
592
593 void BM_mesh_bm_to_me(
594         BMesh *bm, Mesh *me,
595         const struct BMeshToMeshParams *params)
596 {
597         MLoop *mloop;
598         MPoly *mpoly;
599         MVert *mvert, *oldverts;
600         MEdge *med, *medge;
601         BMVert *v, *eve;
602         BMEdge *e;
603         BMFace *f;
604         BMIter iter;
605         int i, j, ototvert;
606
607         const int cd_vert_bweight_offset = CustomData_get_offset(&bm->vdata, CD_BWEIGHT);
608         const int cd_edge_bweight_offset = CustomData_get_offset(&bm->edata, CD_BWEIGHT);
609         const int cd_edge_crease_offset  = CustomData_get_offset(&bm->edata, CD_CREASE);
610
611         ototvert = me->totvert;
612
613         /* new vertex block */
614         if (bm->totvert == 0) mvert = NULL;
615         else mvert = MEM_callocN(bm->totvert * sizeof(MVert), "loadeditbMesh vert");
616
617         /* new edge block */
618         if (bm->totedge == 0) medge = NULL;
619         else medge = MEM_callocN(bm->totedge * sizeof(MEdge), "loadeditbMesh edge");
620
621         /* new ngon face block */
622         if (bm->totface == 0) mpoly = NULL;
623         else mpoly = MEM_callocN(bm->totface * sizeof(MPoly), "loadeditbMesh poly");
624
625         /* new loop block */
626         if (bm->totloop == 0) mloop = NULL;
627         else mloop = MEM_callocN(bm->totloop * sizeof(MLoop), "loadeditbMesh loop");
628
629         /* lets save the old verts just in case we are actually working on
630          * a key ... we now do processing of the keys at the end */
631         oldverts = me->mvert;
632
633         /* don't free this yet */
634         if (oldverts) {
635                 CustomData_set_layer(&me->vdata, CD_MVERT, NULL);
636         }
637
638         /* free custom data */
639         CustomData_free(&me->vdata, me->totvert);
640         CustomData_free(&me->edata, me->totedge);
641         CustomData_free(&me->fdata, me->totface);
642         CustomData_free(&me->ldata, me->totloop);
643         CustomData_free(&me->pdata, me->totpoly);
644
645         /* add new custom data */
646         me->totvert = bm->totvert;
647         me->totedge = bm->totedge;
648         me->totloop = bm->totloop;
649         me->totpoly = bm->totface;
650         /* will be overwritten with a valid value if 'dotess' is set, otherwise we
651          * end up with 'me->totface' and me->mface == NULL which can crash [#28625]
652          */
653         me->totface = 0;
654         me->act_face = -1;
655
656         {
657                 const CustomDataMask mask = CD_MASK_MESH | params->cd_mask_extra;
658                 CustomData_copy(&bm->vdata, &me->vdata, mask, CD_CALLOC, me->totvert);
659                 CustomData_copy(&bm->edata, &me->edata, mask, CD_CALLOC, me->totedge);
660                 CustomData_copy(&bm->ldata, &me->ldata, mask, CD_CALLOC, me->totloop);
661                 CustomData_copy(&bm->pdata, &me->pdata, mask, CD_CALLOC, me->totpoly);
662         }
663
664         CustomData_add_layer(&me->vdata, CD_MVERT, CD_ASSIGN, mvert, me->totvert);
665         CustomData_add_layer(&me->edata, CD_MEDGE, CD_ASSIGN, medge, me->totedge);
666         CustomData_add_layer(&me->ldata, CD_MLOOP, CD_ASSIGN, mloop, me->totloop);
667         CustomData_add_layer(&me->pdata, CD_MPOLY, CD_ASSIGN, mpoly, me->totpoly);
668
669         me->cd_flag = BM_mesh_cd_flag_from_bmesh(bm);
670
671         /* this is called again, 'dotess' arg is used there */
672         BKE_mesh_update_customdata_pointers(me, 0);
673
674         i = 0;
675         BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
676                 copy_v3_v3(mvert->co, v->co);
677                 normal_float_to_short_v3(mvert->no, v->no);
678
679                 mvert->flag = BM_vert_flag_to_mflag(v);
680
681                 BM_elem_index_set(v, i); /* set_inline */
682
683                 /* copy over customdat */
684                 CustomData_from_bmesh_block(&bm->vdata, &me->vdata, v->head.data, i);
685
686                 if (cd_vert_bweight_offset != -1) mvert->bweight = BM_ELEM_CD_GET_FLOAT_AS_UCHAR(v, cd_vert_bweight_offset);
687
688                 i++;
689                 mvert++;
690
691                 BM_CHECK_ELEMENT(v);
692         }
693         bm->elem_index_dirty &= ~BM_VERT;
694
695         med = medge;
696         i = 0;
697         BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
698                 med->v1 = BM_elem_index_get(e->v1);
699                 med->v2 = BM_elem_index_get(e->v2);
700
701                 med->flag = BM_edge_flag_to_mflag(e);
702
703                 BM_elem_index_set(e, i); /* set_inline */
704
705                 /* copy over customdata */
706                 CustomData_from_bmesh_block(&bm->edata, &me->edata, e->head.data, i);
707
708                 bmesh_quick_edgedraw_flag(med, e);
709
710                 if (cd_edge_crease_offset  != -1) med->crease  = BM_ELEM_CD_GET_FLOAT_AS_UCHAR(e, cd_edge_crease_offset);
711                 if (cd_edge_bweight_offset != -1) med->bweight = BM_ELEM_CD_GET_FLOAT_AS_UCHAR(e, cd_edge_bweight_offset);
712
713                 i++;
714                 med++;
715                 BM_CHECK_ELEMENT(e);
716         }
717         bm->elem_index_dirty &= ~BM_EDGE;
718
719         i = 0;
720         j = 0;
721         BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
722                 BMLoop *l_iter, *l_first;
723                 mpoly->loopstart = j;
724                 mpoly->totloop = f->len;
725                 mpoly->mat_nr = f->mat_nr;
726                 mpoly->flag = BM_face_flag_to_mflag(f);
727
728                 l_iter = l_first = BM_FACE_FIRST_LOOP(f);
729                 do {
730                         mloop->e = BM_elem_index_get(l_iter->e);
731                         mloop->v = BM_elem_index_get(l_iter->v);
732
733                         /* copy over customdata */
734                         CustomData_from_bmesh_block(&bm->ldata, &me->ldata, l_iter->head.data, j);
735
736                         j++;
737                         mloop++;
738                         BM_CHECK_ELEMENT(l_iter);
739                         BM_CHECK_ELEMENT(l_iter->e);
740                         BM_CHECK_ELEMENT(l_iter->v);
741                 } while ((l_iter = l_iter->next) != l_first);
742
743                 if (f == bm->act_face) me->act_face = i;
744
745                 /* copy over customdata */
746                 CustomData_from_bmesh_block(&bm->pdata, &me->pdata, f->head.data, i);
747
748                 i++;
749                 mpoly++;
750                 BM_CHECK_ELEMENT(f);
751         }
752
753         /* patch hook indices and vertex parents */
754         if (params->calc_object_remap && (ototvert > 0)) {
755                 Object *ob;
756                 ModifierData *md;
757                 BMVert **vertMap = NULL;
758
759                 for (ob = G.main->object.first; ob; ob = ob->id.next) {
760                         if ((ob->parent) && (ob->parent->data == me) && ELEM(ob->partype, PARVERT1, PARVERT3)) {
761
762                                 if (vertMap == NULL) {
763                                         vertMap = bm_to_mesh_vertex_map(bm, ototvert);
764                                 }
765
766                                 if (ob->par1 < ototvert) {
767                                         eve = vertMap[ob->par1];
768                                         if (eve) ob->par1 = BM_elem_index_get(eve);
769                                 }
770                                 if (ob->par2 < ototvert) {
771                                         eve = vertMap[ob->par2];
772                                         if (eve) ob->par2 = BM_elem_index_get(eve);
773                                 }
774                                 if (ob->par3 < ototvert) {
775                                         eve = vertMap[ob->par3];
776                                         if (eve) ob->par3 = BM_elem_index_get(eve);
777                                 }
778
779                         }
780                         if (ob->data == me) {
781                                 for (md = ob->modifiers.first; md; md = md->next) {
782                                         if (md->type == eModifierType_Hook) {
783                                                 HookModifierData *hmd = (HookModifierData *) md;
784
785                                                 if (vertMap == NULL) {
786                                                         vertMap = bm_to_mesh_vertex_map(bm, ototvert);
787                                                 }
788
789                                                 for (i = j = 0; i < hmd->totindex; i++) {
790                                                         if (hmd->indexar[i] < ototvert) {
791                                                                 eve = vertMap[hmd->indexar[i]];
792
793                                                                 if (eve) {
794                                                                         hmd->indexar[j++] = BM_elem_index_get(eve);
795                                                                 }
796                                                         }
797                                                         else {
798                                                                 j++;
799                                                         }
800                                                 }
801
802                                                 hmd->totindex = j;
803                                         }
804                                 }
805                         }
806                 }
807
808                 if (vertMap) MEM_freeN(vertMap);
809         }
810
811         if (params->calc_tessface) {
812                 BKE_mesh_tessface_calc(me);
813         }
814
815         BKE_mesh_update_customdata_pointers(me, params->calc_tessface);
816
817         {
818                 BMEditSelection *selected;
819                 me->totselect = BLI_listbase_count(&(bm->selected));
820
821                 MEM_SAFE_FREE(me->mselect);
822                 if (me->totselect != 0) {
823                         me->mselect = MEM_mallocN(sizeof(MSelect) * me->totselect, "Mesh selection history");
824                 }
825
826                 for (i = 0, selected = bm->selected.first; selected; i++, selected = selected->next) {
827                         if (selected->htype == BM_VERT) {
828                                 me->mselect[i].type = ME_VSEL;
829
830                         }
831                         else if (selected->htype == BM_EDGE) {
832                                 me->mselect[i].type = ME_ESEL;
833
834                         }
835                         else if (selected->htype == BM_FACE) {
836                                 me->mselect[i].type = ME_FSEL;
837                         }
838
839                         me->mselect[i].index = BM_elem_index_get(selected->ele);
840                 }
841         }
842
843         /* see comment below, this logic is in twice */
844
845         if (me->key) {
846                 const int cd_shape_keyindex_offset = CustomData_get_offset(&bm->vdata, CD_SHAPE_KEYINDEX);
847
848                 KeyBlock *currkey;
849                 KeyBlock *actkey = BLI_findlink(&me->key->block, bm->shapenr - 1);
850
851                 float (*ofs)[3] = NULL;
852
853                 /* go through and find any shapekey customdata layers
854                  * that might not have corresponding KeyBlocks, and add them if
855                  * necessary */
856                 j = 0;
857                 for (i = 0; i < bm->vdata.totlayer; i++) {
858                         if (bm->vdata.layers[i].type != CD_SHAPEKEY)
859                                 continue;
860
861                         for (currkey = me->key->block.first; currkey; currkey = currkey->next) {
862                                 if (currkey->uid == bm->vdata.layers[i].uid)
863                                         break;
864                         }
865
866                         if (!currkey) {
867                                 currkey = BKE_keyblock_add(me->key, bm->vdata.layers[i].name);
868                                 currkey->uid = bm->vdata.layers[i].uid;
869                         }
870
871                         j++;
872                 }
873
874
875                 /* editing the base key should update others */
876                 if ((me->key->type == KEY_RELATIVE) && /* only need offsets for relative shape keys */
877                     (actkey != NULL) &&                /* unlikely, but the active key may not be valid if the
878                                                         * bmesh and the mesh are out of sync */
879                     (oldverts != NULL))                /* not used here, but 'oldverts' is used later for applying 'ofs' */
880                 {
881                         const bool act_is_basis = BKE_keyblock_is_basis(me->key, bm->shapenr - 1);
882
883                         /* active key is a base */
884                         if (act_is_basis && (cd_shape_keyindex_offset != -1)) {
885                                 float (*fp)[3] = actkey->data;
886
887                                 ofs = MEM_callocN(sizeof(float) * 3 * bm->totvert,  "currkey->data");
888                                 mvert = me->mvert;
889                                 BM_ITER_MESH_INDEX (eve, &iter, bm, BM_VERTS_OF_MESH, i) {
890                                         const int keyi = BM_ELEM_CD_GET_INT(eve, cd_shape_keyindex_offset);
891
892                                         if (keyi != ORIGINDEX_NONE) {
893                                                 sub_v3_v3v3(ofs[i], mvert->co, fp[keyi]);
894                                         }
895                                         else {
896                                                 /* if there are new vertices in the mesh, we can't propagate the offset
897                                                  * because it will only work for the existing vertices and not the new
898                                                  * ones, creating a mess when doing e.g. subdivide + translate */
899                                                 MEM_freeN(ofs);
900                                                 ofs = NULL;
901                                                 break;
902                                         }
903
904                                         mvert++;
905                                 }
906                         }
907                 }
908
909                 for (currkey = me->key->block.first; currkey; currkey = currkey->next) {
910                         const bool apply_offset = (ofs && (currkey != actkey) && (bm->shapenr - 1 == currkey->relative));
911                         int cd_shape_offset;
912                         int keyi;
913                         float (*ofs_pt)[3] = ofs;
914                         float *newkey, (*oldkey)[3], *fp;
915
916                         j = bm_to_mesh_shape_layer_index_from_kb(bm, currkey);
917                         cd_shape_offset = CustomData_get_n_offset(&bm->vdata, CD_SHAPEKEY, j);
918
919
920                         fp = newkey = MEM_callocN(me->key->elemsize * bm->totvert,  "currkey->data");
921                         oldkey = currkey->data;
922
923                         mvert = me->mvert;
924                         BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
925
926                                 if (currkey == actkey) {
927                                         copy_v3_v3(fp, eve->co);
928
929                                         if (actkey != me->key->refkey) { /* important see bug [#30771] */
930                                                 if (cd_shape_keyindex_offset != -1) {
931                                                         if (oldverts) {
932                                                                 keyi = BM_ELEM_CD_GET_INT(eve, cd_shape_keyindex_offset);
933                                                                 if (keyi != ORIGINDEX_NONE && keyi < currkey->totelem) { /* valid old vertex */
934                                                                         copy_v3_v3(mvert->co, oldverts[keyi].co);
935                                                                 }
936                                                         }
937                                                 }
938                                         }
939                                 }
940                                 else if (j != -1) {
941                                         /* in most cases this runs */
942                                         copy_v3_v3(fp, BM_ELEM_CD_GET_VOID_P(eve, cd_shape_offset));
943                                 }
944                                 else if ((oldkey != NULL) &&
945                                          (cd_shape_keyindex_offset != -1) &&
946                                          ((keyi = BM_ELEM_CD_GET_INT(eve, cd_shape_keyindex_offset)) != ORIGINDEX_NONE) &&
947                                          (keyi < currkey->totelem))
948                                 {
949                                         /* old method of reconstructing keys via vertice's original key indices,
950                                          * currently used if the new method above fails (which is theoretically
951                                          * possible in certain cases of undo) */
952                                         copy_v3_v3(fp, oldkey[keyi]);
953                                 }
954                                 else {
955                                         /* fail! fill in with dummy value */
956                                         copy_v3_v3(fp, mvert->co);
957                                 }
958
959                                 /* propagate edited basis offsets to other shapes */
960                                 if (apply_offset) {
961                                         add_v3_v3(fp, *ofs_pt++);
962                                         /* Apply back new coordinates of offsetted shapekeys into BMesh.
963                                          * Otherwise, in case we call again BM_mesh_bm_to_me on same BMesh, we'll apply diff from previous
964                                          * call to BM_mesh_bm_to_me, to shapekey values from *original creation of the BMesh*. See T50524. */
965                                         copy_v3_v3(BM_ELEM_CD_GET_VOID_P(eve, cd_shape_offset), fp);
966                                 }
967
968                                 fp += 3;
969                                 mvert++;
970                         }
971
972                         currkey->totelem = bm->totvert;
973                         if (currkey->data) {
974                                 MEM_freeN(currkey->data);
975                         }
976                         currkey->data = newkey;
977                 }
978
979                 if (ofs) MEM_freeN(ofs);
980         }
981
982         if (oldverts) MEM_freeN(oldverts);
983
984         /* topology could be changed, ensure mdisps are ok */
985         multires_topology_changed(me);
986 }