Split Normals I (2/5): Add basic BMesh support of split normals.
[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(MPoly *mp, MLoop *ml,
204                                          BMesh *bm, BMVert **vtable, BMEdge **etable)
205 {
206         BMVert **verts = BLI_array_alloca(verts, mp->totloop);
207         BMEdge **edges = BLI_array_alloca(edges, mp->totloop);
208         int j;
209
210         for (j = 0; j < mp->totloop; j++, ml++) {
211                 verts[j] = vtable[ml->v];
212                 edges[j] = etable[ml->e];
213         }
214
215         return BM_face_create(bm, verts, edges, mp->totloop, NULL, BM_CREATE_SKIP_CD);
216 }
217
218
219 /**
220  * \brief Mesh -> BMesh
221  *
222  * \warning This function doesn't calculate face normals.
223  */
224 void BM_mesh_bm_from_me(BMesh *bm, Mesh *me,
225                         const bool calc_face_normal, const bool set_key, int act_key_nr)
226 {
227         MVert *mvert;
228         MEdge *medge;
229         MLoop *mloop;
230         MPoly *mp;
231         KeyBlock *actkey, *block;
232         BMVert *v, **vtable = NULL;
233         BMEdge *e, **etable = NULL;
234         BMFace *f;
235         float (*keyco)[3] = NULL;
236         int *keyi;
237         int totuv, i, j;
238
239         int cd_vert_bweight_offset;
240         int cd_edge_bweight_offset;
241         int cd_edge_crease_offset;
242
243         /* free custom data */
244         /* this isnt needed in most cases but do just incase */
245         CustomData_free(&bm->vdata, bm->totvert);
246         CustomData_free(&bm->edata, bm->totedge);
247         CustomData_free(&bm->ldata, bm->totloop);
248         CustomData_free(&bm->pdata, bm->totface);
249
250         if (!me || !me->totvert) {
251                 if (me) { /*no verts? still copy customdata layout*/
252                         CustomData_copy(&me->vdata, &bm->vdata, CD_MASK_BMESH, CD_ASSIGN, 0);
253                         CustomData_copy(&me->edata, &bm->edata, CD_MASK_BMESH, CD_ASSIGN, 0);
254                         CustomData_copy(&me->ldata, &bm->ldata, CD_MASK_BMESH, CD_ASSIGN, 0);
255                         CustomData_copy(&me->pdata, &bm->pdata, CD_MASK_BMESH, CD_ASSIGN, 0);
256
257                         CustomData_bmesh_init_pool(&bm->vdata, me->totvert, BM_VERT);
258                         CustomData_bmesh_init_pool(&bm->edata, me->totedge, BM_EDGE);
259                         CustomData_bmesh_init_pool(&bm->ldata, me->totloop, BM_LOOP);
260                         CustomData_bmesh_init_pool(&bm->pdata, me->totpoly, BM_FACE);
261                 }
262                 return; /* sanity check */
263         }
264
265         vtable = MEM_mallocN(sizeof(void **) * me->totvert, "mesh to bmesh vtable");
266
267         CustomData_copy(&me->vdata, &bm->vdata, CD_MASK_BMESH, CD_CALLOC, 0);
268         CustomData_copy(&me->edata, &bm->edata, CD_MASK_BMESH, CD_CALLOC, 0);
269         CustomData_copy(&me->ldata, &bm->ldata, CD_MASK_BMESH, CD_CALLOC, 0);
270         CustomData_copy(&me->pdata, &bm->pdata, CD_MASK_BMESH, CD_CALLOC, 0);
271
272         /* make sure uv layer names are consisten */
273         totuv = CustomData_number_of_layers(&bm->pdata, CD_MTEXPOLY);
274         for (i = 0; i < totuv; i++) {
275                 int li = CustomData_get_layer_index_n(&bm->pdata, CD_MTEXPOLY, i);
276                 CustomData_set_layer_name(&bm->ldata, CD_MLOOPUV, i, bm->pdata.layers[li].name);
277         }
278
279         if ((act_key_nr != 0) && (me->key != NULL)) {
280                 actkey = BLI_findlink(&me->key->block, act_key_nr - 1);
281         }
282         else {
283                 actkey = NULL;
284         }
285
286         if (me->key) {
287                 CustomData_add_layer(&bm->vdata, CD_SHAPE_KEYINDEX, CD_ASSIGN, NULL, 0);
288
289                 /* check if we need to generate unique ids for the shapekeys.
290                  * this also exists in the file reading code, but is here for
291                  * a sanity check */
292                 if (!me->key->uidgen) {
293                         fprintf(stderr,
294                                 "%s had to generate shape key uid's in a situation we shouldn't need to! "
295                                 "(bmesh internal error)\n",
296                                 __func__);
297
298                         me->key->uidgen = 1;
299                         for (block = me->key->block.first; block; block = block->next) {
300                                 block->uid = me->key->uidgen++;
301                         }
302                 }
303
304                 if (actkey && actkey->totelem == me->totvert) {
305                         keyco = actkey->data;
306                         bm->shapenr = act_key_nr;
307                 }
308
309                 for (i = 0, block = me->key->block.first; block; block = block->next, i++) {
310                         CustomData_add_layer_named(&bm->vdata, CD_SHAPEKEY,
311                                                    CD_ASSIGN, NULL, 0, block->name);
312
313                         j = CustomData_get_layer_index_n(&bm->vdata, CD_SHAPEKEY, i);
314                         bm->vdata.layers[j].uid = block->uid;
315                 }
316         }
317
318         CustomData_bmesh_init_pool(&bm->vdata, me->totvert, BM_VERT);
319         CustomData_bmesh_init_pool(&bm->edata, me->totedge, BM_EDGE);
320         CustomData_bmesh_init_pool(&bm->ldata, me->totloop, BM_LOOP);
321         CustomData_bmesh_init_pool(&bm->pdata, me->totpoly, BM_FACE);
322
323         BM_mesh_cd_flag_apply(bm, me->cd_flag);
324
325         cd_vert_bweight_offset = CustomData_get_offset(&bm->vdata, CD_BWEIGHT);
326         cd_edge_bweight_offset = CustomData_get_offset(&bm->edata, CD_BWEIGHT);
327         cd_edge_crease_offset  = CustomData_get_offset(&bm->edata, CD_CREASE);
328
329         for (i = 0, mvert = me->mvert; i < me->totvert; i++, mvert++) {
330                 v = vtable[i] = BM_vert_create(bm, keyco && set_key ? keyco[i] : mvert->co, NULL, BM_CREATE_SKIP_CD);
331                 BM_elem_index_set(v, i); /* set_ok */
332
333                 /* transfer flag */
334                 v->head.hflag = BM_vert_flag_from_mflag(mvert->flag & ~SELECT);
335
336                 /* this is necessary for selection counts to work properly */
337                 if (mvert->flag & SELECT) {
338                         BM_vert_select_set(bm, v, true);
339                 }
340
341                 normal_short_to_float_v3(v->no, mvert->no);
342
343                 /* Copy Custom Data */
344                 CustomData_to_bmesh_block(&me->vdata, &bm->vdata, i, &v->head.data, true);
345
346                 if (cd_vert_bweight_offset != -1) BM_ELEM_CD_SET_FLOAT(v, cd_vert_bweight_offset, (float)mvert->bweight / 255.0f);
347
348                 /* set shapekey data */
349                 if (me->key) {
350                         /* set shape key original index */
351                         keyi = CustomData_bmesh_get(&bm->vdata, v->head.data, CD_SHAPE_KEYINDEX);
352                         if (keyi) {
353                                 *keyi = i;
354                         }
355
356                         for (block = me->key->block.first, j = 0; block; block = block->next, j++) {
357                                 float *co = CustomData_bmesh_get_n(&bm->vdata, v->head.data, CD_SHAPEKEY, j);
358
359                                 if (co) {
360                                         copy_v3_v3(co, ((float *)block->data) + 3 * i);
361                                 }
362                         }
363                 }
364         }
365
366         bm->elem_index_dirty &= ~BM_VERT; /* added in order, clear dirty flag */
367
368         if (!me->totedge) {
369                 MEM_freeN(vtable);
370                 return;
371         }
372
373         etable = MEM_mallocN(sizeof(void **) * me->totedge, "mesh to bmesh etable");
374
375         medge = me->medge;
376         for (i = 0; i < me->totedge; i++, medge++) {
377                 e = etable[i] = BM_edge_create(bm, vtable[medge->v1], vtable[medge->v2], NULL, BM_CREATE_SKIP_CD);
378                 BM_elem_index_set(e, i); /* set_ok */
379
380                 /* transfer flags */
381                 e->head.hflag = BM_edge_flag_from_mflag(medge->flag & ~SELECT);
382
383                 /* this is necessary for selection counts to work properly */
384                 if (medge->flag & SELECT) {
385                         BM_edge_select_set(bm, e, true);
386                 }
387
388                 /* Copy Custom Data */
389                 CustomData_to_bmesh_block(&me->edata, &bm->edata, i, &e->head.data, true);
390
391                 if (cd_edge_bweight_offset != -1) BM_ELEM_CD_SET_FLOAT(e, cd_edge_bweight_offset, (float)medge->bweight / 255.0f);
392                 if (cd_edge_crease_offset  != -1) BM_ELEM_CD_SET_FLOAT(e, cd_edge_crease_offset,  (float)medge->crease  / 255.0f);
393
394         }
395
396         bm->elem_index_dirty &= ~BM_EDGE; /* added in order, clear dirty flag */
397
398         mloop = me->mloop;
399         mp = me->mpoly;
400         for (i = 0; i < me->totpoly; i++, mp++) {
401                 BMLoop *l_iter;
402                 BMLoop *l_first;
403
404                 f = bm_face_create_from_mpoly(mp, mloop + mp->loopstart,
405                                               bm, vtable, etable);
406
407                 if (UNLIKELY(f == NULL)) {
408                         printf("%s: Warning! Bad face in mesh"
409                                " \"%s\" at index %d!, skipping\n",
410                                __func__, me->id.name + 2, i);
411                         continue;
412                 }
413
414                 /* don't use 'i' since we may have skipped the face */
415                 BM_elem_index_set(f, bm->totface - 1); /* set_ok */
416
417                 /* transfer flag */
418                 f->head.hflag = BM_face_flag_from_mflag(mp->flag & ~ME_FACE_SEL);
419
420                 /* this is necessary for selection counts to work properly */
421                 if (mp->flag & ME_FACE_SEL) {
422                         BM_face_select_set(bm, f, true);
423                 }
424
425                 f->mat_nr = mp->mat_nr;
426                 if (i == me->act_face) bm->act_face = f;
427
428                 j = mp->loopstart;
429                 l_iter = l_first = BM_FACE_FIRST_LOOP(f);
430                 do {
431                         /* Save index of correspsonding MLoop */
432                         CustomData_to_bmesh_block(&me->ldata, &bm->ldata, j++, &l_iter->head.data, true);
433                 } while ((l_iter = l_iter->next) != l_first);
434
435                 /* Copy Custom Data */
436                 CustomData_to_bmesh_block(&me->pdata, &bm->pdata, i, &f->head.data, true);
437
438                 if (calc_face_normal) {
439                         BM_face_normal_update(f);
440                 }
441         }
442
443         bm->elem_index_dirty &= ~BM_FACE; /* added in order, clear dirty flag */
444         bm->elem_index_dirty |= BM_LOOP; /* did not set the loop indices */
445
446         if (me->mselect && me->totselect != 0) {
447
448                 BMVert **vert_array = MEM_mallocN(sizeof(BMVert *) * bm->totvert, "VSelConv");
449                 BMEdge **edge_array = MEM_mallocN(sizeof(BMEdge *) * bm->totedge, "ESelConv");
450                 BMFace **face_array = MEM_mallocN(sizeof(BMFace *) * bm->totface, "FSelConv");
451                 MSelect *msel;
452
453 #pragma omp parallel sections if (bm->totvert + bm->totedge + bm->totface >= BM_OMP_LIMIT)
454                 {
455 #pragma omp section
456                         { BM_iter_as_array(bm, BM_VERTS_OF_MESH, NULL, (void **)vert_array, bm->totvert); }
457 #pragma omp section
458                         { BM_iter_as_array(bm, BM_EDGES_OF_MESH, NULL, (void **)edge_array, bm->totedge); }
459 #pragma omp section
460                         { BM_iter_as_array(bm, BM_FACES_OF_MESH, NULL, (void **)face_array, bm->totface); }
461                 }
462
463                 for (i = 0, msel = me->mselect; i < me->totselect; i++, msel++) {
464                         switch (msel->type) {
465                                 case ME_VSEL:
466                                         BM_select_history_store(bm, (BMElem *)vert_array[msel->index]);
467                                         break;
468                                 case ME_ESEL:
469                                         BM_select_history_store(bm, (BMElem *)edge_array[msel->index]);
470                                         break;
471                                 case ME_FSEL:
472                                         BM_select_history_store(bm, (BMElem *)face_array[msel->index]);
473                                         break;
474                         }
475                 }
476
477                 MEM_freeN(vert_array);
478                 MEM_freeN(edge_array);
479                 MEM_freeN(face_array);
480         }
481         else {
482                 me->totselect = 0;
483                 if (me->mselect) {
484                         MEM_freeN(me->mselect);
485                         me->mselect = NULL;
486                 }
487         }
488
489         MEM_freeN(vtable);
490         MEM_freeN(etable);
491 }
492
493
494 /**
495  * \brief BMesh -> Mesh
496  */
497 static BMVert **bm_to_mesh_vertex_map(BMesh *bm, int ototvert)
498 {
499         BMVert **vertMap = NULL;
500         BMVert *eve;
501         int index;
502         int i = 0;
503         BMIter iter;
504
505         /* caller needs to ensure this */
506         BLI_assert(ototvert > 0);
507
508         vertMap = MEM_callocN(sizeof(*vertMap) * ototvert, "vertMap");
509         if (CustomData_has_layer(&bm->vdata, CD_SHAPE_KEYINDEX)) {
510                 int *keyi;
511                 BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
512                         keyi = CustomData_bmesh_get(&bm->vdata, eve->head.data, CD_SHAPE_KEYINDEX);
513                         if (keyi) {
514                                 if (((index = *keyi) != ORIGINDEX_NONE) && (index < ototvert)) {
515                                         vertMap[index] = eve;
516                                 }
517                         }
518                         else {
519                                 if (i < ototvert) {
520                                         vertMap[i] = eve;
521                                 }
522                         }
523                         i++;
524                 }
525         }
526         else {
527                 BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
528                         if (i < ototvert) {
529                                 vertMap[i] = eve;
530                         }
531                         else {
532                                 break;
533                         }
534                         i++;
535                 }
536         }
537
538         return vertMap;
539 }
540
541 /**
542  * returns customdata shapekey index from a keyblock or -1
543  * \note could split this out into a more generic function */
544 static int bm_to_mesh_shape_layer_index_from_kb(BMesh *bm, KeyBlock *currkey)
545 {
546         int i;
547         int j = 0;
548
549         for (i = 0; i < bm->vdata.totlayer; i++) {
550                 if (bm->vdata.layers[i].type == CD_SHAPEKEY) {
551                         if (currkey->uid == bm->vdata.layers[i].uid) {
552                                 return j;
553                         }
554                         j++;
555                 }
556         }
557         return -1;
558 }
559
560 BLI_INLINE void bmesh_quick_edgedraw_flag(MEdge *med, BMEdge *e)
561 {
562         /* this is a cheap way to set the edge draw, its not precise and will
563          * pick the first 2 faces an edge uses.
564          * The dot comparison is a little arbitrary, but set so that a 5 subd
565          * IcoSphere won't vanish but subd 6 will (as with pre-bmesh blender) */
566
567
568         if ( /* (med->flag & ME_EDGEDRAW) && */ /* assume to be true */
569              (e->l && (e->l != e->l->radial_next)) &&
570              (dot_v3v3(e->l->f->no, e->l->radial_next->f->no) > 0.9995f))
571         {
572                 med->flag &= ~ME_EDGEDRAW;
573         }
574         else {
575                 med->flag |= ME_EDGEDRAW;
576         }
577 }
578
579 void BM_mesh_bm_to_me(BMesh *bm, Mesh *me, bool do_tessface)
580 {
581         MLoop *mloop;
582         MPoly *mpoly;
583         MVert *mvert, *oldverts;
584         MEdge *med, *medge;
585         BMVert *v, *eve;
586         BMEdge *e;
587         BMFace *f;
588         BMIter iter;
589         int i, j, ototvert;
590
591         const int cd_vert_bweight_offset = CustomData_get_offset(&bm->vdata, CD_BWEIGHT);
592         const int cd_edge_bweight_offset = CustomData_get_offset(&bm->edata, CD_BWEIGHT);
593         const int cd_edge_crease_offset  = CustomData_get_offset(&bm->edata, CD_CREASE);
594
595         ototvert = me->totvert;
596
597         /* new vertex block */
598         if (bm->totvert == 0) mvert = NULL;
599         else mvert = MEM_callocN(bm->totvert * sizeof(MVert), "loadeditbMesh vert");
600
601         /* new edge block */
602         if (bm->totedge == 0) medge = NULL;
603         else medge = MEM_callocN(bm->totedge * sizeof(MEdge), "loadeditbMesh edge");
604
605         /* new ngon face block */
606         if (bm->totface == 0) mpoly = NULL;
607         else mpoly = MEM_callocN(bm->totface * sizeof(MPoly), "loadeditbMesh poly");
608
609         /* new loop block */
610         if (bm->totloop == 0) mloop = NULL;
611         else mloop = MEM_callocN(bm->totloop * sizeof(MLoop), "loadeditbMesh loop");
612
613         /* lets save the old verts just in case we are actually working on
614          * a key ... we now do processing of the keys at the end */
615         oldverts = me->mvert;
616
617         /* don't free this yet */
618         if (oldverts) {
619                 CustomData_set_layer(&me->vdata, CD_MVERT, NULL);
620         }
621
622         /* free custom data */
623         CustomData_free(&me->vdata, me->totvert);
624         CustomData_free(&me->edata, me->totedge);
625         CustomData_free(&me->fdata, me->totface);
626         CustomData_free(&me->ldata, me->totloop);
627         CustomData_free(&me->pdata, me->totpoly);
628
629         /* add new custom data */
630         me->totvert = bm->totvert;
631         me->totedge = bm->totedge;
632         me->totloop = bm->totloop;
633         me->totpoly = bm->totface;
634         /* will be overwritten with a valid value if 'dotess' is set, otherwise we
635          * end up with 'me->totface' and me->mface == NULL which can crash [#28625]
636          */
637         me->totface = 0;
638         me->act_face = -1;
639
640         CustomData_copy(&bm->vdata, &me->vdata, CD_MASK_MESH, CD_CALLOC, me->totvert);
641         CustomData_copy(&bm->edata, &me->edata, CD_MASK_MESH, CD_CALLOC, me->totedge);
642         CustomData_copy(&bm->ldata, &me->ldata, CD_MASK_MESH, CD_CALLOC, me->totloop);
643         CustomData_copy(&bm->pdata, &me->pdata, CD_MASK_MESH, CD_CALLOC, me->totpoly);
644
645         CustomData_add_layer(&me->vdata, CD_MVERT, CD_ASSIGN, mvert, me->totvert);
646         CustomData_add_layer(&me->edata, CD_MEDGE, CD_ASSIGN, medge, me->totedge);
647         CustomData_add_layer(&me->ldata, CD_MLOOP, CD_ASSIGN, mloop, me->totloop);
648         CustomData_add_layer(&me->pdata, CD_MPOLY, CD_ASSIGN, mpoly, me->totpoly);
649
650         me->cd_flag = BM_mesh_cd_flag_from_bmesh(bm);
651
652         /* this is called again, 'dotess' arg is used there */
653         BKE_mesh_update_customdata_pointers(me, 0);
654
655         i = 0;
656         BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
657                 copy_v3_v3(mvert->co, v->co);
658                 normal_float_to_short_v3(mvert->no, v->no);
659
660                 mvert->flag = BM_vert_flag_to_mflag(v);
661
662                 BM_elem_index_set(v, i); /* set_inline */
663
664                 /* copy over customdat */
665                 CustomData_from_bmesh_block(&bm->vdata, &me->vdata, v->head.data, i);
666
667                 if (cd_vert_bweight_offset != -1) mvert->bweight = BM_ELEM_CD_GET_FLOAT_AS_UCHAR(v, cd_vert_bweight_offset);
668
669                 i++;
670                 mvert++;
671
672                 BM_CHECK_ELEMENT(v);
673         }
674         bm->elem_index_dirty &= ~BM_VERT;
675
676         med = medge;
677         i = 0;
678         BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
679                 med->v1 = BM_elem_index_get(e->v1);
680                 med->v2 = BM_elem_index_get(e->v2);
681
682                 med->flag = BM_edge_flag_to_mflag(e);
683
684                 BM_elem_index_set(e, i); /* set_inline */
685
686                 /* copy over customdata */
687                 CustomData_from_bmesh_block(&bm->edata, &me->edata, e->head.data, i);
688
689                 bmesh_quick_edgedraw_flag(med, e);
690
691                 if (cd_edge_crease_offset  != -1) med->crease  = BM_ELEM_CD_GET_FLOAT_AS_UCHAR(e, cd_edge_crease_offset);
692                 if (cd_edge_bweight_offset != -1) med->bweight = BM_ELEM_CD_GET_FLOAT_AS_UCHAR(e, cd_edge_bweight_offset);
693
694                 i++;
695                 med++;
696                 BM_CHECK_ELEMENT(e);
697         }
698         bm->elem_index_dirty &= ~BM_EDGE;
699
700         i = 0;
701         j = 0;
702         BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
703                 BMLoop *l_iter, *l_first;
704                 mpoly->loopstart = j;
705                 mpoly->totloop = f->len;
706                 mpoly->mat_nr = f->mat_nr;
707                 mpoly->flag = BM_face_flag_to_mflag(f);
708
709                 l_iter = l_first = BM_FACE_FIRST_LOOP(f);
710                 do {
711                         mloop->e = BM_elem_index_get(l_iter->e);
712                         mloop->v = BM_elem_index_get(l_iter->v);
713
714                         /* copy over customdata */
715                         CustomData_from_bmesh_block(&bm->ldata, &me->ldata, l_iter->head.data, j);
716
717                         j++;
718                         mloop++;
719                         BM_CHECK_ELEMENT(l_iter);
720                         BM_CHECK_ELEMENT(l_iter->e);
721                         BM_CHECK_ELEMENT(l_iter->v);
722                 } while ((l_iter = l_iter->next) != l_first);
723
724                 if (f == bm->act_face) me->act_face = i;
725
726                 /* copy over customdata */
727                 CustomData_from_bmesh_block(&bm->pdata, &me->pdata, f->head.data, i);
728
729                 i++;
730                 mpoly++;
731                 BM_CHECK_ELEMENT(f);
732         }
733
734         /* patch hook indices and vertex parents */
735         if (ototvert > 0) {
736                 Object *ob;
737                 ModifierData *md;
738                 BMVert **vertMap = NULL;
739                 int i, j;
740
741                 for (ob = G.main->object.first; ob; ob = ob->id.next) {
742                         if ((ob->parent) && (ob->parent->data == me) && ELEM(ob->partype, PARVERT1, PARVERT3)) {
743
744                                 if (vertMap == NULL) {
745                                         vertMap = bm_to_mesh_vertex_map(bm, ototvert);
746                                 }
747
748                                 if (ob->par1 < ototvert) {
749                                         eve = vertMap[ob->par1];
750                                         if (eve) ob->par1 = BM_elem_index_get(eve);
751                                 }
752                                 if (ob->par2 < ototvert) {
753                                         eve = vertMap[ob->par2];
754                                         if (eve) ob->par2 = BM_elem_index_get(eve);
755                                 }
756                                 if (ob->par3 < ototvert) {
757                                         eve = vertMap[ob->par3];
758                                         if (eve) ob->par3 = BM_elem_index_get(eve);
759                                 }
760
761                         }
762                         if (ob->data == me) {
763                                 for (md = ob->modifiers.first; md; md = md->next) {
764                                         if (md->type == eModifierType_Hook) {
765                                                 HookModifierData *hmd = (HookModifierData *) md;
766
767                                                 if (vertMap == NULL) {
768                                                         vertMap = bm_to_mesh_vertex_map(bm, ototvert);
769                                                 }
770
771                                                 for (i = j = 0; i < hmd->totindex; i++) {
772                                                         if (hmd->indexar[i] < ototvert) {
773                                                                 eve = vertMap[hmd->indexar[i]];
774
775                                                                 if (eve) {
776                                                                         hmd->indexar[j++] = BM_elem_index_get(eve);
777                                                                 }
778                                                         }
779                                                         else {
780                                                                 j++;
781                                                         }
782                                                 }
783
784                                                 hmd->totindex = j;
785                                         }
786                                 }
787                         }
788                 }
789
790                 if (vertMap) MEM_freeN(vertMap);
791         }
792
793         if (do_tessface) {
794                 BKE_mesh_tessface_calc(me);
795         }
796
797         BKE_mesh_update_customdata_pointers(me, do_tessface);
798
799         {
800                 BMEditSelection *selected;
801                 me->totselect = BLI_countlist(&(bm->selected));
802
803                 if (me->mselect) MEM_freeN(me->mselect);
804
805                 me->mselect = MEM_callocN(sizeof(MSelect) * me->totselect, "Mesh selection history");
806
807
808                 for (i = 0, selected = bm->selected.first; selected; i++, selected = selected->next) {
809                         if (selected->htype == BM_VERT) {
810                                 me->mselect[i].type = ME_VSEL;
811
812                         }
813                         else if (selected->htype == BM_EDGE) {
814                                 me->mselect[i].type = ME_ESEL;
815
816                         }
817                         else if (selected->htype == BM_FACE) {
818                                 me->mselect[i].type = ME_FSEL;
819                         }
820
821                         me->mselect[i].index = BM_elem_index_get(selected->ele);
822                 }
823         }
824
825         /* see comment below, this logic is in twice */
826
827         if (me->key) {
828                 KeyBlock *currkey;
829                 KeyBlock *actkey = BLI_findlink(&me->key->block, bm->shapenr - 1);
830
831                 float (*ofs)[3] = NULL;
832
833                 /* go through and find any shapekey customdata layers
834                  * that might not have corresponding KeyBlocks, and add them if
835                  * necessary */
836                 j = 0;
837                 for (i = 0; i < bm->vdata.totlayer; i++) {
838                         if (bm->vdata.layers[i].type != CD_SHAPEKEY)
839                                 continue;
840
841                         for (currkey = me->key->block.first; currkey; currkey = currkey->next) {
842                                 if (currkey->uid == bm->vdata.layers[i].uid)
843                                         break;
844                         }
845
846                         if (!currkey) {
847                                 currkey = BKE_keyblock_add(me->key, bm->vdata.layers[i].name);
848                                 currkey->uid = bm->vdata.layers[i].uid;
849                         }
850
851                         j++;
852                 }
853
854
855                 /* editing the base key should update others */
856                 if ((me->key->type == KEY_RELATIVE) && /* only need offsets for relative shape keys */
857                     (actkey != NULL) &&                /* unlikely, but the active key may not be valid if the
858                                                         * bmesh and the mesh are out of sync */
859                     (oldverts != NULL))                /* not used here, but 'oldverts' is used later for applying 'ofs' */
860                 {
861                         bool act_is_basis = false;
862
863                         /* find if this key is a basis for any others */
864                         for (currkey = me->key->block.first; currkey; currkey = currkey->next) {
865                                 if (bm->shapenr - 1 == currkey->relative) {
866                                         act_is_basis = true;
867                                         break;
868                                 }
869                         }
870
871                         if (act_is_basis) { /* active key is a base */
872                                 float (*fp)[3] = actkey->data;
873                                 int *keyi;
874
875                                 ofs = MEM_callocN(sizeof(float) * 3 * bm->totvert,  "currkey->data");
876                                 mvert = me->mvert;
877                                 BM_ITER_MESH_INDEX (eve, &iter, bm, BM_VERTS_OF_MESH, i) {
878                                         keyi = CustomData_bmesh_get(&bm->vdata, eve->head.data, CD_SHAPE_KEYINDEX);
879                                         if (keyi && *keyi != ORIGINDEX_NONE) {
880                                                 sub_v3_v3v3(ofs[i], mvert->co, fp[*keyi]);
881                                         }
882                                         else {
883                                                 /* if there are new vertices in the mesh, we can't propagate the offset
884                                                  * because it will only work for the existing vertices and not the new
885                                                  * ones, creating a mess when doing e.g. subdivide + translate */
886                                                 MEM_freeN(ofs);
887                                                 ofs = NULL;
888                                                 break;
889                                         }
890
891                                         mvert++;
892                                 }
893                         }
894                 }
895
896                 for (currkey = me->key->block.first; currkey; currkey = currkey->next) {
897                         int apply_offset = (ofs && (currkey != actkey) && (bm->shapenr - 1 == currkey->relative));
898                         int *keyi;
899                         float (*ofs_pt)[3] = ofs;
900                         float *newkey, *oldkey, *fp;
901
902                         j = bm_to_mesh_shape_layer_index_from_kb(bm, currkey);
903
904
905                         fp = newkey = MEM_callocN(me->key->elemsize * bm->totvert,  "currkey->data");
906                         oldkey = currkey->data;
907
908                         mvert = me->mvert;
909                         BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
910
911                                 if (currkey == actkey) {
912                                         copy_v3_v3(fp, eve->co);
913
914                                         if (actkey != me->key->refkey) { /* important see bug [#30771] */
915                                                 if (oldverts) {
916                                                         keyi = CustomData_bmesh_get(&bm->vdata, eve->head.data, CD_SHAPE_KEYINDEX);
917                                                         if (*keyi != ORIGINDEX_NONE && *keyi < currkey->totelem) { /* valid old vertex */
918                                                                 copy_v3_v3(mvert->co, oldverts[*keyi].co);
919                                                         }
920                                                 }
921                                         }
922                                 }
923                                 else if (j != -1) {
924                                         /* in most cases this runs */
925                                         copy_v3_v3(fp, CustomData_bmesh_get_n(&bm->vdata, eve->head.data, CD_SHAPEKEY, j));
926                                 }
927                                 else if (oldkey &&
928                                          (keyi = CustomData_bmesh_get(&bm->vdata, eve->head.data, CD_SHAPE_KEYINDEX)) &&
929                                          (*keyi != ORIGINDEX_NONE && *keyi < currkey->totelem))
930                                 {
931                                         /* old method of reconstructing keys via vertice's original key indices,
932                                          * currently used if the new method above fails (which is theoretically
933                                          * possible in certain cases of undo) */
934                                         copy_v3_v3(fp, &oldkey[3 * (*keyi)]);
935                                 }
936                                 else {
937                                         /* fail! fill in with dummy value */
938                                         copy_v3_v3(fp, mvert->co);
939                                 }
940
941                                 /* propagate edited basis offsets to other shapes */
942                                 if (apply_offset) {
943                                         add_v3_v3(fp, *ofs_pt++);
944                                 }
945
946                                 fp += 3;
947                                 mvert++;
948                         }
949
950                         currkey->totelem = bm->totvert;
951                         if (currkey->data) {
952                                 MEM_freeN(currkey->data);
953                         }
954                         currkey->data = newkey;
955                 }
956
957                 if (ofs) MEM_freeN(ofs);
958         }
959
960         if (oldverts) MEM_freeN(oldverts);
961
962         /* topology could be changed, ensure mdisps are ok */
963         multires_topology_changed(me);
964 }