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