BMesh: backport minor changes from 2.8
[blender.git] / source / blender / bmesh / intern / bmesh_mesh.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.c
24  *  \ingroup bmesh
25  *
26  * BM mesh level functions.
27  */
28
29 #include "MEM_guardedalloc.h"
30
31 #include "DNA_listBase.h"
32 #include "DNA_object_types.h"
33
34 #include "BLI_linklist_stack.h"
35 #include "BLI_listbase.h"
36 #include "BLI_math.h"
37 #include "BLI_stack.h"
38 #include "BLI_task.h"
39 #include "BLI_utildefines.h"
40
41 #include "BKE_cdderivedmesh.h"
42 #include "BKE_editmesh.h"
43 #include "BKE_mesh.h"
44 #include "BKE_multires.h"
45
46 #include "atomic_ops.h"
47
48 #include "intern/bmesh_private.h"
49
50 /* used as an extern, defined in bmesh.h */
51 const BMAllocTemplate bm_mesh_allocsize_default = {512, 1024, 2048, 512};
52 const BMAllocTemplate bm_mesh_chunksize_default = {512, 1024, 2048, 512};
53
54 static void bm_mempool_init_ex(
55         const BMAllocTemplate *allocsize, const bool use_toolflags,
56         BLI_mempool **r_vpool, BLI_mempool **r_epool, BLI_mempool **r_lpool, BLI_mempool **r_fpool)
57 {
58         size_t vert_size, edge_size, loop_size, face_size;
59
60         if (use_toolflags == true) {
61                 vert_size = sizeof(BMVert_OFlag);
62                 edge_size = sizeof(BMEdge_OFlag);
63                 loop_size = sizeof(BMLoop);
64                 face_size = sizeof(BMFace_OFlag);
65         }
66         else {
67                 vert_size = sizeof(BMVert);
68                 edge_size = sizeof(BMEdge);
69                 loop_size = sizeof(BMLoop);
70                 face_size = sizeof(BMFace);
71         }
72
73         if (r_vpool) {
74                 *r_vpool = BLI_mempool_create(
75                         vert_size, allocsize->totvert,
76                         bm_mesh_chunksize_default.totvert, BLI_MEMPOOL_ALLOW_ITER);
77         }
78         if (r_epool) {
79                 *r_epool = BLI_mempool_create(
80                         edge_size, allocsize->totedge,
81                         bm_mesh_chunksize_default.totedge, BLI_MEMPOOL_ALLOW_ITER);
82         }
83         if (r_lpool) {
84                 *r_lpool = BLI_mempool_create(
85                         loop_size, allocsize->totloop,
86                         bm_mesh_chunksize_default.totloop, BLI_MEMPOOL_NOP);
87         }
88         if (r_fpool) {
89                 *r_fpool = BLI_mempool_create(
90                         face_size, allocsize->totface,
91                         bm_mesh_chunksize_default.totface, BLI_MEMPOOL_ALLOW_ITER);
92         }
93 }
94
95 static void bm_mempool_init(BMesh *bm, const BMAllocTemplate *allocsize, const bool use_toolflags)
96 {
97         bm_mempool_init_ex(
98                 allocsize, use_toolflags,
99                 &bm->vpool, &bm->epool, &bm->lpool, &bm->fpool);
100
101 #ifdef USE_BMESH_HOLES
102         bm->looplistpool = BLI_mempool_create(sizeof(BMLoopList), 512, 512, BLI_MEMPOOL_NOP);
103 #endif
104 }
105
106 void BM_mesh_elem_toolflags_ensure(BMesh *bm)
107 {
108         BLI_assert(bm->use_toolflags);
109
110         if (bm->vtoolflagpool && bm->etoolflagpool && bm->ftoolflagpool) {
111                 return;
112         }
113
114         bm->vtoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer), bm->totvert, 512, BLI_MEMPOOL_NOP);
115         bm->etoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer), bm->totedge, 512, BLI_MEMPOOL_NOP);
116         bm->ftoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer), bm->totface, 512, BLI_MEMPOOL_NOP);
117
118         BMIter iter;
119         BMVert_OFlag *v_olfag;
120         BLI_mempool *toolflagpool = bm->vtoolflagpool;
121         BM_ITER_MESH (v_olfag, &iter, bm, BM_VERTS_OF_MESH) {
122                 v_olfag->oflags = BLI_mempool_calloc(toolflagpool);
123         }
124
125         BMEdge_OFlag *e_olfag;
126         toolflagpool = bm->etoolflagpool;
127         BM_ITER_MESH (e_olfag, &iter, bm, BM_EDGES_OF_MESH) {
128                 e_olfag->oflags = BLI_mempool_calloc(toolflagpool);
129         }
130
131         BMFace_OFlag *f_olfag;
132         toolflagpool = bm->ftoolflagpool;
133         BM_ITER_MESH (f_olfag, &iter, bm, BM_FACES_OF_MESH) {
134                 f_olfag->oflags = BLI_mempool_calloc(toolflagpool);
135         }
136
137         bm->totflags = 1;
138 }
139
140 void BM_mesh_elem_toolflags_clear(BMesh *bm)
141 {
142         if (bm->vtoolflagpool) {
143                 BLI_mempool_destroy(bm->vtoolflagpool);
144                 bm->vtoolflagpool = NULL;
145         }
146         if (bm->etoolflagpool) {
147                 BLI_mempool_destroy(bm->etoolflagpool);
148                 bm->etoolflagpool = NULL;
149         }
150         if (bm->ftoolflagpool) {
151                 BLI_mempool_destroy(bm->ftoolflagpool);
152                 bm->ftoolflagpool = NULL;
153         }
154 }
155
156 /**
157  * \brief BMesh Make Mesh
158  *
159  * Allocates a new BMesh structure.
160  *
161  * \return The New bmesh
162  *
163  * \note ob is needed by multires
164  */
165 BMesh *BM_mesh_create(
166         const BMAllocTemplate *allocsize,
167         const struct BMeshCreateParams *params)
168 {
169         /* allocate the structure */
170         BMesh *bm = MEM_callocN(sizeof(BMesh), __func__);
171
172         /* allocate the memory pools for the mesh elements */
173         bm_mempool_init(bm, allocsize, params->use_toolflags);
174
175         /* allocate one flag pool that we don't get rid of. */
176         bm->use_toolflags = params->use_toolflags;
177         bm->toolflag_index = 0;
178         bm->totflags = 0;
179
180         CustomData_reset(&bm->vdata);
181         CustomData_reset(&bm->edata);
182         CustomData_reset(&bm->ldata);
183         CustomData_reset(&bm->pdata);
184
185         return bm;
186 }
187
188 /**
189  * \brief BMesh Free Mesh Data
190  *
191  *      Frees a BMesh structure.
192  *
193  * \note frees mesh, but not actual BMesh struct
194  */
195 void BM_mesh_data_free(BMesh *bm)
196 {
197         BMVert *v;
198         BMEdge *e;
199         BMLoop *l;
200         BMFace *f;
201
202         BMIter iter;
203         BMIter itersub;
204
205         const bool is_ldata_free = CustomData_bmesh_has_free(&bm->ldata);
206         const bool is_pdata_free = CustomData_bmesh_has_free(&bm->pdata);
207
208         /* Check if we have to call free, if not we can avoid a lot of looping */
209         if (CustomData_bmesh_has_free(&(bm->vdata))) {
210                 BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
211                         CustomData_bmesh_free_block(&(bm->vdata), &(v->head.data));
212                 }
213         }
214         if (CustomData_bmesh_has_free(&(bm->edata))) {
215                 BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
216                         CustomData_bmesh_free_block(&(bm->edata), &(e->head.data));
217                 }
218         }
219
220         if (is_ldata_free || is_pdata_free) {
221                 BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
222                         if (is_pdata_free)
223                                 CustomData_bmesh_free_block(&(bm->pdata), &(f->head.data));
224                         if (is_ldata_free) {
225                                 BM_ITER_ELEM (l, &itersub, f, BM_LOOPS_OF_FACE) {
226                                         CustomData_bmesh_free_block(&(bm->ldata), &(l->head.data));
227                                 }
228                         }
229                 }
230         }
231
232         /* Free custom data pools, This should probably go in CustomData_free? */
233         if (bm->vdata.totlayer) BLI_mempool_destroy(bm->vdata.pool);
234         if (bm->edata.totlayer) BLI_mempool_destroy(bm->edata.pool);
235         if (bm->ldata.totlayer) BLI_mempool_destroy(bm->ldata.pool);
236         if (bm->pdata.totlayer) BLI_mempool_destroy(bm->pdata.pool);
237
238         /* free custom data */
239         CustomData_free(&bm->vdata, 0);
240         CustomData_free(&bm->edata, 0);
241         CustomData_free(&bm->ldata, 0);
242         CustomData_free(&bm->pdata, 0);
243
244         /* destroy element pools */
245         BLI_mempool_destroy(bm->vpool);
246         BLI_mempool_destroy(bm->epool);
247         BLI_mempool_destroy(bm->lpool);
248         BLI_mempool_destroy(bm->fpool);
249
250         if (bm->vtable) MEM_freeN(bm->vtable);
251         if (bm->etable) MEM_freeN(bm->etable);
252         if (bm->ftable) MEM_freeN(bm->ftable);
253
254         /* destroy flag pool */
255         BM_mesh_elem_toolflags_clear(bm);
256
257 #ifdef USE_BMESH_HOLES
258         BLI_mempool_destroy(bm->looplistpool);
259 #endif
260
261         BLI_freelistN(&bm->selected);
262
263         BMO_error_clear(bm);
264 }
265
266 /**
267  * \brief BMesh Clear Mesh
268  *
269  * Clear all data in bm
270  */
271 void BM_mesh_clear(BMesh *bm)
272 {
273         const bool use_toolflags = bm->use_toolflags;
274
275         /* free old mesh */
276         BM_mesh_data_free(bm);
277         memset(bm, 0, sizeof(BMesh));
278
279         /* allocate the memory pools for the mesh elements */
280         bm_mempool_init(bm, &bm_mesh_allocsize_default, use_toolflags);
281
282         bm->use_toolflags = use_toolflags;
283         bm->toolflag_index = 0;
284         bm->totflags = 0;
285
286         CustomData_reset(&bm->vdata);
287         CustomData_reset(&bm->edata);
288         CustomData_reset(&bm->ldata);
289         CustomData_reset(&bm->pdata);
290 }
291
292 /**
293  * \brief BMesh Free Mesh
294  *
295  *      Frees a BMesh data and its structure.
296  */
297 void BM_mesh_free(BMesh *bm)
298 {
299         BM_mesh_data_free(bm);
300
301         if (bm->py_handle) {
302                 /* keep this out of 'BM_mesh_data_free' because we want python
303                  * to be able to clear the mesh and maintain access. */
304                 bpy_bm_generic_invalidate(bm->py_handle);
305                 bm->py_handle = NULL;
306         }
307
308         MEM_freeN(bm);
309 }
310
311
312 /**
313  * Helpers for #BM_mesh_normals_update and #BM_verts_calc_normal_vcos
314  */
315
316 typedef struct BMEdgesCalcVectorsData {
317         /* Read-only data. */
318         const float (*vcos)[3];
319
320         /* Read-write data, but no need to protect it, no concurrency to fear here. */
321         float (*edgevec)[3];
322 } BMEdgesCalcVectorsData;
323
324
325 static void mesh_edges_calc_vectors_cb(void *userdata, MempoolIterData *mp_e)
326 {
327         BMEdgesCalcVectorsData *data = userdata;
328         BMEdge *e = (BMEdge *)mp_e;
329
330         if (e->l) {
331                 const float *v1_co = data->vcos ? data->vcos[BM_elem_index_get(e->v1)] : e->v1->co;
332                 const float *v2_co = data->vcos ? data->vcos[BM_elem_index_get(e->v2)] : e->v2->co;
333                 sub_v3_v3v3(data->edgevec[BM_elem_index_get(e)], v2_co, v1_co);
334                 normalize_v3(data->edgevec[BM_elem_index_get(e)]);
335         }
336         else {
337                 /* the edge vector will not be needed when the edge has no radial */
338         }
339 }
340
341 static void bm_mesh_edges_calc_vectors(BMesh *bm, float (*edgevec)[3], const float (*vcos)[3])
342 {
343         BM_mesh_elem_index_ensure(bm, BM_EDGE | (vcos ?  BM_VERT : 0));
344
345         BMEdgesCalcVectorsData data = {
346             .vcos = vcos,
347             .edgevec = edgevec
348         };
349
350         BM_iter_parallel(bm, BM_EDGES_OF_MESH, mesh_edges_calc_vectors_cb, &data, bm->totedge >= BM_OMP_LIMIT);
351 }
352
353
354 typedef struct BMVertsCalcNormalsData {
355         /* Read-only data. */
356         const float (*fnos)[3];
357         const float (*edgevec)[3];
358         const float (*vcos)[3];
359
360         /* Read-write data, protected by an atomic-based fake spinlock-like system... */
361         float (*vnos)[3];
362 } BMVertsCalcNormalsData;
363
364 static void mesh_verts_calc_normals_accum_cb(void *userdata, MempoolIterData *mp_f)
365 {
366         BMVertsCalcNormalsData *data = userdata;
367         BMFace *f = (BMFace *)mp_f;
368
369         const float *f_no = data->fnos ? data->fnos[BM_elem_index_get(f)] : f->no;
370
371         BMLoop *l_first, *l_iter;
372         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
373         do {
374                 const float *e1diff, *e2diff;
375                 float dotprod;
376                 float fac;
377
378                 /* calculate the dot product of the two edges that
379                  * meet at the loop's vertex */
380                 e1diff = data->edgevec[BM_elem_index_get(l_iter->prev->e)];
381                 e2diff = data->edgevec[BM_elem_index_get(l_iter->e)];
382                 dotprod = dot_v3v3(e1diff, e2diff);
383
384                 /* edge vectors are calculated from e->v1 to e->v2, so
385                  * adjust the dot product if one but not both loops
386                  * actually runs from from e->v2 to e->v1 */
387                 if ((l_iter->prev->e->v1 == l_iter->prev->v) ^ (l_iter->e->v1 == l_iter->v)) {
388                         dotprod = -dotprod;
389                 }
390
391                 fac = saacos(-dotprod);
392
393                 /* accumulate weighted face normal into the vertex's normal */
394                 float *v_no = data->vnos ? data->vnos[BM_elem_index_get(l_iter->v)] : l_iter->v->no;
395
396                 /* This block is a lockless threadsafe madd_v3_v3fl.
397                  * It uses the first float of the vector as a sort of cheap spinlock,
398                  * assuming FLT_MAX is a safe 'illegal' value that cannot be set here otherwise.
399                  * It also assumes that collisions between threads are highly unlikely,
400                  * else performances would be quite bad here. */
401                 float virtual_lock = v_no[0];
402                 while (true) {
403                         /* This loops until following conditions are met:
404                          *   - v_no[0] has same value as virtual_lock (i.e. it did not change since last try).
405                          *   - v_no[0] was not FLT_MAX, i.e. it was not locked by another thread.
406                          */
407                         const float vl = atomic_cas_float(&v_no[0], virtual_lock, FLT_MAX);
408                         if (vl == virtual_lock && vl != FLT_MAX) {
409                                 break;
410                         }
411                         virtual_lock = vl;
412                 }
413                 BLI_assert(v_no[0] == FLT_MAX);
414                 /* Now we own that normal value, and can change it.
415                  * But first scalar of the vector must not be changed yet, it's our lock! */
416                 virtual_lock += f_no[0] * fac;
417                 v_no[1] += f_no[1] * fac;
418                 v_no[2] += f_no[2] * fac;
419                 /* Second atomic operation to 'release' our lock on that vector and set its first scalar value. */
420                 /* Note that we do not need to loop here, since we 'locked' v_no[0],
421                  * nobody should have changed it in the mean time. */
422                 virtual_lock = atomic_cas_float(&v_no[0], FLT_MAX, virtual_lock);
423                 BLI_assert(virtual_lock == FLT_MAX);
424
425         } while ((l_iter = l_iter->next) != l_first);
426 }
427
428 static void mesh_verts_calc_normals_normalize_cb(void *userdata, MempoolIterData *mp_v)
429 {
430         BMVertsCalcNormalsData *data = userdata;
431         BMVert *v = (BMVert *)mp_v;
432
433         float *v_no = data->vnos ? data->vnos[BM_elem_index_get(v)] : v->no;
434         if (UNLIKELY(normalize_v3(v_no) == 0.0f)) {
435                 const float *v_co = data->vcos ? data->vcos[BM_elem_index_get(v)] : v->co;
436                 normalize_v3_v3(v_no, v_co);
437         }
438 }
439
440 static void bm_mesh_verts_calc_normals(
441         BMesh *bm, const float (*edgevec)[3], const float (*fnos)[3],
442         const float (*vcos)[3], float (*vnos)[3])
443 {
444         BM_mesh_elem_index_ensure(bm, (BM_EDGE | BM_FACE) | ((vnos || vcos) ?  BM_VERT : 0));
445
446         BMVertsCalcNormalsData data = {
447             .fnos = fnos,
448             .edgevec = edgevec,
449             .vcos = vcos,
450             .vnos = vnos
451         };
452
453         BM_iter_parallel(bm, BM_FACES_OF_MESH, mesh_verts_calc_normals_accum_cb, &data, bm->totface >= BM_OMP_LIMIT);
454
455         /* normalize the accumulated vertex normals */
456         BM_iter_parallel(bm, BM_VERTS_OF_MESH, mesh_verts_calc_normals_normalize_cb, &data, bm->totvert >= BM_OMP_LIMIT);
457 }
458
459
460 static void mesh_faces_calc_normals_cb(void *UNUSED(userdata), MempoolIterData *mp_f)
461 {
462         BMFace *f = (BMFace *)mp_f;
463
464         BM_face_normal_update(f);
465 }
466
467
468 /**
469  * \brief BMesh Compute Normals
470  *
471  * Updates the normals of a mesh.
472  */
473 void BM_mesh_normals_update(BMesh *bm)
474 {
475         float (*edgevec)[3] = MEM_mallocN(sizeof(*edgevec) * bm->totedge, __func__);
476
477         /* Parallel mempool iteration does not allow to generate indices inline anymore... */
478         BM_mesh_elem_index_ensure(bm, (BM_EDGE | BM_FACE));
479
480         /* calculate all face normals */
481         BM_iter_parallel(bm, BM_FACES_OF_MESH, mesh_faces_calc_normals_cb, NULL, bm->totface >= BM_OMP_LIMIT);
482
483         /* Zero out vertex normals */
484         BMIter viter;
485         BMVert *v;
486         int i;
487
488         BM_ITER_MESH_INDEX (v, &viter, bm, BM_VERTS_OF_MESH, i) {
489                 BM_elem_index_set(v, i); /* set_inline */
490                 zero_v3(v->no);
491         }
492         bm->elem_index_dirty &= ~BM_VERT;
493
494         /* Compute normalized direction vectors for each edge.
495          * Directions will be used for calculating the weights of the face normals on the vertex normals.
496          */
497         bm_mesh_edges_calc_vectors(bm, edgevec, NULL);
498
499         /* Add weighted face normals to vertices, and normalize vert normals. */
500         bm_mesh_verts_calc_normals(bm, (const float(*)[3])edgevec, NULL, NULL, NULL);
501         MEM_freeN(edgevec);
502 }
503
504 /**
505  * \brief BMesh Compute Normals from/to external data.
506  *
507  * Computes the vertex normals of a mesh into vnos, using given vertex coordinates (vcos) and polygon normals (fnos).
508  */
509 void BM_verts_calc_normal_vcos(BMesh *bm, const float (*fnos)[3], const float (*vcos)[3], float (*vnos)[3])
510 {
511         float (*edgevec)[3] = MEM_mallocN(sizeof(*edgevec) * bm->totedge, __func__);
512
513         /* Compute normalized direction vectors for each edge.
514          * Directions will be used for calculating the weights of the face normals on the vertex normals.
515          */
516         bm_mesh_edges_calc_vectors(bm, edgevec, vcos);
517
518         /* Add weighted face normals to vertices, and normalize vert normals. */
519         bm_mesh_verts_calc_normals(bm, (const float(*)[3])edgevec, fnos, vcos, vnos);
520         MEM_freeN(edgevec);
521 }
522
523 /**
524  * Helpers for #BM_mesh_loop_normals_update and #BM_loops_calc_normal_vcos
525  */
526 static void bm_mesh_edges_sharp_tag(
527         BMesh *bm,
528         const float (*vnos)[3], const float (*fnos)[3], float (*r_lnos)[3],
529         const float split_angle, const bool do_sharp_edges_tag)
530 {
531         BMIter eiter;
532         BMEdge *e;
533         int i;
534
535         const bool check_angle = (split_angle < (float)M_PI);
536         const float split_angle_cos = check_angle ? cosf(split_angle) : -1.0f;
537
538         {
539                 char htype = BM_VERT | BM_LOOP;
540                 if (fnos) {
541                         htype |= BM_FACE;
542                 }
543                 BM_mesh_elem_index_ensure(bm, htype);
544         }
545
546         /* This first loop checks which edges are actually smooth, and pre-populate lnos with vnos (as if they were
547          * all smooth).
548          */
549         BM_ITER_MESH_INDEX (e, &eiter, bm, BM_EDGES_OF_MESH, i) {
550                 BMLoop *l_a, *l_b;
551
552                 BM_elem_index_set(e, i); /* set_inline */
553                 BM_elem_flag_disable(e, BM_ELEM_TAG); /* Clear tag (means edge is sharp). */
554
555                 /* An edge with only two loops, might be smooth... */
556                 if (BM_edge_loop_pair(e, &l_a, &l_b)) {
557                         bool is_angle_smooth = true;
558                         if (check_angle) {
559                                 const float *no_a = fnos ? fnos[BM_elem_index_get(l_a->f)] : l_a->f->no;
560                                 const float *no_b = fnos ? fnos[BM_elem_index_get(l_b->f)] : l_b->f->no;
561                                 is_angle_smooth = (dot_v3v3(no_a, no_b) >= split_angle_cos);
562                         }
563
564                         /* We only tag edges that are *really* smooth:
565                          * If the angle between both its polys' normals is below split_angle value,
566                          * and it is tagged as such,
567                          * and both its faces are smooth,
568                          * and both its faces have compatible (non-flipped) normals,
569                          * i.e. both loops on the same edge do not share the same vertex.
570                          */
571                         if (BM_elem_flag_test(e, BM_ELEM_SMOOTH) &&
572                             BM_elem_flag_test(l_a->f, BM_ELEM_SMOOTH) &&
573                             BM_elem_flag_test(l_b->f, BM_ELEM_SMOOTH) &&
574                             l_a->v != l_b->v)
575                         {
576                                 if (is_angle_smooth) {
577                                         const float *no;
578                                         BM_elem_flag_enable(e, BM_ELEM_TAG);
579
580                                         /* linked vertices might be fully smooth, copy their normals to loop ones. */
581                                         if (r_lnos) {
582                                                 no = vnos ? vnos[BM_elem_index_get(l_a->v)] : l_a->v->no;
583                                                 copy_v3_v3(r_lnos[BM_elem_index_get(l_a)], no);
584                                                 no = vnos ? vnos[BM_elem_index_get(l_b->v)] : l_b->v->no;
585                                                 copy_v3_v3(r_lnos[BM_elem_index_get(l_b)], no);
586                                         }
587                                 }
588                                 else if (do_sharp_edges_tag) {
589                                         /* Note that we do not care about the other sharp-edge cases (sharp poly, non-manifold edge, etc.),
590                                          * only tag edge as sharp when it is due to angle threashold. */
591                                         BM_elem_flag_disable(e, BM_ELEM_SMOOTH);
592                                 }
593                         }
594                 }
595         }
596
597         bm->elem_index_dirty &= ~BM_EDGE;
598 }
599
600 /**
601  * Check whether given loop is part of an unknown-so-far cyclic smooth fan, or not.
602  * Needed because cyclic smooth fans have no obvious 'entry point', and yet we need to walk them once, and only once.
603  */
604 bool BM_loop_check_cyclic_smooth_fan(BMLoop *l_curr)
605 {
606         BMLoop *lfan_pivot_next = l_curr;
607         BMEdge *e_next = l_curr->e;
608
609         BLI_assert(!BM_elem_flag_test(lfan_pivot_next, BM_ELEM_TAG));
610         BM_elem_flag_enable(lfan_pivot_next, BM_ELEM_TAG);
611
612         while (true) {
613                 /* Much simpler than in sibling code with basic Mesh data! */
614                 lfan_pivot_next = BM_vert_step_fan_loop(lfan_pivot_next, &e_next);
615
616                 if (!lfan_pivot_next || !BM_elem_flag_test(e_next, BM_ELEM_TAG)) {
617                         /* Sharp loop/edge, so not a cyclic smooth fan... */
618                         return false;
619                 }
620                 /* Smooth loop/edge... */
621                 else if (BM_elem_flag_test(lfan_pivot_next, BM_ELEM_TAG)) {
622                         if (lfan_pivot_next == l_curr) {
623                                 /* We walked around a whole cyclic smooth fan without finding any already-processed loop, means we can
624                                  * use initial l_curr/l_prev edge as start for this smooth fan. */
625                                 return true;
626                         }
627                         /* ... already checked in some previous looping, we can abort. */
628                         return false;
629                 }
630                 else {
631                         /* ... we can skip it in future, and keep checking the smooth fan. */
632                         BM_elem_flag_enable(lfan_pivot_next, BM_ELEM_TAG);
633                 }
634         }
635 }
636
637 /* BMesh version of BKE_mesh_normals_loop_split() in mesh_evaluate.c
638  * Will use first clnors_data array, and fallback to cd_loop_clnors_offset (use NULL and -1 to not use clnors). */
639 static void bm_mesh_loops_calc_normals(
640         BMesh *bm, const float (*vcos)[3], const float (*fnos)[3], float (*r_lnos)[3],
641         MLoopNorSpaceArray *r_lnors_spacearr, short (*clnors_data)[2], const int cd_loop_clnors_offset)
642 {
643         BMIter fiter;
644         BMFace *f_curr;
645         const bool has_clnors = clnors_data || (cd_loop_clnors_offset != -1);
646
647         MLoopNorSpaceArray _lnors_spacearr = {NULL};
648
649         /* Temp normal stack. */
650         BLI_SMALLSTACK_DECLARE(normal, float *);
651         /* Temp clnors stack. */
652         BLI_SMALLSTACK_DECLARE(clnors, short *);
653         /* Temp edge vectors stack, only used when computing lnor spacearr. */
654         BLI_Stack *edge_vectors = NULL;
655
656         {
657                 char htype = 0;
658                 if (vcos) {
659                         htype |= BM_VERT;
660                 }
661                 /* Face/Loop indices are set inline below. */
662                 BM_mesh_elem_index_ensure(bm, htype);
663         }
664
665         if (!r_lnors_spacearr && has_clnors) {
666                 /* We need to compute lnor spacearr if some custom lnor data are given to us! */
667                 r_lnors_spacearr = &_lnors_spacearr;
668         }
669         if (r_lnors_spacearr) {
670                 BKE_lnor_spacearr_init(r_lnors_spacearr, bm->totloop, MLNOR_SPACEARR_BMLOOP_PTR);
671                 edge_vectors = BLI_stack_new(sizeof(float[3]), __func__);
672         }
673
674         /* Clear all loops' tags (means none are to be skipped for now). */
675         int index_face, index_loop = 0;
676         BM_ITER_MESH_INDEX (f_curr, &fiter, bm, BM_FACES_OF_MESH, index_face) {
677                 BMLoop *l_curr, *l_first;
678
679                 BM_elem_index_set(f_curr, index_face); /* set_inline */
680
681                 l_curr = l_first = BM_FACE_FIRST_LOOP(f_curr);
682                 do {
683                         BM_elem_index_set(l_curr, index_loop++); /* set_inline */
684                         BM_elem_flag_disable(l_curr, BM_ELEM_TAG);
685                 } while ((l_curr = l_curr->next) != l_first);
686         }
687         bm->elem_index_dirty &= ~(BM_FACE | BM_LOOP);
688
689         /* We now know edges that can be smoothed (they are tagged), and edges that will be hard (they aren't).
690          * Now, time to generate the normals.
691          */
692         BM_ITER_MESH (f_curr, &fiter, bm, BM_FACES_OF_MESH) {
693                 BMLoop *l_curr, *l_first;
694
695                 l_curr = l_first = BM_FACE_FIRST_LOOP(f_curr);
696                 do {
697                         /* A smooth edge, we have to check for cyclic smooth fan case.
698                          * If we find a new, never-processed cyclic smooth fan, we can do it now using that loop/edge as
699                          * 'entry point', otherwise we can skip it. */
700                         /* Note: In theory, we could make bm_mesh_loop_check_cyclic_smooth_fan() store mlfan_pivot's in a stack,
701                          * to avoid having to fan again around the vert during actual computation of clnor & clnorspace.
702                          * However, this would complicate the code, add more memory usage, and BM_vert_step_fan_loop()
703                          * is quite cheap in term of CPU cycles, so really think it's not worth it. */
704                         if (BM_elem_flag_test(l_curr->e, BM_ELEM_TAG) &&
705                             (BM_elem_flag_test(l_curr, BM_ELEM_TAG) || !BM_loop_check_cyclic_smooth_fan(l_curr)))
706                         {
707                         }
708                         else if (!BM_elem_flag_test(l_curr->e, BM_ELEM_TAG) &&
709                                  !BM_elem_flag_test(l_curr->prev->e, BM_ELEM_TAG))
710                         {
711                                 /* Simple case (both edges around that vertex are sharp in related polygon),
712                                  * this vertex just takes its poly normal.
713                                  */
714                                 const int l_curr_index = BM_elem_index_get(l_curr);
715                                 const float *no = fnos ? fnos[BM_elem_index_get(f_curr)] : f_curr->no;
716                                 copy_v3_v3(r_lnos[l_curr_index], no);
717
718                                 /* If needed, generate this (simple!) lnor space. */
719                                 if (r_lnors_spacearr) {
720                                         float vec_curr[3], vec_prev[3];
721                                         MLoopNorSpace *lnor_space = BKE_lnor_space_create(r_lnors_spacearr);
722
723                                         {
724                                                 const BMVert *v_pivot = l_curr->v;
725                                                 const float *co_pivot = vcos ? vcos[BM_elem_index_get(v_pivot)] : v_pivot->co;
726                                                 const BMVert *v_1 = BM_edge_other_vert(l_curr->e, v_pivot);
727                                                 const float *co_1 = vcos ? vcos[BM_elem_index_get(v_1)] : v_1->co;
728                                                 const BMVert *v_2 = BM_edge_other_vert(l_curr->prev->e, v_pivot);
729                                                 const float *co_2 = vcos ? vcos[BM_elem_index_get(v_2)] : v_2->co;
730
731                                                 sub_v3_v3v3(vec_curr, co_1, co_pivot);
732                                                 normalize_v3(vec_curr);
733                                                 sub_v3_v3v3(vec_prev, co_2, co_pivot);
734                                                 normalize_v3(vec_prev);
735                                         }
736
737                                         BKE_lnor_space_define(lnor_space, r_lnos[l_curr_index], vec_curr, vec_prev, NULL);
738                                         /* We know there is only one loop in this space, no need to create a linklist in this case... */
739                                         BKE_lnor_space_add_loop(r_lnors_spacearr, lnor_space, l_curr_index, l_curr, true);
740
741                                         if (has_clnors) {
742                                                 short (*clnor)[2] = clnors_data ? &clnors_data[l_curr_index] :
743                                                                                   BM_ELEM_CD_GET_VOID_P(l_curr, cd_loop_clnors_offset);
744                                                 BKE_lnor_space_custom_data_to_normal(lnor_space, *clnor, r_lnos[l_curr_index]);
745                                         }
746                                 }
747                         }
748                         /* We *do not need* to check/tag loops as already computed!
749                          * Due to the fact a loop only links to one of its two edges, a same fan *will never be walked more than
750                          * once!*
751                          * Since we consider edges having neighbor faces with inverted (flipped) normals as sharp, we are sure that
752                          * no fan will be skipped, even only considering the case (sharp curr_edge, smooth prev_edge), and not the
753                          * alternative (smooth curr_edge, sharp prev_edge).
754                          * All this due/thanks to link between normals and loop ordering.
755                          */
756                         else {
757                                 /* We have to fan around current vertex, until we find the other non-smooth edge,
758                                  * and accumulate face normals into the vertex!
759                                  * Note in case this vertex has only one sharp edge, this is a waste because the normal is the same as
760                                  * the vertex normal, but I do not see any easy way to detect that (would need to count number
761                                  * of sharp edges per vertex, I doubt the additional memory usage would be worth it, especially as
762                                  * it should not be a common case in real-life meshes anyway).
763                                  */
764                                 BMVert *v_pivot = l_curr->v;
765                                 BMEdge *e_next;
766                                 const BMEdge *e_org = l_curr->e;
767                                 BMLoop *lfan_pivot, *lfan_pivot_next;
768                                 int lfan_pivot_index;
769                                 float lnor[3] = {0.0f, 0.0f, 0.0f};
770                                 float vec_curr[3], vec_next[3], vec_org[3];
771
772                                 /* We validate clnors data on the fly - cheapest way to do! */
773                                 int clnors_avg[2] = {0, 0};
774                                 short (*clnor_ref)[2] = NULL;
775                                 int clnors_nbr = 0;
776                                 bool clnors_invalid = false;
777
778                                 const float *co_pivot = vcos ? vcos[BM_elem_index_get(v_pivot)] : v_pivot->co;
779
780                                 MLoopNorSpace *lnor_space = r_lnors_spacearr ? BKE_lnor_space_create(r_lnors_spacearr) : NULL;
781
782                                 BLI_assert((edge_vectors == NULL) || BLI_stack_is_empty(edge_vectors));
783
784                                 lfan_pivot = l_curr;
785                                 lfan_pivot_index = BM_elem_index_get(lfan_pivot);
786                                 e_next = lfan_pivot->e;  /* Current edge here, actually! */
787
788                                 /* Only need to compute previous edge's vector once, then we can just reuse old current one! */
789                                 {
790                                         const BMVert *v_2 = BM_edge_other_vert(e_next, v_pivot);
791                                         const float *co_2 = vcos ? vcos[BM_elem_index_get(v_2)] : v_2->co;
792
793                                         sub_v3_v3v3(vec_org, co_2, co_pivot);
794                                         normalize_v3(vec_org);
795                                         copy_v3_v3(vec_curr, vec_org);
796
797                                         if (r_lnors_spacearr) {
798                                                 BLI_stack_push(edge_vectors, vec_org);
799                                         }
800                                 }
801
802                                 while (true) {
803                                         /* Much simpler than in sibling code with basic Mesh data! */
804                                         lfan_pivot_next = BM_vert_step_fan_loop(lfan_pivot, &e_next);
805                                         if (lfan_pivot_next) {
806                                                 BLI_assert(lfan_pivot_next->v == v_pivot);
807                                         }
808                                         else {
809                                                 /* next edge is non-manifold, we have to find it ourselves! */
810                                                 e_next = (lfan_pivot->e == e_next) ? lfan_pivot->prev->e : lfan_pivot->e;
811                                         }
812
813                                         /* Compute edge vector.
814                                          * NOTE: We could pre-compute those into an array, in the first iteration, instead of computing them
815                                          *       twice (or more) here. However, time gained is not worth memory and time lost,
816                                          *       given the fact that this code should not be called that much in real-life meshes...
817                                          */
818                                         {
819                                                 const BMVert *v_2 = BM_edge_other_vert(e_next, v_pivot);
820                                                 const float *co_2 = vcos ? vcos[BM_elem_index_get(v_2)] : v_2->co;
821
822                                                 sub_v3_v3v3(vec_next, co_2, co_pivot);
823                                                 normalize_v3(vec_next);
824                                         }
825
826                                         {
827                                                 /* Code similar to accumulate_vertex_normals_poly_v3. */
828                                                 /* Calculate angle between the two poly edges incident on this vertex. */
829                                                 const BMFace *f = lfan_pivot->f;
830                                                 const float fac = saacos(dot_v3v3(vec_next, vec_curr));
831                                                 const float *no = fnos ? fnos[BM_elem_index_get(f)] : f->no;
832                                                 /* Accumulate */
833                                                 madd_v3_v3fl(lnor, no, fac);
834
835                                                 if (has_clnors) {
836                                                         /* Accumulate all clnors, if they are not all equal we have to fix that! */
837                                                         short (*clnor)[2] = clnors_data ? &clnors_data[lfan_pivot_index] :
838                                                                                           BM_ELEM_CD_GET_VOID_P(lfan_pivot, cd_loop_clnors_offset);
839                                                         if (clnors_nbr) {
840                                                                 clnors_invalid |= ((*clnor_ref)[0] != (*clnor)[0] || (*clnor_ref)[1] != (*clnor)[1]);
841                                                         }
842                                                         else {
843                                                                 clnor_ref = clnor;
844                                                         }
845                                                         clnors_avg[0] += (*clnor)[0];
846                                                         clnors_avg[1] += (*clnor)[1];
847                                                         clnors_nbr++;
848                                                         /* We store here a pointer to all custom lnors processed. */
849                                                         BLI_SMALLSTACK_PUSH(clnors, (short *)*clnor);
850                                                 }
851                                         }
852
853                                         /* We store here a pointer to all loop-normals processed. */
854                                         BLI_SMALLSTACK_PUSH(normal, (float *)r_lnos[lfan_pivot_index]);
855
856                                         if (r_lnors_spacearr) {
857                                                 /* Assign current lnor space to current 'vertex' loop. */
858                                                 BKE_lnor_space_add_loop(r_lnors_spacearr, lnor_space, lfan_pivot_index, lfan_pivot, false);
859                                                 if (e_next != e_org) {
860                                                         /* We store here all edges-normalized vectors processed. */
861                                                         BLI_stack_push(edge_vectors, vec_next);
862                                                 }
863                                         }
864
865                                         if (!BM_elem_flag_test(e_next, BM_ELEM_TAG) || (e_next == e_org)) {
866                                                 /* Next edge is sharp, we have finished with this fan of faces around this vert! */
867                                                 break;
868                                         }
869
870                                         /* Copy next edge vector to current one. */
871                                         copy_v3_v3(vec_curr, vec_next);
872                                         /* Next pivot loop to current one. */
873                                         lfan_pivot = lfan_pivot_next;
874                                         lfan_pivot_index = BM_elem_index_get(lfan_pivot);
875                                 }
876
877                                 {
878                                         float lnor_len = normalize_v3(lnor);
879
880                                         /* If we are generating lnor spacearr, we can now define the one for this fan. */
881                                         if (r_lnors_spacearr) {
882                                                 if (UNLIKELY(lnor_len == 0.0f)) {
883                                                         /* Use vertex normal as fallback! */
884                                                         copy_v3_v3(lnor, r_lnos[lfan_pivot_index]);
885                                                         lnor_len = 1.0f;
886                                                 }
887
888                                                 BKE_lnor_space_define(lnor_space, lnor, vec_org, vec_next, edge_vectors);
889
890                                                 if (has_clnors) {
891                                                         if (clnors_invalid) {
892                                                                 short *clnor;
893
894                                                                 clnors_avg[0] /= clnors_nbr;
895                                                                 clnors_avg[1] /= clnors_nbr;
896                                                                 /* Fix/update all clnors of this fan with computed average value. */
897
898                                                                 /* Prints continuously when merge custom normals, so commenting. */
899                                                                 /* printf("Invalid clnors in this fan!\n"); */
900
901                                                                 while ((clnor = BLI_SMALLSTACK_POP(clnors))) {
902                                                                         //print_v2("org clnor", clnor);
903                                                                         clnor[0] = (short)clnors_avg[0];
904                                                                         clnor[1] = (short)clnors_avg[1];
905                                                                 }
906                                                                 //print_v2("new clnors", clnors_avg);
907                                                         }
908                                                         else {
909                                                                 /* We still have to consume the stack! */
910                                                                 while (BLI_SMALLSTACK_POP(clnors));
911                                                         }
912                                                         BKE_lnor_space_custom_data_to_normal(lnor_space, *clnor_ref, lnor);
913                                                 }
914                                         }
915
916                                         /* In case we get a zero normal here, just use vertex normal already set! */
917                                         if (LIKELY(lnor_len != 0.0f)) {
918                                                 /* Copy back the final computed normal into all related loop-normals. */
919                                                 float *nor;
920
921                                                 while ((nor = BLI_SMALLSTACK_POP(normal))) {
922                                                         copy_v3_v3(nor, lnor);
923                                                 }
924                                         }
925                                         else {
926                                                 /* We still have to consume the stack! */
927                                                 while (BLI_SMALLSTACK_POP(normal));
928                                         }
929                                 }
930
931                                 /* Tag related vertex as sharp, to avoid fanning around it again (in case it was a smooth one). */
932                                 if (r_lnors_spacearr) {
933                                         BM_elem_flag_enable(l_curr->v, BM_ELEM_TAG);
934                                 }
935                         }
936                 } while ((l_curr = l_curr->next) != l_first);
937         }
938
939         if (r_lnors_spacearr) {
940                 BLI_stack_free(edge_vectors);
941                 if (r_lnors_spacearr == &_lnors_spacearr) {
942                         BKE_lnor_spacearr_free(r_lnors_spacearr);
943                 }
944         }
945 }
946
947 static void bm_mesh_loops_calc_normals_no_autosmooth(
948         BMesh *bm, const float (*vnos)[3], const float (*fnos)[3], float (*r_lnos)[3])
949 {
950         BMIter fiter;
951         BMFace *f_curr;
952
953         {
954                 char htype = BM_LOOP;
955                 if (vnos) {
956                         htype |= BM_VERT;
957                 }
958                 if (fnos) {
959                         htype |= BM_FACE;
960                 }
961                 BM_mesh_elem_index_ensure(bm, htype);
962         }
963
964         BM_ITER_MESH (f_curr, &fiter, bm, BM_FACES_OF_MESH) {
965                 BMLoop *l_curr, *l_first;
966                 const bool is_face_flat = !BM_elem_flag_test(f_curr, BM_ELEM_SMOOTH);
967
968                 l_curr = l_first = BM_FACE_FIRST_LOOP(f_curr);
969                 do {
970                         const float *no = is_face_flat ? (fnos ? fnos[BM_elem_index_get(f_curr)] : f_curr->no) :
971                                                          (vnos ? vnos[BM_elem_index_get(l_curr->v)] : l_curr->v->no);
972                         copy_v3_v3(r_lnos[BM_elem_index_get(l_curr)], no);
973
974                 } while ((l_curr = l_curr->next) != l_first);
975         }
976 }
977
978 #if 0  /* Unused currently */
979 /**
980  * \brief BMesh Compute Loop Normals
981  *
982  * Updates the loop normals of a mesh. Assumes vertex and face normals are valid (else call BM_mesh_normals_update()
983  * first)!
984  */
985 void BM_mesh_loop_normals_update(
986         BMesh *bm, const bool use_split_normals, const float split_angle, float (*r_lnos)[3],
987         MLoopNorSpaceArray *r_lnors_spacearr, short (*clnors_data)[2], const int cd_loop_clnors_offset)
988 {
989         const bool has_clnors = clnors_data || (cd_loop_clnors_offset != -1);
990
991         if (use_split_normals) {
992                 /* Tag smooth edges and set lnos from vnos when they might be completely smooth...
993                  * When using custom loop normals, disable the angle feature! */
994                 bm_mesh_edges_sharp_tag(bm, NULL, NULL, has_clnors ? (float)M_PI : split_angle, r_lnos);
995
996                 /* Finish computing lnos by accumulating face normals in each fan of faces defined by sharp edges. */
997                 bm_mesh_loops_calc_normals(bm, NULL, NULL, r_lnos, r_lnors_spacearr, clnors_data, cd_loop_clnors_offset);
998         }
999         else {
1000                 BLI_assert(!r_lnors_spacearr);
1001                 bm_mesh_loops_calc_normals_no_autosmooth(bm, NULL, NULL, r_lnos);
1002         }
1003 }
1004 #endif
1005
1006 /**
1007  * \brief BMesh Compute Loop Normals from/to external data.
1008  *
1009  * Compute split normals, i.e. vertex normals associated with each poly (hence 'loop normals').
1010  * Useful to materialize sharp edges (or non-smooth faces) without actually modifying the geometry (splitting edges).
1011  */
1012 void BM_loops_calc_normal_vcos(
1013         BMesh *bm, const float (*vcos)[3], const float (*vnos)[3], const float (*fnos)[3],
1014         const bool use_split_normals, const float split_angle, float (*r_lnos)[3],
1015         MLoopNorSpaceArray *r_lnors_spacearr, short (*clnors_data)[2],
1016         const int cd_loop_clnors_offset)
1017 {
1018         const bool has_clnors = clnors_data || (cd_loop_clnors_offset != -1);
1019
1020         if (use_split_normals) {
1021                 /* Tag smooth edges and set lnos from vnos when they might be completely smooth...
1022                  * When using custom loop normals, disable the angle feature! */
1023                 bm_mesh_edges_sharp_tag(bm, vnos, fnos, r_lnos, has_clnors ? (float)M_PI : split_angle, false);
1024
1025                 /* Finish computing lnos by accumulating face normals in each fan of faces defined by sharp edges. */
1026                 bm_mesh_loops_calc_normals(
1027                         bm, vcos, fnos, r_lnos, r_lnors_spacearr, clnors_data, cd_loop_clnors_offset);
1028         }
1029         else {
1030                 BLI_assert(!r_lnors_spacearr);
1031                 bm_mesh_loops_calc_normals_no_autosmooth(bm, vnos, fnos, r_lnos);
1032         }
1033 }
1034
1035 /** Define sharp edges as needed to mimic 'autosmooth' from angle threshold.
1036  *
1037  * Used when defining an empty custom loop normals data layer, to keep same shading as with autosmooth!
1038  */
1039 void BM_edges_sharp_from_angle_set(BMesh *bm, const float split_angle)
1040 {
1041         if (split_angle >= (float)M_PI) {
1042                 /* Nothing to do! */
1043                 return;
1044         }
1045
1046         bm_mesh_edges_sharp_tag(bm, NULL, NULL, NULL, split_angle, true);
1047 }
1048
1049 static void UNUSED_FUNCTION(bm_mdisps_space_set)(Object *ob, BMesh *bm, int from, int to)
1050 {
1051         /* switch multires data out of tangent space */
1052         if (CustomData_has_layer(&bm->ldata, CD_MDISPS)) {
1053                 BMEditMesh *em = BKE_editmesh_create(bm, false);
1054                 DerivedMesh *dm = CDDM_from_editbmesh(em, true, false);
1055                 MDisps *mdisps;
1056                 BMFace *f;
1057                 BMIter iter;
1058                 // int i = 0; // UNUSED
1059
1060                 multires_set_space(dm, ob, from, to);
1061
1062                 mdisps = CustomData_get_layer(&dm->loopData, CD_MDISPS);
1063
1064                 BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
1065                         BMLoop *l;
1066                         BMIter liter;
1067                         BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
1068                                 MDisps *lmd = CustomData_bmesh_get(&bm->ldata, l->head.data, CD_MDISPS);
1069
1070                                 if (!lmd->disps) {
1071                                         printf("%s: warning - 'lmd->disps' == NULL\n", __func__);
1072                                 }
1073
1074                                 if (lmd->disps && lmd->totdisp == mdisps->totdisp) {
1075                                         memcpy(lmd->disps, mdisps->disps, sizeof(float) * 3 * lmd->totdisp);
1076                                 }
1077                                 else if (mdisps->disps) {
1078                                         if (lmd->disps)
1079                                                 MEM_freeN(lmd->disps);
1080
1081                                         lmd->disps = MEM_dupallocN(mdisps->disps);
1082                                         lmd->totdisp = mdisps->totdisp;
1083                                         lmd->level = mdisps->level;
1084                                 }
1085
1086                                 mdisps++;
1087                                 // i += 1;
1088                         }
1089                 }
1090
1091                 dm->needsFree = 1;
1092                 dm->release(dm);
1093
1094                 /* setting this to NULL prevents BKE_editmesh_free from freeing it */
1095                 em->bm = NULL;
1096                 BKE_editmesh_free(em);
1097                 MEM_freeN(em);
1098         }
1099 }
1100
1101 /**
1102  * \brief BMesh Begin Edit
1103  *
1104  * Functions for setting up a mesh for editing and cleaning up after
1105  * the editing operations are done. These are called by the tools/operator
1106  * API for each time a tool is executed.
1107  */
1108 void bmesh_edit_begin(BMesh *UNUSED(bm), BMOpTypeFlag UNUSED(type_flag))
1109 {
1110         /* Most operators seem to be using BMO_OPTYPE_FLAG_UNTAN_MULTIRES to change the MDisps to
1111          * absolute space during mesh edits. With this enabled, changes to the topology
1112          * (loop cuts, edge subdivides, etc) are not reflected in the higher levels of
1113          * the mesh at all, which doesn't seem right. Turning off completely for now,
1114          * until this is shown to be better for certain types of mesh edits. */
1115 #ifdef BMOP_UNTAN_MULTIRES_ENABLED
1116         /* switch multires data out of tangent space */
1117         if ((type_flag & BMO_OPTYPE_FLAG_UNTAN_MULTIRES) && CustomData_has_layer(&bm->ldata, CD_MDISPS)) {
1118                 bmesh_mdisps_space_set(bm, MULTIRES_SPACE_TANGENT, MULTIRES_SPACE_ABSOLUTE);
1119
1120                 /* ensure correct normals, if possible */
1121                 bmesh_rationalize_normals(bm, 0);
1122                 BM_mesh_normals_update(bm);
1123         }
1124 #endif
1125 }
1126
1127 /**
1128  * \brief BMesh End Edit
1129  */
1130 void bmesh_edit_end(BMesh *bm, BMOpTypeFlag type_flag)
1131 {
1132         ListBase select_history;
1133
1134         /* BMO_OPTYPE_FLAG_UNTAN_MULTIRES disabled for now, see comment above in bmesh_edit_begin. */
1135 #ifdef BMOP_UNTAN_MULTIRES_ENABLED
1136         /* switch multires data into tangent space */
1137         if ((flag & BMO_OPTYPE_FLAG_UNTAN_MULTIRES) && CustomData_has_layer(&bm->ldata, CD_MDISPS)) {
1138                 /* set normals to their previous winding */
1139                 bmesh_rationalize_normals(bm, 1);
1140                 bmesh_mdisps_space_set(bm, MULTIRES_SPACE_ABSOLUTE, MULTIRES_SPACE_TANGENT);
1141         }
1142         else if (flag & BMO_OP_FLAG_RATIONALIZE_NORMALS) {
1143                 bmesh_rationalize_normals(bm, 1);
1144         }
1145 #endif
1146
1147         /* compute normals, clear temp flags and flush selections */
1148         if (type_flag & BMO_OPTYPE_FLAG_NORMALS_CALC) {
1149                 BM_mesh_normals_update(bm);
1150         }
1151
1152
1153         if ((type_flag & BMO_OPTYPE_FLAG_SELECT_VALIDATE) == 0) {
1154                 select_history = bm->selected;
1155                 BLI_listbase_clear(&bm->selected);
1156         }
1157
1158         if (type_flag & BMO_OPTYPE_FLAG_SELECT_FLUSH) {
1159                 BM_mesh_select_mode_flush(bm);
1160         }
1161
1162         if ((type_flag & BMO_OPTYPE_FLAG_SELECT_VALIDATE) == 0) {
1163                 bm->selected = select_history;
1164         }
1165 }
1166
1167 void BM_mesh_elem_index_ensure(BMesh *bm, const char htype)
1168 {
1169         const char htype_needed = bm->elem_index_dirty & htype;
1170
1171 #ifdef DEBUG
1172         BM_ELEM_INDEX_VALIDATE(bm, "Should Never Fail!", __func__);
1173 #endif
1174
1175         if (0 && htype_needed == 0) {
1176                 goto finally;
1177         }
1178
1179         if (htype & BM_VERT) {
1180                 if (bm->elem_index_dirty & BM_VERT) {
1181                         BMIter iter;
1182                         BMElem *ele;
1183
1184                         int index;
1185                         BM_ITER_MESH_INDEX (ele, &iter, bm, BM_VERTS_OF_MESH, index) {
1186                                 BM_elem_index_set(ele, index); /* set_ok */
1187                         }
1188                         BLI_assert(index == bm->totvert);
1189                 }
1190                 else {
1191                         // printf("%s: skipping vert index calc!\n", __func__);
1192                 }
1193         }
1194
1195         if (htype & BM_EDGE) {
1196                 if (bm->elem_index_dirty & BM_EDGE) {
1197                         BMIter iter;
1198                         BMElem *ele;
1199
1200                         int index;
1201                         BM_ITER_MESH_INDEX (ele, &iter, bm, BM_EDGES_OF_MESH, index) {
1202                                 BM_elem_index_set(ele, index); /* set_ok */
1203                         }
1204                         BLI_assert(index == bm->totedge);
1205                 }
1206                 else {
1207                         // printf("%s: skipping edge index calc!\n", __func__);
1208                 }
1209         }
1210
1211         if (htype & (BM_FACE | BM_LOOP)) {
1212                 if (bm->elem_index_dirty & (BM_FACE | BM_LOOP)) {
1213                         BMIter iter;
1214                         BMElem *ele;
1215
1216                         const bool update_face = (htype & BM_FACE) && (bm->elem_index_dirty & BM_FACE);
1217                         const bool update_loop = (htype & BM_LOOP) && (bm->elem_index_dirty & BM_LOOP);
1218
1219                         int index;
1220                         int index_loop = 0;
1221
1222                         BM_ITER_MESH_INDEX (ele, &iter, bm, BM_FACES_OF_MESH, index) {
1223                                 if (update_face) {
1224                                         BM_elem_index_set(ele, index); /* set_ok */
1225                                 }
1226
1227                                 if (update_loop) {
1228                                         BMLoop *l_iter, *l_first;
1229
1230                                         l_iter = l_first = BM_FACE_FIRST_LOOP((BMFace *)ele);
1231                                         do {
1232                                                 BM_elem_index_set(l_iter, index_loop++); /* set_ok */
1233                                         } while ((l_iter = l_iter->next) != l_first);
1234                                 }
1235                         }
1236
1237                         BLI_assert(index == bm->totface);
1238                         if (update_loop) {
1239                                 BLI_assert(index_loop == bm->totloop);
1240                         }
1241                 }
1242                 else {
1243                         // printf("%s: skipping face/loop index calc!\n", __func__);
1244                 }
1245         }
1246
1247 finally:
1248         bm->elem_index_dirty &= ~htype;
1249 }
1250
1251
1252 /**
1253  * Array checking/setting macros
1254  *
1255  * Currently vert/edge/loop/face index data is being abused, in a few areas of the code.
1256  *
1257  * To avoid correcting them afterwards, set 'bm->elem_index_dirty' however its possible
1258  * this flag is set incorrectly which could crash blender.
1259  *
1260  * These functions ensure its correct and are called more often in debug mode.
1261  */
1262
1263 void BM_mesh_elem_index_validate(
1264         BMesh *bm, const char *location, const char *func,
1265         const char *msg_a, const char *msg_b)
1266 {
1267         const char iter_types[3] = {BM_VERTS_OF_MESH,
1268                                     BM_EDGES_OF_MESH,
1269                                     BM_FACES_OF_MESH};
1270
1271         const char flag_types[3] = {BM_VERT, BM_EDGE, BM_FACE};
1272         const char *type_names[3] = {"vert", "edge", "face"};
1273
1274         BMIter iter;
1275         BMElem *ele;
1276         int i;
1277         bool is_any_error = 0;
1278
1279         for (i = 0; i < 3; i++) {
1280                 const bool is_dirty = (flag_types[i] & bm->elem_index_dirty) != 0;
1281                 int index = 0;
1282                 bool is_error = false;
1283                 int err_val = 0;
1284                 int err_idx = 0;
1285
1286                 BM_ITER_MESH (ele, &iter, bm, iter_types[i]) {
1287                         if (!is_dirty) {
1288                                 if (BM_elem_index_get(ele) != index) {
1289                                         err_val = BM_elem_index_get(ele);
1290                                         err_idx = index;
1291                                         is_error = true;
1292                                 }
1293                         }
1294
1295                         BM_elem_index_set(ele, index); /* set_ok */
1296                         index++;
1297                 }
1298
1299                 if ((is_error == true) && (is_dirty == false)) {
1300                         is_any_error = true;
1301                         fprintf(stderr,
1302                                 "Invalid Index: at %s, %s, %s[%d] invalid index %d, '%s', '%s'\n",
1303                                 location, func, type_names[i], err_idx, err_val, msg_a, msg_b);
1304                 }
1305                 else if ((is_error == false) && (is_dirty == true)) {
1306
1307 #if 0       /* mostly annoying */
1308
1309                         /* dirty may have been incorrectly set */
1310                         fprintf(stderr,
1311                                 "Invalid Dirty: at %s, %s (%s), dirty flag was set but all index values are correct, '%s', '%s'\n",
1312                                 location, func, type_names[i], msg_a, msg_b);
1313 #endif
1314                 }
1315         }
1316
1317 #if 0 /* mostly annoying, even in debug mode */
1318 #ifdef DEBUG
1319         if (is_any_error == 0) {
1320                 fprintf(stderr,
1321                         "Valid Index Success: at %s, %s, '%s', '%s'\n",
1322                         location, func, msg_a, msg_b);
1323         }
1324 #endif
1325 #endif
1326         (void) is_any_error; /* shut up the compiler */
1327
1328 }
1329
1330 /* debug check only - no need to optimize */
1331 #ifndef NDEBUG
1332 bool BM_mesh_elem_table_check(BMesh *bm)
1333 {
1334         BMIter iter;
1335         BMElem *ele;
1336         int i;
1337
1338         if (bm->vtable && ((bm->elem_table_dirty & BM_VERT) == 0)) {
1339                 BM_ITER_MESH_INDEX (ele, &iter, bm, BM_VERTS_OF_MESH, i) {
1340                         if (ele != (BMElem *)bm->vtable[i]) {
1341                                 return false;
1342                         }
1343                 }
1344         }
1345
1346         if (bm->etable && ((bm->elem_table_dirty & BM_EDGE) == 0)) {
1347                 BM_ITER_MESH_INDEX (ele, &iter, bm, BM_EDGES_OF_MESH, i) {
1348                         if (ele != (BMElem *)bm->etable[i]) {
1349                                 return false;
1350                         }
1351                 }
1352         }
1353
1354         if (bm->ftable && ((bm->elem_table_dirty & BM_FACE) == 0)) {
1355                 BM_ITER_MESH_INDEX (ele, &iter, bm, BM_FACES_OF_MESH, i) {
1356                         if (ele != (BMElem *)bm->ftable[i]) {
1357                                 return false;
1358                         }
1359                 }
1360         }
1361
1362         return true;
1363 }
1364 #endif
1365
1366
1367
1368 void BM_mesh_elem_table_ensure(BMesh *bm, const char htype)
1369 {
1370         /* assume if the array is non-null then its valid and no need to recalc */
1371         const char htype_needed = (((bm->vtable && ((bm->elem_table_dirty & BM_VERT) == 0)) ? 0 : BM_VERT) |
1372                                    ((bm->etable && ((bm->elem_table_dirty & BM_EDGE) == 0)) ? 0 : BM_EDGE) |
1373                                    ((bm->ftable && ((bm->elem_table_dirty & BM_FACE) == 0)) ? 0 : BM_FACE)) & htype;
1374
1375         BLI_assert((htype & ~BM_ALL_NOLOOP) == 0);
1376
1377         /* in debug mode double check we didn't need to recalculate */
1378         BLI_assert(BM_mesh_elem_table_check(bm) == true);
1379
1380         if (htype_needed == 0) {
1381                 goto finally;
1382         }
1383
1384         if (htype_needed & BM_VERT) {
1385                 if (bm->vtable && bm->totvert <= bm->vtable_tot && bm->totvert * 2 >= bm->vtable_tot) {
1386                         /* pass (re-use the array) */
1387                 }
1388                 else {
1389                         if (bm->vtable)
1390                                 MEM_freeN(bm->vtable);
1391                         bm->vtable = MEM_mallocN(sizeof(void **) * bm->totvert, "bm->vtable");
1392                         bm->vtable_tot = bm->totvert;
1393                 }
1394         }
1395         if (htype_needed & BM_EDGE) {
1396                 if (bm->etable && bm->totedge <= bm->etable_tot && bm->totedge * 2 >= bm->etable_tot) {
1397                         /* pass (re-use the array) */
1398                 }
1399                 else {
1400                         if (bm->etable)
1401                                 MEM_freeN(bm->etable);
1402                         bm->etable = MEM_mallocN(sizeof(void **) * bm->totedge, "bm->etable");
1403                         bm->etable_tot = bm->totedge;
1404                 }
1405         }
1406         if (htype_needed & BM_FACE) {
1407                 if (bm->ftable && bm->totface <= bm->ftable_tot && bm->totface * 2 >= bm->ftable_tot) {
1408                         /* pass (re-use the array) */
1409                 }
1410                 else {
1411                         if (bm->ftable)
1412                                 MEM_freeN(bm->ftable);
1413                         bm->ftable = MEM_mallocN(sizeof(void **) * bm->totface, "bm->ftable");
1414                         bm->ftable_tot = bm->totface;
1415                 }
1416         }
1417
1418         if (htype_needed & BM_VERT) {
1419                 BM_iter_as_array(bm, BM_VERTS_OF_MESH, NULL, (void **)bm->vtable, bm->totvert);
1420         }
1421
1422         if (htype_needed & BM_EDGE) {
1423                 BM_iter_as_array(bm, BM_EDGES_OF_MESH, NULL, (void **)bm->etable, bm->totedge);
1424         }
1425
1426         if (htype_needed & BM_FACE) {
1427                 BM_iter_as_array(bm, BM_FACES_OF_MESH, NULL, (void **)bm->ftable, bm->totface);
1428         }
1429
1430 finally:
1431         /* Only clear dirty flags when all the pointers and data are actually valid.
1432          * This prevents possible threading issues when dirty flag check failed but
1433          * data wasn't ready still.
1434          */
1435         bm->elem_table_dirty &= ~htype_needed;
1436 }
1437
1438 /* use BM_mesh_elem_table_ensure where possible to avoid full rebuild */
1439 void BM_mesh_elem_table_init(BMesh *bm, const char htype)
1440 {
1441         BLI_assert((htype & ~BM_ALL_NOLOOP) == 0);
1442
1443         /* force recalc */
1444         BM_mesh_elem_table_free(bm, BM_ALL_NOLOOP);
1445         BM_mesh_elem_table_ensure(bm, htype);
1446 }
1447
1448 void BM_mesh_elem_table_free(BMesh *bm, const char htype)
1449 {
1450         if (htype & BM_VERT) {
1451                 MEM_SAFE_FREE(bm->vtable);
1452         }
1453
1454         if (htype & BM_EDGE) {
1455                 MEM_SAFE_FREE(bm->etable);
1456         }
1457
1458         if (htype & BM_FACE) {
1459                 MEM_SAFE_FREE(bm->ftable);
1460         }
1461 }
1462
1463 BMVert *BM_vert_at_index_find(BMesh *bm, const int index)
1464 {
1465         return BLI_mempool_findelem(bm->vpool, index);
1466 }
1467
1468 BMEdge *BM_edge_at_index_find(BMesh *bm, const int index)
1469 {
1470         return BLI_mempool_findelem(bm->epool, index);
1471 }
1472
1473 BMFace *BM_face_at_index_find(BMesh *bm, const int index)
1474 {
1475         return BLI_mempool_findelem(bm->fpool, index);
1476 }
1477
1478 /**
1479  * Use lookup table when available, else use slower find functions.
1480  *
1481  * \note Try to use #BM_mesh_elem_table_ensure instead.
1482  */
1483 BMVert *BM_vert_at_index_find_or_table(BMesh *bm, const int index)
1484 {
1485         if ((bm->elem_table_dirty & BM_VERT) == 0) {
1486                 return (index < bm->totvert) ? bm->vtable[index] : NULL;
1487         }
1488         else {
1489                 return BM_vert_at_index_find(bm, index);
1490         }
1491 }
1492
1493 BMEdge *BM_edge_at_index_find_or_table(BMesh *bm, const int index)
1494 {
1495         if ((bm->elem_table_dirty & BM_EDGE) == 0) {
1496                 return (index < bm->totedge) ? bm->etable[index] : NULL;
1497         }
1498         else {
1499                 return BM_edge_at_index_find(bm, index);
1500         }
1501 }
1502
1503 BMFace *BM_face_at_index_find_or_table(BMesh *bm, const int index)
1504 {
1505         if ((bm->elem_table_dirty & BM_FACE) == 0) {
1506                 return (index < bm->totface) ? bm->ftable[index] : NULL;
1507         }
1508         else {
1509                 return BM_face_at_index_find(bm, index);
1510         }
1511 }
1512
1513
1514 /**
1515  * Return the amount of element of type 'type' in a given bmesh.
1516  */
1517 int BM_mesh_elem_count(BMesh *bm, const char htype)
1518 {
1519         BLI_assert((htype & ~BM_ALL_NOLOOP) == 0);
1520
1521         switch (htype) {
1522                 case BM_VERT: return bm->totvert;
1523                 case BM_EDGE: return bm->totedge;
1524                 case BM_FACE: return bm->totface;
1525                 default:
1526                 {
1527                         BLI_assert(0);
1528                         return 0;
1529                 }
1530         }
1531 }
1532
1533
1534 /**
1535  * Remaps the vertices, edges and/or faces of the bmesh as indicated by vert/edge/face_idx arrays
1536  * (xxx_idx[org_index] = new_index).
1537  *
1538  * A NULL array means no changes.
1539  *
1540  * Note: - Does not mess with indices, just sets elem_index_dirty flag.
1541  *       - For verts/edges/faces only (as loops must remain "ordered" and "aligned"
1542  *         on a per-face basis...).
1543  *
1544  * WARNING: Be careful if you keep pointers to affected BM elements, or arrays, when using this func!
1545  */
1546 void BM_mesh_remap(
1547         BMesh *bm,
1548         const uint *vert_idx,
1549         const uint *edge_idx,
1550         const uint *face_idx)
1551 {
1552         /* Mapping old to new pointers. */
1553         GHash *vptr_map = NULL, *eptr_map = NULL, *fptr_map = NULL;
1554         BMIter iter, iterl;
1555         BMVert *ve;
1556         BMEdge *ed;
1557         BMFace *fa;
1558         BMLoop *lo;
1559
1560         if (!(vert_idx || edge_idx || face_idx))
1561                 return;
1562
1563         BM_mesh_elem_table_ensure(
1564                 bm,
1565                 (vert_idx ? BM_VERT : 0) |
1566                 (edge_idx ? BM_EDGE : 0) |
1567                 (face_idx ? BM_FACE : 0));
1568
1569         /* Remap Verts */
1570         if (vert_idx) {
1571                 BMVert **verts_pool, *verts_copy, **vep;
1572                 int i, totvert = bm->totvert;
1573                 const uint *new_idx;
1574                 /* Special case: Python uses custom - data layers to hold PyObject references.
1575                  * These have to be kept in - place, else the PyObject's we point to, wont point back to us. */
1576                 const int cd_vert_pyptr  = CustomData_get_offset(&bm->vdata, CD_BM_ELEM_PYPTR);
1577
1578                 /* Init the old-to-new vert pointers mapping */
1579                 vptr_map = BLI_ghash_ptr_new_ex("BM_mesh_remap vert pointers mapping", bm->totvert);
1580
1581                 /* Make a copy of all vertices. */
1582                 verts_pool = bm->vtable;
1583                 verts_copy = MEM_mallocN(sizeof(BMVert) * totvert, "BM_mesh_remap verts copy");
1584                 void **pyptrs = (cd_vert_pyptr != -1) ? MEM_mallocN(sizeof(void *) * totvert, __func__) : NULL;
1585                 for (i = totvert, ve = verts_copy + totvert - 1, vep = verts_pool + totvert - 1; i--; ve--, vep--) {
1586                         *ve = **vep;
1587 /*                      printf("*vep: %p, verts_pool[%d]: %p\n", *vep, i, verts_pool[i]);*/
1588                         if (cd_vert_pyptr != -1) {
1589                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)ve), cd_vert_pyptr);
1590                                 pyptrs[i] = *pyptr;
1591                         }
1592                 }
1593
1594                 /* Copy back verts to their new place, and update old2new pointers mapping. */
1595                 new_idx = vert_idx + totvert - 1;
1596                 ve = verts_copy + totvert - 1;
1597                 vep = verts_pool + totvert - 1; /* old, org pointer */
1598                 for (i = totvert; i--; new_idx--, ve--, vep--) {
1599                         BMVert *new_vep = verts_pool[*new_idx];
1600                         *new_vep = *ve;
1601 /*                      printf("mapping vert from %d to %d (%p/%p to %p)\n", i, *new_idx, *vep, verts_pool[i], new_vep);*/
1602                         BLI_ghash_insert(vptr_map, *vep, new_vep);
1603                         if (cd_vert_pyptr != -1) {
1604                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)new_vep), cd_vert_pyptr);
1605                                 *pyptr = pyptrs[*new_idx];
1606                         }
1607                 }
1608                 bm->elem_index_dirty |= BM_VERT;
1609                 bm->elem_table_dirty |= BM_VERT;
1610
1611                 MEM_freeN(verts_copy);
1612                 if (pyptrs) {
1613                         MEM_freeN(pyptrs);
1614                 }
1615         }
1616
1617         /* Remap Edges */
1618         if (edge_idx) {
1619                 BMEdge **edges_pool, *edges_copy, **edp;
1620                 int i, totedge = bm->totedge;
1621                 const uint *new_idx;
1622                 /* Special case: Python uses custom - data layers to hold PyObject references.
1623                  * These have to be kept in - place, else the PyObject's we point to, wont point back to us. */
1624                 const int cd_edge_pyptr  = CustomData_get_offset(&bm->edata, CD_BM_ELEM_PYPTR);
1625
1626                 /* Init the old-to-new vert pointers mapping */
1627                 eptr_map = BLI_ghash_ptr_new_ex("BM_mesh_remap edge pointers mapping", bm->totedge);
1628
1629                 /* Make a copy of all vertices. */
1630                 edges_pool = bm->etable;
1631                 edges_copy = MEM_mallocN(sizeof(BMEdge) * totedge, "BM_mesh_remap edges copy");
1632                 void **pyptrs = (cd_edge_pyptr != -1) ? MEM_mallocN(sizeof(void *) * totedge, __func__) : NULL;
1633                 for (i = totedge, ed = edges_copy + totedge - 1, edp = edges_pool + totedge - 1; i--; ed--, edp--) {
1634                         *ed = **edp;
1635                         if (cd_edge_pyptr != -1) {
1636                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)ed), cd_edge_pyptr);
1637                                 pyptrs[i] = *pyptr;
1638                         }
1639                 }
1640
1641                 /* Copy back verts to their new place, and update old2new pointers mapping. */
1642                 new_idx = edge_idx + totedge - 1;
1643                 ed = edges_copy + totedge - 1;
1644                 edp = edges_pool + totedge - 1; /* old, org pointer */
1645                 for (i = totedge; i--; new_idx--, ed--, edp--) {
1646                         BMEdge *new_edp = edges_pool[*new_idx];
1647                         *new_edp = *ed;
1648                         BLI_ghash_insert(eptr_map, *edp, new_edp);
1649 /*                      printf("mapping edge from %d to %d (%p/%p to %p)\n", i, *new_idx, *edp, edges_pool[i], new_edp);*/
1650                         if (cd_edge_pyptr != -1) {
1651                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)new_edp), cd_edge_pyptr);
1652                                 *pyptr = pyptrs[*new_idx];
1653                         }
1654                 }
1655                 bm->elem_index_dirty |= BM_EDGE;
1656                 bm->elem_table_dirty |= BM_EDGE;
1657
1658                 MEM_freeN(edges_copy);
1659                 if (pyptrs) {
1660                         MEM_freeN(pyptrs);
1661                 }
1662         }
1663
1664         /* Remap Faces */
1665         if (face_idx) {
1666                 BMFace **faces_pool, *faces_copy, **fap;
1667                 int i, totface = bm->totface;
1668                 const uint *new_idx;
1669                 /* Special case: Python uses custom - data layers to hold PyObject references.
1670                  * These have to be kept in - place, else the PyObject's we point to, wont point back to us. */
1671                 const int cd_poly_pyptr  = CustomData_get_offset(&bm->pdata, CD_BM_ELEM_PYPTR);
1672
1673                 /* Init the old-to-new vert pointers mapping */
1674                 fptr_map = BLI_ghash_ptr_new_ex("BM_mesh_remap face pointers mapping", bm->totface);
1675
1676                 /* Make a copy of all vertices. */
1677                 faces_pool = bm->ftable;
1678                 faces_copy = MEM_mallocN(sizeof(BMFace) * totface, "BM_mesh_remap faces copy");
1679                 void **pyptrs = (cd_poly_pyptr != -1) ? MEM_mallocN(sizeof(void *) * totface, __func__) : NULL;
1680                 for (i = totface, fa = faces_copy + totface - 1, fap = faces_pool + totface - 1; i--; fa--, fap--) {
1681                         *fa = **fap;
1682                         if (cd_poly_pyptr != -1) {
1683                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)fa), cd_poly_pyptr);
1684                                 pyptrs[i] = *pyptr;
1685                         }
1686                 }
1687
1688                 /* Copy back verts to their new place, and update old2new pointers mapping. */
1689                 new_idx = face_idx + totface - 1;
1690                 fa = faces_copy + totface - 1;
1691                 fap = faces_pool + totface - 1; /* old, org pointer */
1692                 for (i = totface; i--; new_idx--, fa--, fap--) {
1693                         BMFace *new_fap = faces_pool[*new_idx];
1694                         *new_fap = *fa;
1695                         BLI_ghash_insert(fptr_map, *fap, new_fap);
1696                         if (cd_poly_pyptr != -1) {
1697                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)new_fap), cd_poly_pyptr);
1698                                 *pyptr = pyptrs[*new_idx];
1699                         }
1700                 }
1701
1702                 bm->elem_index_dirty |= BM_FACE | BM_LOOP;
1703                 bm->elem_table_dirty |= BM_FACE;
1704
1705                 MEM_freeN(faces_copy);
1706                 if (pyptrs) {
1707                         MEM_freeN(pyptrs);
1708                 }
1709         }
1710
1711         /* And now, fix all vertices/edges/faces/loops pointers! */
1712         /* Verts' pointers, only edge pointers... */
1713         if (eptr_map) {
1714                 BM_ITER_MESH (ve, &iter, bm, BM_VERTS_OF_MESH) {
1715 /*                      printf("Vert e: %p -> %p\n", ve->e, BLI_ghash_lookup(eptr_map, ve->e));*/
1716                         if (ve->e) {
1717                                 ve->e = BLI_ghash_lookup(eptr_map, ve->e);
1718                                 BLI_assert(ve->e);
1719                         }
1720                 }
1721         }
1722
1723         /* Edges' pointers, only vert pointers (as we don't mess with loops!), and - ack! - edge pointers,
1724          * as we have to handle disklinks... */
1725         if (vptr_map || eptr_map) {
1726                 BM_ITER_MESH (ed, &iter, bm, BM_EDGES_OF_MESH) {
1727                         if (vptr_map) {
1728 /*                              printf("Edge v1: %p -> %p\n", ed->v1, BLI_ghash_lookup(vptr_map, ed->v1));*/
1729 /*                              printf("Edge v2: %p -> %p\n", ed->v2, BLI_ghash_lookup(vptr_map, ed->v2));*/
1730                                 ed->v1 = BLI_ghash_lookup(vptr_map, ed->v1);
1731                                 ed->v2 = BLI_ghash_lookup(vptr_map, ed->v2);
1732                                 BLI_assert(ed->v1);
1733                                 BLI_assert(ed->v2);
1734                         }
1735                         if (eptr_map) {
1736 /*                              printf("Edge v1_disk_link prev: %p -> %p\n", ed->v1_disk_link.prev,*/
1737 /*                                     BLI_ghash_lookup(eptr_map, ed->v1_disk_link.prev));*/
1738 /*                              printf("Edge v1_disk_link next: %p -> %p\n", ed->v1_disk_link.next,*/
1739 /*                                     BLI_ghash_lookup(eptr_map, ed->v1_disk_link.next));*/
1740 /*                              printf("Edge v2_disk_link prev: %p -> %p\n", ed->v2_disk_link.prev,*/
1741 /*                                     BLI_ghash_lookup(eptr_map, ed->v2_disk_link.prev));*/
1742 /*                              printf("Edge v2_disk_link next: %p -> %p\n", ed->v2_disk_link.next,*/
1743 /*                                     BLI_ghash_lookup(eptr_map, ed->v2_disk_link.next));*/
1744                                 ed->v1_disk_link.prev = BLI_ghash_lookup(eptr_map, ed->v1_disk_link.prev);
1745                                 ed->v1_disk_link.next = BLI_ghash_lookup(eptr_map, ed->v1_disk_link.next);
1746                                 ed->v2_disk_link.prev = BLI_ghash_lookup(eptr_map, ed->v2_disk_link.prev);
1747                                 ed->v2_disk_link.next = BLI_ghash_lookup(eptr_map, ed->v2_disk_link.next);
1748                                 BLI_assert(ed->v1_disk_link.prev);
1749                                 BLI_assert(ed->v1_disk_link.next);
1750                                 BLI_assert(ed->v2_disk_link.prev);
1751                                 BLI_assert(ed->v2_disk_link.next);
1752                         }
1753                 }
1754         }
1755
1756         /* Faces' pointers (loops, in fact), always needed... */
1757         BM_ITER_MESH (fa, &iter, bm, BM_FACES_OF_MESH) {
1758                 BM_ITER_ELEM (lo, &iterl, fa, BM_LOOPS_OF_FACE) {
1759                         if (vptr_map) {
1760 /*                              printf("Loop v: %p -> %p\n", lo->v, BLI_ghash_lookup(vptr_map, lo->v));*/
1761                                 lo->v = BLI_ghash_lookup(vptr_map, lo->v);
1762                                 BLI_assert(lo->v);
1763                         }
1764                         if (eptr_map) {
1765 /*                              printf("Loop e: %p -> %p\n", lo->e, BLI_ghash_lookup(eptr_map, lo->e));*/
1766                                 lo->e = BLI_ghash_lookup(eptr_map, lo->e);
1767                                 BLI_assert(lo->e);
1768                         }
1769                         if (fptr_map) {
1770 /*                              printf("Loop f: %p -> %p\n", lo->f, BLI_ghash_lookup(fptr_map, lo->f));*/
1771                                 lo->f = BLI_ghash_lookup(fptr_map, lo->f);
1772                                 BLI_assert(lo->f);
1773                         }
1774                 }
1775         }
1776
1777         /* Selection history */
1778         {
1779                 BMEditSelection *ese;
1780                 for (ese = bm->selected.first; ese; ese = ese->next) {
1781                         switch (ese->htype) {
1782                                 case BM_VERT:
1783                                         if (vptr_map) {
1784                                                 ese->ele = BLI_ghash_lookup(vptr_map, ese->ele);
1785                                                 BLI_assert(ese->ele);
1786                                         }
1787                                         break;
1788                                 case BM_EDGE:
1789                                         if (eptr_map) {
1790                                                 ese->ele = BLI_ghash_lookup(eptr_map, ese->ele);
1791                                                 BLI_assert(ese->ele);
1792                                         }
1793                                         break;
1794                                 case BM_FACE:
1795                                         if (fptr_map) {
1796                                                 ese->ele = BLI_ghash_lookup(fptr_map, ese->ele);
1797                                                 BLI_assert(ese->ele);
1798                                         }
1799                                         break;
1800                         }
1801                 }
1802         }
1803
1804         if (fptr_map) {
1805                 if (bm->act_face) {
1806                         bm->act_face = BLI_ghash_lookup(fptr_map, bm->act_face);
1807                         BLI_assert(bm->act_face);
1808                 }
1809         }
1810
1811         if (vptr_map)
1812                 BLI_ghash_free(vptr_map, NULL, NULL);
1813         if (eptr_map)
1814                 BLI_ghash_free(eptr_map, NULL, NULL);
1815         if (fptr_map)
1816                 BLI_ghash_free(fptr_map, NULL, NULL);
1817 }
1818
1819 /**
1820  * Use new memory pools for this mesh.
1821  *
1822  * \note needed for re-sizing elements (adding/removing tool flags)
1823  * but could also be used for packing fragmented bmeshes.
1824  */
1825 void BM_mesh_rebuild(
1826         BMesh *bm, const struct BMeshCreateParams *params,
1827         BLI_mempool *vpool_dst, BLI_mempool *epool_dst, BLI_mempool *lpool_dst, BLI_mempool *fpool_dst)
1828 {
1829         const char remap =
1830                 (vpool_dst ? BM_VERT : 0) |
1831                 (epool_dst ? BM_EDGE : 0) |
1832                 (lpool_dst ? BM_LOOP : 0) |
1833                 (fpool_dst ? BM_FACE : 0);
1834
1835         BMVert **vtable_dst = (remap & BM_VERT) ? MEM_mallocN(bm->totvert * sizeof(BMVert *), __func__) : NULL;
1836         BMEdge **etable_dst = (remap & BM_EDGE) ? MEM_mallocN(bm->totedge * sizeof(BMEdge *), __func__) : NULL;
1837         BMLoop **ltable_dst = (remap & BM_LOOP) ? MEM_mallocN(bm->totloop * sizeof(BMLoop *), __func__) : NULL;
1838         BMFace **ftable_dst = (remap & BM_FACE) ? MEM_mallocN(bm->totface * sizeof(BMFace *), __func__) : NULL;
1839
1840         const bool use_toolflags = params->use_toolflags;
1841
1842         if (remap & BM_VERT) {
1843                 BMIter iter;
1844                 int index;
1845                 BMVert *v_src;
1846                 BM_ITER_MESH_INDEX (v_src, &iter, bm, BM_VERTS_OF_MESH, index) {
1847                         BMVert *v_dst = BLI_mempool_alloc(vpool_dst);
1848                         memcpy(v_dst, v_src, sizeof(BMVert));
1849                         if (use_toolflags) {
1850                                 ((BMVert_OFlag *)v_dst)->oflags = bm->vtoolflagpool ? BLI_mempool_calloc(bm->vtoolflagpool) : NULL;
1851                         }
1852
1853                         vtable_dst[index] = v_dst;
1854                         BM_elem_index_set(v_src, index);  /* set_ok */
1855                 }
1856         }
1857
1858         if (remap & BM_EDGE) {
1859                 BMIter iter;
1860                 int index;
1861                 BMEdge *e_src;
1862                 BM_ITER_MESH_INDEX (e_src, &iter, bm, BM_EDGES_OF_MESH, index) {
1863                         BMEdge *e_dst = BLI_mempool_alloc(epool_dst);
1864                         memcpy(e_dst, e_src, sizeof(BMEdge));
1865                         if (use_toolflags) {
1866                                 ((BMEdge_OFlag *)e_dst)->oflags = bm->etoolflagpool ? BLI_mempool_calloc(bm->etoolflagpool) : NULL;
1867                         }
1868
1869                         etable_dst[index] = e_dst;
1870                         BM_elem_index_set(e_src, index);  /* set_ok */
1871                 }
1872         }
1873
1874         if (remap & (BM_LOOP | BM_FACE)) {
1875                 BMIter iter;
1876                 int index, index_loop = 0;
1877                 BMFace *f_src;
1878                 BM_ITER_MESH_INDEX (f_src, &iter, bm, BM_FACES_OF_MESH, index) {
1879
1880                         if (remap & BM_FACE) {
1881                                 BMFace *f_dst = BLI_mempool_alloc(fpool_dst);
1882                                 memcpy(f_dst, f_src, sizeof(BMFace));
1883                                 if (use_toolflags) {
1884                                         ((BMFace_OFlag *)f_dst)->oflags = bm->ftoolflagpool ? BLI_mempool_calloc(bm->ftoolflagpool) : NULL;
1885                                 }
1886
1887                                 ftable_dst[index] = f_dst;
1888                                 BM_elem_index_set(f_src, index);  /* set_ok */
1889                         }
1890
1891                         /* handle loops */
1892                         if (remap & BM_LOOP) {
1893                                 BMLoop *l_iter_src, *l_first_src;
1894                                 l_iter_src = l_first_src = BM_FACE_FIRST_LOOP((BMFace *)f_src);
1895                                 do {
1896                                         BMLoop *l_dst = BLI_mempool_alloc(lpool_dst);
1897                                         memcpy(l_dst, l_iter_src, sizeof(BMLoop));
1898                                         ltable_dst[index_loop] = l_dst;
1899                                         BM_elem_index_set(l_iter_src, index_loop++); /* set_ok */
1900                                 } while ((l_iter_src = l_iter_src->next) != l_first_src);
1901                         }
1902                 }
1903         }
1904
1905 #define MAP_VERT(ele) vtable_dst[BM_elem_index_get(ele)]
1906 #define MAP_EDGE(ele) etable_dst[BM_elem_index_get(ele)]
1907 #define MAP_LOOP(ele) ltable_dst[BM_elem_index_get(ele)]
1908 #define MAP_FACE(ele) ftable_dst[BM_elem_index_get(ele)]
1909
1910 #define REMAP_VERT(ele) { if (remap & BM_VERT) { ele = MAP_VERT(ele); }} ((void)0)
1911 #define REMAP_EDGE(ele) { if (remap & BM_EDGE) { ele = MAP_EDGE(ele); }} ((void)0)
1912 #define REMAP_LOOP(ele) { if (remap & BM_LOOP) { ele = MAP_LOOP(ele); }} ((void)0)
1913 #define REMAP_FACE(ele) { if (remap & BM_FACE) { ele = MAP_FACE(ele); }} ((void)0)
1914
1915         /* verts */
1916         {
1917                 for (int i = 0; i < bm->totvert; i++) {
1918                         BMVert *v = vtable_dst[i];
1919                         if (v->e) {
1920                                 REMAP_EDGE(v->e);
1921                         }
1922                 }
1923         }
1924
1925         /* edges */
1926         {
1927                 for (int i = 0; i < bm->totedge; i++) {
1928                         BMEdge *e = etable_dst[i];
1929                         REMAP_VERT(e->v1);
1930                         REMAP_VERT(e->v2);
1931                         REMAP_EDGE(e->v1_disk_link.next);
1932                         REMAP_EDGE(e->v1_disk_link.prev);
1933                         REMAP_EDGE(e->v2_disk_link.next);
1934                         REMAP_EDGE(e->v2_disk_link.prev);
1935                         if (e->l) {
1936                                 REMAP_LOOP(e->l);
1937                         }
1938                 }
1939         }
1940
1941         /* faces */
1942         {
1943                 for (int i = 0; i < bm->totface; i++) {
1944                         BMFace *f = ftable_dst[i];
1945                         REMAP_LOOP(f->l_first);
1946
1947                         {
1948                                 BMLoop *l_iter, *l_first;
1949                                 l_iter = l_first = BM_FACE_FIRST_LOOP((BMFace *)f);
1950                                 do {
1951                                         REMAP_VERT(l_iter->v);
1952                                         REMAP_EDGE(l_iter->e);
1953                                         REMAP_FACE(l_iter->f);
1954
1955                                         REMAP_LOOP(l_iter->radial_next);
1956                                         REMAP_LOOP(l_iter->radial_prev);
1957                                         REMAP_LOOP(l_iter->next);
1958                                         REMAP_LOOP(l_iter->prev);
1959                                 } while ((l_iter = l_iter->next) != l_first);
1960                         }
1961                 }
1962         }
1963
1964         for (BMEditSelection *ese = bm->selected.first; ese; ese = ese->next) {
1965                 switch (ese->htype) {
1966                         case BM_VERT:
1967                                 if (remap & BM_VERT) {
1968                                         ese->ele = (BMElem *)MAP_VERT(ese->ele);
1969                                 }
1970                                 break;
1971                         case BM_EDGE:
1972                                 if (remap & BM_EDGE) {
1973                                         ese->ele = (BMElem *)MAP_EDGE(ese->ele);
1974                                 }
1975                                 break;
1976                         case BM_FACE:
1977                                 if (remap & BM_FACE) {
1978                                         ese->ele = (BMElem *)MAP_FACE(ese->ele);
1979                                 }
1980                                 break;
1981                 }
1982         }
1983
1984         if (bm->act_face) {
1985                 REMAP_FACE(bm->act_face);
1986         }
1987
1988 #undef MAP_VERT
1989 #undef MAP_EDGE
1990 #undef MAP_LOOP
1991 #undef MAP_EDGE
1992
1993 #undef REMAP_VERT
1994 #undef REMAP_EDGE
1995 #undef REMAP_LOOP
1996 #undef REMAP_EDGE
1997
1998         /* Cleanup, re-use local tables if the current mesh had tables allocated.
1999          * could use irrespective but it may use more memory then the caller wants (and not be needed). */
2000         if (remap & BM_VERT) {
2001                 if (bm->vtable) {
2002                         SWAP(BMVert **, vtable_dst, bm->vtable);
2003                         bm->vtable_tot = bm->totvert;
2004                         bm->elem_table_dirty &= ~BM_VERT;
2005                 }
2006                 MEM_freeN(vtable_dst);
2007                 BLI_mempool_destroy(bm->vpool);
2008                 bm->vpool = vpool_dst;
2009         }
2010
2011         if (remap & BM_EDGE) {
2012                 if (bm->etable) {
2013                         SWAP(BMEdge **, etable_dst, bm->etable);
2014                         bm->etable_tot = bm->totedge;
2015                         bm->elem_table_dirty &= ~BM_EDGE;
2016                 }
2017                 MEM_freeN(etable_dst);
2018                 BLI_mempool_destroy(bm->epool);
2019                 bm->epool = epool_dst;
2020         }
2021
2022         if (remap & BM_LOOP) {
2023                 /* no loop table */
2024                 MEM_freeN(ltable_dst);
2025                 BLI_mempool_destroy(bm->lpool);
2026                 bm->lpool = lpool_dst;
2027         }
2028
2029         if (remap & BM_FACE) {
2030                 if (bm->ftable) {
2031                         SWAP(BMFace **, ftable_dst, bm->ftable);
2032                         bm->ftable_tot = bm->totface;
2033                         bm->elem_table_dirty &= ~BM_FACE;
2034                 }
2035                 MEM_freeN(ftable_dst);
2036                 BLI_mempool_destroy(bm->fpool);
2037                 bm->fpool = fpool_dst;
2038         }
2039 }
2040
2041 /**
2042  * Re-allocates mesh data with/without toolflags.
2043  */
2044 void BM_mesh_toolflags_set(BMesh *bm, bool use_toolflags)
2045 {
2046         if (bm->use_toolflags == use_toolflags) {
2047                 return;
2048         }
2049
2050         const BMAllocTemplate allocsize = BMALLOC_TEMPLATE_FROM_BM(bm);
2051
2052         BLI_mempool *vpool_dst = NULL;
2053         BLI_mempool *epool_dst = NULL;
2054         BLI_mempool *fpool_dst = NULL;
2055
2056         bm_mempool_init_ex(
2057                 &allocsize, use_toolflags,
2058                 &vpool_dst, &epool_dst, NULL, &fpool_dst);
2059
2060         if (use_toolflags == false) {
2061                 BLI_mempool_destroy(bm->vtoolflagpool);
2062                 BLI_mempool_destroy(bm->etoolflagpool);
2063                 BLI_mempool_destroy(bm->ftoolflagpool);
2064
2065                 bm->vtoolflagpool = NULL;
2066                 bm->etoolflagpool = NULL;
2067                 bm->ftoolflagpool = NULL;
2068         }
2069
2070         BM_mesh_rebuild(
2071                 bm,
2072                 &((struct BMeshCreateParams){.use_toolflags = use_toolflags,}),
2073                 vpool_dst, epool_dst, NULL, fpool_dst);
2074
2075         bm->use_toolflags = use_toolflags;
2076 }